Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

twig

symfony

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?

like image 675
David Morales Avatar asked Aug 20 '11 19:08

David Morales


3 Answers

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

or

{% for obj in form.mycollection %}
  {{ obj.get('value').someMethod }}
{% endif %}
like image 124
dturcotte Avatar answered Nov 20 '22 14:11

dturcotte


An even more convenient syntax to get the underlying entity instead of

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

is this:

{{ form.vars.value }}

Then you can call any entity method like this:

{{ form.vars.value.someMethod }}

See also the Form chapter in the Symfony2 Docs:

http://symfony.com/doc/current/book/forms.html#rendering-a-form-in-a-template

like image 37
Philipp Rieber Avatar answered Nov 20 '22 14:11

Philipp Rieber


Just in order to update the subject:

form.get('value')

is deprecated since symfony 2.1. Copy from Symfony\Component\Form\FormView :

/*
 * @deprecated Deprecated since version 2.1, to be removed in 2.3. Access
 *             the public property {@link vars} instead.
 */
public function get($name, $default = null) ....

so, I guess

form.vars.value.youMethod()

should be the way to go. It has worked form me.

... and there it goes my first post here. hope it helps!

like image 15
javigzz Avatar answered Nov 20 '22 16:11

javigzz