ben*_*h-o 14 php forms symfony
我想在symfony2中对字段进行分组.例如,将它们包装在div中并在其间放置标题:
<form>
<div class="step-1">
<h3>Step 1</h3>
Field 1
Field 2
</div>
<div class="step-2">
<h3>Step 2</h3>
Field 3
Field 4
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
问题是表单有很多字段,所以我不能在模板中逐个渲染它们.添加字段时没有任何选项吗?喜欢:
$form = $this->createFormBuilder()
->addGroup('step-1')
Run Code Online (Sandbox Code Playgroud)
或者我该如何处理?
ben*_*h-o 15
我发现,根据这篇文章(谢谢"n.1"的链接),可以在控制器内分组:
$form = $this->createFormBuilder()
->add(
$this->createFormBuilder()->create('step1', 'form', array('virtual' => true))
->add('field1', 'text')
->add('field2', 'text')
)
Run Code Online (Sandbox Code Playgroud)
其中给出了以下模板:
<div class="input-wrapper">
<label class="required">Step1</label>
<div id="form_step1">
<div class="input-wrapper">
<label class="required" for="form_step1_field1">Field1</label>
<input id="form_step1_field1" type="text" required="required" name="form[step1][field1]">
<input id="form_step1_field2" type="text" required="required" name="form[step1][field1]">
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我可以按照我想要的方式主题.而且"bschussek"写道:
表单类中的结构不一定与布局中的结构相关.您可以按照自己喜欢的方式构建HTML中的字段.
所以也许最好的做法是不使用控制器进行结构化,我更喜欢"n.1"的做法.
A.L*_*A.L 11
Twig可以帮助您使用最少的代码显示多个字段:
<form>
<div class="step-1">
<h3>Step 1</h3>
{% for field in [ 'field1', 'field2']
if (attribute(form, field) is defined) %}
{{ form_row(attribute(form, field)) }}
{% endfor %}
</div>
<div class="step-2">
<h3>Step 2</h3>
{% for field in [
'field3',
'field4',
'field5',
'field6'
] if (attribute(form, field) is defined) %}
{{ form_row(attribute(form, field)) }}
{% endfor %}
</div>
{# Display the other fields #}
{{ form_rest(form) }}
</form>
Run Code Online (Sandbox Code Playgroud)
表单类中的结构不一定与布局中的结构相关.您可以按照自己喜欢的方式构建HTML格式的字段.在您的情况下,您可以像在Q中一样放置步骤标题,例如:
<div class="step-1">
<h3>Step 1</h3>
{{ form_widget(form.field1) }}
{{ form_widget(form.field2) }}
</div>
Run Code Online (Sandbox Code Playgroud)
如果你仍然有兴趣分组表格(我没有测试):
$builder->add(
$builder->create('step1', 'form', array('virtual' => true))
->add('field1', 'text')
->add('field2', 'text')
);
Run Code Online (Sandbox Code Playgroud)
来源.