Djagu
Djagu

Reputation: 161

Twig : Get value of the entity attached to the form in twig view Symfony

I would like to access to the values of the entity I attached to my form in my TWIG view.

The form is created this way :

$form = $this->createForm(new SuperForm(), $entity);

In the twig view if I display the {{ dump(form.vars.value) }} I have this :

Zone {#1000 ▼
#name: "First book zone"
 -book: Book {#538 ▶}
 -location: "inside"
 -priority: 5
 -live: true
 -BooksGroups: PersistentCollection {#1003 ▶}
 -hasGroups: true
 #slug: "sdds"
 #id: 2
 #createdAt: DateTime {#999 ▶}
 #updatedAt: null
 #owner: null
 #updateUser: null
}

EDIT:

However, when I try to access the value through this method, I can't :

{{ form.vars.value.name }}

Impossible to access an attribute ("name") on a null   variable

The curious thing is that, when I do it with de default method, I have no problem and the real value is displayed :

{{ form.vars.value.name|default('Default name') }}

Displayed: 'First book zone'

This is maybe a workaround for the strings and the integers, but how can I do for the Collections and the arrays ?

Upvotes: 4

Views: 2250

Answers (1)

sabat
sabat

Reputation: 146

The trick is needed because you are probably set allow_add option inside your collection type. So this is why first null comes from the prototype of the collection, since there aren't any values set in the prototype. Prototype is a special field which isn't rendered directly in Twig. This is why you have to set default value for prototype or set allow_add to false in your collection.

Upvotes: 1

Related Questions