【问题标题】:Dynamically translate Forms depending on local根据本地动态翻译表单
【发布时间】:2018-04-18 10:36:20
【问题描述】:

所以我正在使用 symfony 2.8 创建一个多语言网站,但在翻译表单时遇到了这个问题,我设法使用 translation_domain 选项更改标签,如下例所示:

->add('save','submit',
            array('label'=>'btn.send',
                'translation_domain' => 'FrontBundle',
                'attr'=>array(
                    'class'=>'btn btn-blue',
        )))

但是我在翻译实体类型时遇到了问题,因为名称来自数据库,所以我添加了其他语言的字段 像这样:

name_fr ,name_en , name_es ,...

问题是如何将它们与表单一起使用,经过数小时的谷歌搜索后,即使我不喜欢它,我也找到了这个解决方案。

使用 documentation 我将 _local 从请求传递到我的表单,如下所示:

联系人控制器:

 public function contactAction(Request $request)
{
    $contact = new contact();
    $contact->setSendTime(new \DateTime('now'));
    $form = $this->createForm(new contactType(), $contact,array('lang'=>$request->getLocale()));
    //...
}

联系人类型:

class TaskType extends AbstractType
{
    // ...

    public function configureOptions(OptionsResolver $resolver)
    {
        // ...

        $resolver->setRequired('lang');
    }
    //...
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $local = $options['lang'];
        // ...
        $builder

            ->add('civility', 'entity', array(
                'class'=>'BackBundle\Entity\civility',
                //use this
                'property' => $local == 'fr'?'name_fr':'name_en',
                //or this or dont use them both
                //'choice_label' => 'name',
                'label'=>'Civilité:',
                'expanded'=>true,
            ))
            /...
            ;

    }

}

我想知道是否有一个更简洁更好的解决方案来翻译表单中的实体

【问题讨论】:

标签: php symfony symfony-forms


【解决方案1】:

您可以使用 Symfony 表单事件来动态管理表单数据。看一下这个 https://symfony.com/doc/2.8/form/dynamic_form_modification.html

这似乎正是您所需要的。您可以将区域设置从您的控制器传递给您的表单(作为一个选项),并在表单类中添加一个事件侦听器来侦听事件(选择最适合您需要的一个,我最好的猜测是您需要 PRE_SET_DATA 事件 -一种操作数据库中的数据)并根据传递的区域设置选项,您可以修改您需要的表单字段。

【讨论】:

    【解决方案2】:

    所以我读到@dbrumann 给我的Translatable from the DoctrineExtensions,我在管理端将它与Sonata Translation Bundle 并排使用,它工作得很好。 如果有人对配置有任何疑问,请发表评论

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      相关资源
      最近更新 更多