Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access mapped entity from form in Twig

I have a entity mapped to a form, but I don't want to have all fields editable, but still want to show the value.

For example this is my form type:

class GameHasPlayerType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('inTeam', new TeamPositioningCheckboxType())
            ->add('positionX', new TeamPositioningNumberType(), array(
                'attr' => array(
                    'class' => 'in-table'
                )
            ))
            ->add('positionY', new TeamPositioningNumberType(), array(
                'attr' => array(
                    'class' => 'in-table'
                )
            ))
            ->add('exchanged', new TeamPositioningCheckboxType())
        ;
    }
}

This type has a custom form template:

{% block team_positioning_widget %}
    {% spaceless %}
        <td>
            {{ form_widget(form.inTeam) }}
        </td>
        <td>
            {{ form.player.firstName }} {# Player is not in the form, but inside the mapped entity #}
        </td>
    {% endspaceless %}
{% endblock %}

From the form I want to reference to the mapped entity and access fields that are not added to the form.

How can I access the mapped entity from the form object?

like image 820
Johannes Klauß Avatar asked May 26 '14 11:05

Johannes Klauß


1 Answers

You can access the mapped entity through the form.vars.data attribute.

{{ form.vars.data.firstName }} {# The data attribute is the Player instance #}

Or as the documentation says through form.vars.value:

You can access the current data of your form via form.vars.value:

{{ form.vars.value.firstName }}

like image 168
dtengeri Avatar answered Nov 18 '22 07:11

dtengeri