Access mapped entity from form in Twig
Asked Answered
D

1

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?

Delius answered 26/5, 2014 at 11:2 Comment(1)
This is a duplicate to How to get a Doctrine2 Entity method from a Symfony2 Form in Twig. I posted an answer relevant to version 2.6.7 there.Monandrous
E
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 }}

Esemplastic answered 26/5, 2014 at 11:10 Comment(4)
This does not work. {{ form.vars.value }} is null as well as {{ form.vars.data }}Arrest
How do you create your form in your controller? Do you pass your entity as data: $this->createForm(new GameHasPlayerType(), $entity);Esemplastic
No I create this form in a parent form like this: $builder->add('subForm', new GameHasPlayerType())Arrest
Aaah, now I got it. I needed to set the data key to the entity in the options array. Thank alot for your help :)Arrest

© 2022 - 2024 — McMap. All rights reserved.