Kal Kal - 1 year ago 151
PHP Question

Symfony Form Field Valid Even With Errors?

I have applied a form error to a form collection field (custom fieldset).

if ($this->isFieldset($form, $field) && !empty($error)) {
new FormError(
ucfirst(str_replace('_', ' ', $field)) . ' is invalid.')

The form has an error applied to it but is still marked as valid?

enter image description here

As you see in the controller the form has the errors on the about_you child before isValid is called?

enter image description here

Any suggestions why?

Answer Source

I dug through the code and found this snippet:

public function buildView(FormView $view, FormInterface $form, array $options)

    $view->vars = array_replace($view->vars, array(
        'errors' => $form->getErrors(),
        'valid' => $form->isSubmitted() ? $form->isValid() : true,  //<=== HERE
        'value' => $form->getViewData(),
        'data' => $form->getNormData(),
        'required' => $form->isRequired(),
        'size' => null,
        'label_attr' => $options['label_attr'],
        'compound' => $form->getConfig()->getCompound(),
        'method' => $form->getConfig()->getMethod(),
        'action' => $form->getConfig()->getAction(),
        'submitted' => $form->isSubmitted(),

This seems to be the only place where valid is set. Note that it happens during buildView! Everything afterwards will not effect the value of valid.

However, not everything is in vain as you can simply use $form->isValid() to check, if the form is currently valid, as we can see in the following snippet:

public function isValid()
    if (!$this->submitted) {
        return false;

    if ($this->isDisabled()) {
        return true;

    return 0 === count($this->getErrors(true));