1

尝试自定义 Symfony2 表单以生成类似于以下示例的 html 代码:

<div class="cform_box">
  <div><label>First name:</label></div>
  <input name="" type="text" id="" class="TextBox" />
</div>
<div class="cform_box" style="height:auto">
   <div><label>Message:</label></div>
  <textarea name="" rows="10" cols="38" id="" class="TextBox" style="height:100px;" /></textarea>
</div>

我的表单代码:

$builder->add('name', 'text', array('label' =>'First Name:'));
$builder->add('message', 'textarea', array('label' =>'Message:'));

模板contact.html.twig

{% form_theme form _self %}
{% block text_widget %}
{% spaceless %}
    <input type="text" class='TextBox' {% if value is not empty %}value="{{ value }}"     {% endif %}/>
{% endspaceless %}
{% endblock %}
{% block textarea_widget %}
{% spaceless %}
    <div class="textarea_widget">
        <textarea rows="10" cols="38" id="{{ id }}" class="TextBox" style="height:100px;">{{ value }}</textarea>
    </div>
{% endspaceless %}
{% endblock textarea_widget %}

<div class="cform_box">    
    <div>{{ form_label(form.name) }}</div>{{ form_widget(form.name) }}
</div>
<div class="cform_box" style="height:auto">
    <div>{{ form_label(form.message) }}</div>{{ form_widget(form.message) }}
</div>

我要么得到要么Variable "value" does not exist in contact.html.twig发表Variable "id" does not exist in form_div_layout.html.twig评论{% block text_widget %}

我正在使用 Symfony 2.0.15

4

1 回答 1

1

Symfony2 表单助手中不存在名为“text_widget”的块。这是一个 field_widget type = 'text'

您应该使用 'attr' 从 php 表单定义中添加类“textBox”:

$builder->add('name', 'text', array('label' =>'First Name:', 'attr' => array('class' => 'textBox')));
$builder->add('message', 'textarea', array('label' =>'Message:', 'attr' => array('class' => 'textBox')));

或在您的 form_theme 文件中:

{% block field_widget %}
{% spaceless %}
    {% if type == 'text' or type == 'textarea' %}
        {% set attr = attr|merge({'class': attr.class|default('') ~ ' textBox'}) %}
    {% endif %}
    {% set type = type|default('text') %}
    <input type="{{ type }}" {{ block('widget_attributes') }} value="{{ value }}" />
{% endspaceless %}
{% endblock field_widget %}
于 2012-06-27T13:59:26.017 回答