我试图在Symfony(2.7)中创建一个自定义表单类型,以便为我的某些表单字段添加help_block(Boostrap 3样式)。在symfony2中翻译自定义表单类型
我跟着这个页面的说明: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 %}
在此先感谢您的帮助,
问候
我用我的扩展代码更新了我的文章。即使在清除缓存后,我的字段也没有标记为可翻译的。 –
当你使用动态字符串时,你需要在数据库中进行翻译(或者他们来自的地方,比如文件)。翻译文件仅用于* static *翻译。 – nakashu