Symfony2 : accessing entity fields in Twig with an entity field type

Aurel picture Aurel · Apr 26, 2012 · Viewed 23.8k times · Source

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.

Answer

Aaron Geiser picture Aaron Geiser · Oct 1, 2014

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) }}