如何在createView上翻译表单?

时间:2017-04-24 15:05:10

标签: symfony symfony-forms

我创建了一个表单:

$data = new Task();
$form = $this->createForm(TaskType::class, $data);

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class, [
                'label' => 'name'
            ])
        /* .... */
    }
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
       'data_class' => Task::class,
        'translation_domain' => 'task'
    ]);
}

$form->createView()之后我的标签形式未翻译。 在config.yml中我启用了翻译器:

framework:
    translator: { fallbacks: ['%locale%'] }

在app / Resources / translations / task.ru.yml:

name: Название задачи
responsible: Ответственный
status: Статус
dateStart: Начало
planDateEnd: Окончание
description: Описание
dayCount: Число дней
file: Документы
notifications: Уведомления
watchers: Наблюдателе
complete: '% завершения'

我可以在表单类中翻译没有send translator组件的标签吗?

1 个答案:

答案 0 :(得分:0)

您可以在$ form-> createView()之后手动翻译标签。

(未经测试的代码)

$view = $form->createView();
$trans = $this->get('translator');

foreach ($view->children as $name => $child)
{
    if (isset($child->vars['label']))
    {
        $view->children[$name]->vars['label'] = $trans->trans($child->vars['label']);
    }
}