Question

I would like to display error message in the field it is for. I know how to put the error message into the field, but I want to find a dynamic way to check after re-submittion, if the inserted value is not the error message itself. I use doctrine annotations. For example if the field is "title", the error message would be "The title must be filled!". So the title field is not empty anymore, I click submit again, and it is valid now. I don't want to check every single field like if $entity->getTitle() == "The title must be filled" ... I've managed to do this with not displayed error divs in the twig, and jquery, but I want to know if there is a better way to do this from the controller? Thanks

Was it helpful?

Solution

You're asking how to correctly do something the wrong way... If the input value is not the value you want processed, it should have never been the value to begin with. That being said, I'm sure you have your reasons...

You need to listen to FormEvents::BIND_CLIENT_DATA and clear the form data if it matches your error string.

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('title');
    $builder->get('title')->addEventListener(
        FormEvents::BIND_CLIENT_DATA,
        function(FilterDataEvent $event)
        {
            if ('The title must be filled' == $event->getData()) {
                $event->setData('');
            }
        },
    );

If you want to apply this behavior globally you need to attach this listener using a form type extension that extends 'field'. You will also need to introspect all of the possible validation error messages for the current field using the validator and pass these through the translator, then compare the results with the event data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top