在表单定义UserType.php中获取并使用转换程序

时间:2015-08-10 20:05:25

标签: symfony

我有一个UserType.php个用户注册。标签的翻译没有问题,但没有翻译invalid_message

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text', array('label' => 'translate.label.name'))
            ->add('email', 'email', array('label' => 'translate.label.email'))
            ->add('password', 'repeated', array(
                'type' => 'password',
                'first_name' => 'password',
                'second_name' => 'confirm',
                'invalid_message' => 'translate.invalid.message.password.match',
                'first_options'   => array('label' => 'translate.label.password'),
                'second_options'  => array('label' => 'translate.label.repeat.password'),
            ))
            ->add('submit', 'submit', array('label' => 'translate.label.sign.up'))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Digisolution\UserBundle\Entity\User'
        ));
    }

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

如果我制作相同的表单,我的控制器错误可以翻译为:

$this->get('translator')->trans('translate.invalid.message.password.match')

但在我的UserType中,您无法使用$ this-> get ('translator')

访问翻译人员

我需要在UserType.php中实例化哪个类来使用它?

3 个答案:

答案 0 :(得分:1)

将您的表单类型声明为服务,注入multiFormatReader服务并像这样使用它:

reset()

实际上translator方法只调用指定的服务,例如... 'invalid_message' => $this->translator->trans('translate.invalid.message.password.match', HERE_GO_OPTIONAL_PARAMETERS), ... - 只是从服务容器返回翻译服务。

另外,更好的方法是将验证错误消息放入$this->get()文件,因为验证错误在验证器转换域中被翻译,但看起来像there are some issues我认为

答案 1 :(得分:1)

RESOLVE:在控制器中:

$form = $this->createForm(new UserType($this->get('translator')), $user);

传递翻译器实例工作正常

表单类中的

class UserType extends AbstractType{
private $translator;
public function __construct($translator){
    $this->translator =$translator;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$translator = $this->translator;
$builder
        ->add('name', 'text', array('label' => 'translate.label.name'))
        ->add('email', 'email', array('label' => 'translate.label.email'))
        ->add('password', 'repeated', array(
            'type' => 'password',
            'first_name' => 'password',
            'second_name' => 'confirm',
            'invalid_message' => $translator->trans('translate.invalid.message.password.match'),
            'first_options'   => array('label' => 'translate.label.password'),
            'second_options'  => array('label' => 'translate.label.repeat.password'),
        ))
...
...
}

答案 2 :(得分:0)

标签已自动翻译。