Here is my FormType :
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('user', 'entity', array(
'class' => 'UserBundle:User',
'expanded' => true,
'property' => 'name',
));
}
Is there a way to access user's fields in the view (Twig) ?
I'd like to do something like this :
{% for u in form.user %}
{{ form_widget(u) }}
{{ form_label(u) }}
{% if u.moneyLeft > 0 %}
<span>{{ u.name }} : {{ u.moneyLeft }} €</span>
{% endif %}
{% endfor %}
... where moneyLeft and name are fields from User entity.
In Symfony 2.5 - you can accomplish this by accessing the data from each choice using the child's index value.
In the form builder - as you might expect:
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Generate form
$builder
->add('child', 'entity', array(
'class' => 'MyBundle:Child',
'label' => 'Children',
'property' => 'any_property_for_label',
'expanded' => true,
'multiple' => true
));
}
In the Twig template:
{{ form_start(form) }}
{% for child in form.child %}
{% set index = child.vars.value %}{# get array index #}
{% set entity = form.child.vars.choices[index].data %}{# get entity object #}
<tr>
<td>{{ form_widget(child) }}</td>{# render checkbox #}
<td>{{ entity.name }}</td>
<td>{{ entity.email }}</td>
<td>{{ entity.otherProperty }}</td>
</tr>
{% endfor %}
{{ form_end(form) }}
As of today, you can do the following in the master branch (and upcoming 2.1):
{{ u.vars.data.name }}
u
is the form view for the user, which contains a list of attached variables. The data
variable contains the normalized data of the form, which usually is your object (unless you added a custom model transformer).
In earlier versions of Symfony, you can do:
{{ u.vars.value.name }}
The value
variable contains the view data of the form, which is also your object (unless you added a custom model or view transformer).
If you are working on Symfony master or >=2.1, I recommend to access data
instead of value
.
This worked for me in Symfony 3.1 for a radio widget:
{% set entity = form.parent.vars.choices[form.vars.name].data %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With