Customize Symfony Form Builder Error Message in Twig Template

I’m building a form to gather credit card information and I want to customize the error messages displayed on the form.

I’m sure I can do this with form theming, and that’s great, but I just wanted a down and dirty, in the template, spitting out custom error messages solution. Of course, normally, I would put my entity validation stuff in the entity class, but in this case, the form was not tied to an entity. I’m not actually saving the credit card information, I’m sending it to Paypal.

It took a bit of digging to solve this problem. I assumed that I could just specify an error message when building the form in my form builder class, but apparently that’s not the case.

So here’s how I did it for the credit card expiration field in the Twig template.

<fieldset>
{% if form.ccexp.vars.errors|length >0 %}
Oops, the credit card expiration date is invalid, please specify the expiration date in this format mm/YYYY (e.g. 1/2020 for January 2020).
{% endif %}
{{ form_label(form.ccexp) }}
{{ form_widget(form.ccexp, {attr: { 
        'data-format': "MM-yyyy" },
    }) }}
</fieldset>
Share Button

One Comment

Comments are closed.