php - Symfony2 Nested Collections and the Prototype

393

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 thatCategory has aProduct and the Product has aTag. Each one of them would be a reusableAbstractType.

This would be the code for the CategoryType (I will leave outallow_add,allow_delete, andby_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 twodivs like this...

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

<div 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.

931

Answer

Solution:

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.

923

Answer

Solution:

Okay, i figured it out.

This was a project that I inhereted. It had its own form themeing and that themeing made nested form collections be rendered inside own another.

So if anyone sees this, check your form theme, if you made it custom.

The answers above all work.

People are also looking for solutions to the problem: php - Populating 2 tables from one controller in Laravel 5.1

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.