在symfony形式事件中的翻译

时间:2017-05-29 16:51:37

标签: php symfony

在自定义formType中,我有一个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'));
}
});

FormError()的第一个参数是"翻译的错误消息",所以, 如果我不想将翻译器作为参数传递给formType,我就无法在我的formType中获得翻译器。如何翻译此自定义错误?

我的中间解决方案是翻译所有表单错误并将它们作为选项传递给表单。这是一个例子:

在控制器中:

....
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)]);
}
....

在formType中,类似于:

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()
        ));

}

我宁愿选择更优雅的解决方案

任何帮助将不胜感激

0 个答案:

没有答案