Kal
Kal

Reputation: 2299

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)) {
    $form->get($field)->addError(
        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?

Upvotes: 2

Views: 747

Answers (1)

Emanuel Oster
Emanuel Oster

Reputation: 1306

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));
}

Upvotes: 2

Related Questions