How to Customize Symfony Form Widget Error Messages When Not Using an Entity

Earlier today I was researching how to customize error messages in a Symfony form type that isn’t linked to an entity.

Initially I wanted to do this in the form builder class, but I couldn’t find the solution. Then I found a solution to do what I need in Twig and that was fine.

But now I’ve found the correct solution, the one that works regardless of where my form is rendered in my application. You can modify the error message in the form builder, it’s actually quite simple, I don’t know why I couldn’t find this earlier today.

$builder->add('firstname', TextType::class, array(
      'label' => 'First Name',
       'required' => TRUE,
       'constraints'=>new NotBlank(array('message'=>'Please enter a first name'))
))

This is the more correct way to do this when not using an entity. But my other solution is nice and dirty, and requires less work in some instances, but it’s less portable.

To close the loop on this one, I actually did figure out how to put my error messaging in the form builder, which in this case, seems appropriate.

For the credit card expiration date, for instance, I’m doing this.

->add('ccexp', TextType::class, array(
        'label' => 'Card Expiration',
        'required' => TRUE,
        'constraints' => new Regex(array(
            'pattern' => '/^(0[1-9]|1[0-2])\/|\-?([0-9]{4}|[0-9]{2})$/',
            'message' => 'The credit card expiration date is not valid. Enter MM-YYYY, such as 01-2020 for January 2020.'
        ))
Share Button