使用表单主题添加帮助块

时间:2015-11-18 10:50:38

标签: php symfony twig symfony-2.7

在我的应用中,我尝试使用官方Symfony2 cookbook中的提示来显示表单帮助块。这是我的代码:

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

{% block form_widget_simple %}
  {{ block('base_form_widget_simple') }}

  {{ dump(help) }}
  {% if help is defined %}
     <span class="help">{{ help }}</span>
  {% endif %}
{% endblock %}

使用这个主题:

{{ form_row(form.pageTitle, {'help': 'some help'}) }}

这样我就会收到错误Variable "help" does not exist。我错过了什么想法? 附:我使用Symfony 2.7.1。

1 个答案:

答案 0 :(得分:2)

创建扩展表单类型的表单类型扩展名:

namespace Acme\AppBundle\Form\Extension;

use ...

class FieldTypeHelpExtension extends AbstractTypeExtension
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->setAttribute('help', $options['help']);
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['help'] = $options['help'];
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'help' => null
        ]);
    }

    public function getExtendedType()
    {
        return 'form';
    }

}

将扩展名定义为服务:

acme_app.form.extension.field_type_help:
        class: Acme\AppBundle\Form\Extension\FieldTypeHelpExtension
        tags:
            - { name: form.type_extension, alias: form }

创建一个从div布局扩展的模板:

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

{% block field_help %}
    {% if help is defined and help %}
        <p class="help-block">{{ help|trans }}</p>
    {% endif %}
{% endblock field_help %}

{% block integer_widget %}
    {{ parent() }}
    {{ block('field_help') }}
{% endblock integer_widget %}

{% block form_widget %}
    {{ parent() }}
    {{ block('field_help') }}
{% endblock form_widget %}

在config.yml

上将此模板配置为表单主题
twig:
    form_themes:
        - 'Form/fields.html.twig'

现在,您可以在模板上渲染字段时使用它:

{{ form_widget(form.name, { 'help': 'this is help' }) }}

或在您的表单类型中:

$form->add('name', 'text', ['help' => 'this is help']);