I want to group fields in symfony2. For example wrap them in a div and place headlines in between:
<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>
The problem is the form got very much fields so i cant render them one by one in the template. Isnt there any option when adding fields? Like:
$form = $this->createFormBuilder()
->addGroup('step-1')
Or how can i handle this?
Twig can help you to display multiple fields with a minimal code:
<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>
I found out, according to this post(Thanks "n.1" for the link) it is possible to group within controller:
$form = $this->createFormBuilder()
->add(
$this->createFormBuilder()->create('step1', 'form', array('virtual' => true))
->add('field1', 'text')
->add('field2', 'text')
)
Which gives following template:
<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>
Which i can theme the way i want to. But also "bschussek" wrote:
The structure in your form class shouldn't necessarily be related to the structure in your layout. You can structure the fields in the HTML in whichever way you like.
So maybe the best practice is not to use the controller for structuring and I should prefer the practice from "n.1"
The structure in your form class shouldn't necessarily be related to the structure in your layout. You can structure the fields in yout HTML in whichever way you like. In your case you would put your step headings just like you did in your Q, e.g.:
<div class="step-1">
<h3>Step 1</h3>
{{ form_widget(form.field1) }}
{{ form_widget(form.field2) }}
</div>
If you still interested to group forms (I did not test that):
$builder->add(
$builder->create('step1', 'form', array('virtual' => true))
->add('field1', 'text')
->add('field2', 'text')
);
Source.