将表单转换为自定义设置区域设置


Translate form to custom set locale

嗨,我有一个用例,我想把表单转换为自定义语言环境,然后在请求

我试着做一些像

$tmpLocale = $request->getLocale();
$request->setLocale('es');
$form = $this->createForm(new DataType());
$formView = $form->renderView();
$request->setLocale($tmpLocale);
return $this->render('AppBundle:Data:edit.html.twig', array(
    'data' => $data,
    'form' => $formView,
));

但是它不工作,我怎么能使它工作这个?我需要表单标签被翻译成这个自定义语言环境

在表单呈现时进行表单标签转换。如果这是应用程序中的常见用例,那么您可以考虑通过转换标签来覆盖该行为:

创建一个新的表单类型扩展,并将locale变量传递给模板布局:

class FormTypeExtension extends AbstractTypeExtension
{
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['locale'] = $options['locale'];
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        // define locale option for each form field.
        // if null the labels are translates to current locale.
        $resolver->setDefaults(array('locale' => null));
    }
    public function getExtendedType()
    {
        return 'form';
    }
}
服务:

services:
    app.form.extension.locale:
        class: AppBundle'Form'Extension'FormTypeExtension
        tags:
            - { name: form.type_extension, alias: form }

接下来,覆盖所有包含trans()函数的表单块,并添加locale作为第三个参数:

{{ label|trans({}, translation_domain, locale) }}
示例:

{%- block form_label -%}
    {% if label is not same as(false) -%}
        {# ... #}
        <label ... >{{ translation_domain is same as(false) ? label : label|trans({}, translation_domain, locale) }}</label>
    {%- endif -%}
{%- endblock form_label -%}

之后,您可以为每个表单字段使用locale选项:

$form->add('name', null, array('locale' => 'es'));

看看TranslatorInterface,它的第四个参数是locale,您可以直接使用它来翻译消息。您需要将表单类型注册为服务,向其注入translator(可能还有自定义语言环境),并使用该语言环境翻译其中的所有消息。

我通过简单地更改翻译服务的区域设置来实现。

$tmpLocale = $this->get('translator')->getLocale();
$this->get('translator')->setLocale('es');
$form = $this->createForm(new DataType());
$formView = $form->createView();
$this->get('translator')->setLocale($tmpLocale);

这个很好。不需要高级解决方案