Mario Legenda Mario Legenda - 3 years ago 256
PHP Question

Symfony2 Nested Collections and the Prototype

I have 3 nested form in Symfony2. I won't get into all the code here beacuse it can be long. I'm just gonna show an example of what I want to do here.

So, let's say that

Category
has a
Product
and the Product has a
Tag
.
Each one of them would be a reusable
AbstractType
.

This would be the code for the CategoryType (I will leave out
allow_add
,
allow_delete
, and
by_reference
for increased readability).

$builder->add('product', 'collection', array(
'type' => new ProductType(),
'prototype' => true,
'prototype_name' => '__product__'
));


This would be the ProductType

$builder->add('tag', 'collection', array(
'type' => TagType(),
'prototype' => true,
'prototype_name' => '__tag_name__'
));


TagType is not really important here. What I want is render the prototype for these collections in Twig in two
divs
like this...

<div class="ResourceAttributePrototype" data-product-prototype="{{ form_widget(form.product.vars.prototype)|e }}"></div>

<div class="Prototype" data-tag-prototype="{{ form_widget(form.product.vars.prototype.children['tag'].vars.prototype)|e }}"></div>


The problem is that the first prototype is render in the data attribute, but the second is an empty string. Why?

Also, if anyone has a better idea of how to render nested form collections, Im all ears. I found a good example that i followed but it does not work.

Answer Source

If you simply render out the children first, this problem goes away.

Example from one of my projects:

Render these prototypes first:

campaignForm.campaignRows.vars.prototype.children['campaignTexts'].vars.prototype campaignForm.campaignRows.vars.prototype.children['featuredItems'].vars.prototype campaignForm.campaignRows.vars.prototype.children['campaignImageCampaigns'].vars.prototype

Then the parent:

campaignForm.campaignRows.vars.prototype

Works for me, hopefully it works for you too. I assume the children are set as rendered internally somehow which causes the problem you have.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download