Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 259
Aurel Avatar asked Apr 26 '12 14:04

Aurel


3 Answers

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) }}
like image 84
Aaron Geiser Avatar answered Nov 04 '22 06:11

Aaron Geiser


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.

like image 43
Bernhard Schussek Avatar answered Nov 04 '22 08:11

Bernhard Schussek


This worked for me in Symfony 3.1 for a radio widget:

{% set entity = form.parent.vars.choices[form.vars.name].data %}
like image 24
Jonathan Avatar answered Nov 04 '22 07:11

Jonathan