8

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?

Johannes Klauß
  • 10,676
  • 16
  • 68
  • 122
  • This is a duplicate to [How to get a Doctrine2 Entity method from a Symfony2 Form in Twig](http://stackoverflow.com/questions/7134216/how-to-get-a-doctrine2-entity-method-from-a-symfony2-form-in-twig/30344827#30344827). I posted an answer relevant to **version 2.6.7** there. – Jonny May 20 '15 at 12:46

1 Answers1

20

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

jake stayman
  • 1,687
  • 13
  • 22
dtengeri
  • 937
  • 10
  • 21