mbajorek mbajorek - 5 months ago 65
PHP Question

Symfony forms, error bubbling

I have a problem with forms' error bubbling.
One field in my form is defined like this:

$formBuilder->add('title','text',
'required' => true,
'error_bubbling' => false,
)
)


I would like to add a validator like this to this field:

/**
* @Assert\True(message = "Bad title.")
*/
public function getTitleCorrect()
{
/* ... */
return false;
}


It works ok, but the error message shows up on top of the form, not in the field row.

In the Twig template this error message is rendered by
{{form_errors(form)}}
as a global error. When I use
{{form_errors(form.title)}}
, it does not print my error.

What can I do to change the assignment of the error?

Answer

Messages are attached to a field only when validator is attached to corresponding property. Your validator is attached to a method of the class so error is indeed global.

You should to something like that:

use ...\TitleValidator as AssertTitleValid;

class MyEntity
{
    /**
     * @AssertTitleValid
     */
    private $title;
}

And create your own TitleValidator class.

Comments