Translating validation error messages in a custom FormType

2.7k Views Asked by At

I have the current situation

<?php

namespace MyBundle\Form\Type;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;

class MyFormType extends AbstractType implements ContainerAwareInterface
{
    use \Symfony\Component\DependencyInjection\ContainerAwareTrait;

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $translator = $this->container->get('translator');

        $builder->add('my-field', 'text', [
            'constraints' => [
                new Assert\NotBlank([
                    'message' => $translator->trans('%field% should not be blank.', ['%field%' => $translator->trans('MyFieldName')]),
                ]),
            ],
        ]);
    }

    public function getName()
    {
        return 'my_form';
    }
}

This example already works, I am trying to refactor it so I don't have to include the container (or the translator) in it.

The challenge lies in keeping

  • '%field% should not be blank.' and
  • 'MyFieldName'

as the only two translatable strings, 'cause it's likely that MyFieldName is going to be translated already (like for labels) leaving '%field% should not be blank.' as a generic message valid for any field in the site.

2

There are 2 best solutions below

1
On

Past into constraints 'attr' => array( 'placeholder' => 'Message', )

1
On

If you have activated the translator in symfony framework config by uncommenting this line :

#translator: { fallbacks: [%locale%] }

in config.yml, all error messages of violations set by the validator are translated by default with values from validators domain.

You should us either app/Resources/translations/validators.(_format) or src/(Acme/)*Bundle/Resources/translations/validators.(_format) to define your custom messages and once done clear your cache.

example :

# app/Resources/translations/validators.yml
my_form:
    errors:
       my_field:
           not_blank: My field should not be blank

and

// FormType
$builder->add('my-field', 'text', [
        'constraints' => [
            new Assert\NotBlank([
                'message' => 'my_form.errors.my_field.not_blank',
            ]),
        ],
    ]);

Error messages from validator will be automatically translated.

See http://symfony.com/doc/current/book/translation.html#translating-constraint-messages