David Morales David Morales - 11 months ago 54
PHP Question

How to get a Doctrine2 Entity method from a Symfony2 Form in Twig

I'm in a Twig template, and I have a "form" variable that represents a Doctrine2 Entity Form.

This Entity has properties that are mapped into the form, but the Entity has also some methods that I would like to access from my Twig template.

I would love to do something like this:

{{ form.myMethod }}

or maybe something like this:

{{ form.getEntity.myMethod }}

but unfortunately it doesn't work.

How could I achieve what I need?

Answer Source

To access your entity from your FormView in a twig template you can use the following code

{{ form.get('value') }}

Where form is your FormView object. This will return your entity and from there you can call any methods on it. If you embed a collection of entities or a single entity in your form you can access it the same way

{{ form.someembedform.get('value') }}


{% for obj in form.mycollection %}
  {{ obj.get('value').someMethod }}
{% endif %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download