'Translation in symfony form event
In a custom formType I have an evenListener
$builder->add('somefield');
....
//surveyor and surveyorid can't be empty
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
if($data['surveyor']=='' && $data['surveyorid']==''){
form = $event->getForm();
$form->addError(new \Symfony\Component\Form\FormError('esto.esta.mal'));
}
});
The first argument of FormError() is "The translated error message", so, if If I don't like to pass the translator as argument to the formType and I can't get the translator in my formType. How can I translate this custom error?
My intermediate solution is to translate all form errors and pass them as options to the form. This is a sort example:
In controller:
....
editAction(Request $request)
{
//translate errors
$errors = [
'form.map.surveyor.incomplete'=>$this->get('translator')->trans('form.map.surveyor.incomplete'),
'form.map.surveyor.chooseonefield'=>$this->get('translator')->trans('form.map.surveyor.chooseonefield'),
];
//
$form = $this->createForm( $formType, $entity, ['errors'=>$errors]);
....
if ($form->isValid()) {
...
}else{errors to string
return new \Symfony\Component\HttpFoundation\JsonResponse(['e'=>(string) $form->getErrors(true, false)]);
}
....
In formType, something like:
public function buildForm(FormBuilderInterface $builder, array $defaults)
{
$errors = $defaults['errors'];//translated errors
....
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($errors) {
$data = $event->getData();
if($data['surveyor']=='' && $data['surveyorid']==''){
$form = $event->getForm();
$form->addError(new \Symfony\Component\Form\FormError( sprintf($errors['form.map.surveyor.incomplete'] )));
}
if($data['surveyor']!=='' && $data['surveyorid']!==''){
$form = $event->getForm();
$form->addError(new \Symfony\Component\Form\FormError($errors['form.map.surveyor.chooseonefield']));
}
});
....
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Gpt\MyBundle\Entity\Mapsurveyor',
'errors'=>array()
));
}
I would rather a more elegant solution
Any help will be appreciated
EDIT
Autowire is available in constructor formTypes
class MyformType extends AbstractType
{
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator= $translator;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
