在symfony2中翻译自定义表单类型

时间:2015-10-20 19:31:50

标签: php forms symfony translation symfony-2.7

我试图在Symfony(2.7)中创建自定义表单类型,以便为我的某些表单字段添加help_block(Boostrap 3样式)。

我按照此页面说明操作:http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html

显示没问题,help_block工作正常,但不可翻译,(dev栏没有显示任何缺失的翻译)。所以我的问题是:如何使自定义表单类型可翻译,如标签选项,如果可能,在与表单相同的translation_domain中?

这是扩展代码:

<?php

namespace WIC\MasterBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Add a BootStrap Help block to any form field
 */
class HelpTextExtension extends AbstractTypeExtension
{

    /**
     * Returns the name of the type being extended.
     *
     * @return string The name of the type being extended
     */
    public function getExtendedType() {
        return 'form';
    }

    /**
     * Add the help_text option
     *
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefined(array('help_text'));
        $resolver->setDefault('help', null);
    }

    /**
     * Pass the Help Text to the view
     *
     * @param FormView $view
     * @param FormInterface $form
     * @param array $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options) {
        $view->vars['help_text'] = $form->getConfig()->getAttribute('help_text');
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        if (array_key_exists('help_text', $options)) {
            $builder->setAttribute('help_text', $options['help_text']);
        }
    }

}

我的模板覆盖:

{% extends 'bootstrap_3_horizontal_layout.html.twig' %}

{% block form_row -%}
    {% spaceless %}
        <div class="form-group{% if (not compound or force_error|default(false)) and not valid %} has-error{% endif %}">
            {{ form_label(form) }}
            <div class="{{ block('form_group_class') }}">
                {{ form_widget(form) }}
                {{ form_errors(form) }}
                {% if help_text is not null %}
                    <span class="help-block">{{ help_text }}</span>
                {% endif %}
            </div>
        </div>
    {% endspaceless %}
{%- endblock form_row %}

提前感谢您的帮助,

祝你好运

2 个答案:

答案 0 :(得分:5)

您可以像在其他地方一样添加翻译,只需填写标签即可。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title', 'text', [
            'label' => 'rpr.page.title', // <- any string can be there
        ]);
}

默认翻译域名为“邮件”,可将“translation_domain”添加到configureOptions

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
       'data_class'         => 'Acme\Entity\DemoEntity',
       'translation_domain' => 'forms'
    ]);
}

当然,您需要在正确的位置创建翻译文件:AcmeBundle\Resources\translations

需要注意的重要事项: - 当您在AcmeBundle\Resources\translations中创建新的翻译文件时,如表格.de.yml,需要即使在开发过程中也要清除缓存。

这里的文档:http://symfony.com/doc/current/reference/forms/types/form.html#translation-domain

答案 1 :(得分:1)

a)设置locale参数并在config.yml中启用转换

parameters:
    locale: en

framework:
    #esi:             ~
    translator:      { fallbacks: ["%locale%"] }

b)创建自定义表单类型。我从docs创建了GenderType。

c)使用构造函数扩展自定义表单类型以访问转换程序并在您希望的位置使用translater:

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\Translator;

class GenderType extends AbstractType
{
    private $translator;

    public function __construct(Translator $translator)
    {
        $this->translator = $translator;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'choices' => array(
                'm' => $this->translator->trans('user.male'),
                'f' => $this->translator->trans('user.female'),
            )
        ));
    }

    public function getParent()
    {
        return 'choice';
    }

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

d)创建您的字段类型即服务

// app/config/services.yml
services:
    app.form.type.gender:
        class: AppBundle\Form\Type\GenderType
        arguments:
            - @translator.default
        tags:
            - { name: form.type, alias: gender }

e)创建翻译文件:

// src/AppBundle/Resources/translations/user.en.yml
user:
    creation: Create User
    gender: Gender
    male: Male
    female: Female

f)扩展您的formType(例如UserType)。确保您通过&#39;性别&#39;传递字段类型。您在步骤d中创建的服务别名。同时为每个字段设置标签 translation_domain 选项。

// src/AppBundle/Form/UserType.php
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use AppBundle\Form\Type\GenderType;

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('gender', 'gender', array('label' => 'user.gender', 'translation_domain' => 'user'))
            // and more fields
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'appbundle_user';
    }
}

g)将trans_default_domain添加到您的twig模板并翻译您想要翻译的内容。例如:

{% extends '::base.html.twig' %}

{% trans_default_domain 'user' %}

{% block body -%}
    <h1>{{ 'user.creation'|trans }}</h1>

    {{ form(form) }}

{% endblock %}