Answer the question
In order to leave comments, you need to log in
How to set translation domain for custom errors in form validators?
There is a regular form (a Symfony Forms component) with some fields and a custom translation domain is configured for them. The standard rules from Symfony Validation apply to the fields.
Question: how can I set a custom translation domain to translate validator error messages? You can add translations to the validators.en.yml file , but what I really need is to be able to specify the necessary translation domain for different forms.
Form example (shortened):
class RegistrationForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('login', TextType::class, [
'label' => 'registration.details.label.login',
'constraints' => [
new NotBlank(['message' => 'registration.details.error.login.required']),
new Regex([
'pattern' => '/^[a-z0-9_]+/i',
'message' => 'registration.details.error.login.wrong_symbols'
]),
],
])
...
}
public function configureOptions(OptionsResolver $resolver)
{
// Set custom translation domain for this form
$resolver->setDefaults(['translation_domain' => 'users']);
}
public function getExtendedType()
{
return FormType::class;
}
}
Answer the question
In order to leave comments, you need to log in
Some strange "standard" form type. It doesn't seem to have a getExtendedType() method...
As for validation.
Use validation groups, the form will be cleaner, and the validation object will be available in the context of the validator.
In setDefaults , you have a default value, so to change the domain in another form that reuses this type, you just need to override this value.
$this->createForm(RegistrationForm:class, null, ['translation_domain' => 'foo'])
$this->createForm(RegistrationForm:class, null, ['translation_domain' => 'bar'])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question