I want to render a form which has multiple Entities of same Class. I will display 2 fields, Price(type=text) and Enabled(type=checkbox).
I don't know how many I will have of those entities, so form will have to get them dynamically.
I have tried to do the following
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('price', 'text', array(
'label' => 'Price',
'required' => true
))
->add('enabled','checkbox',array(
'label' => 'Use this currency',
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Osiris\Entity\Pricing',
'csrf_protection' => false
));
}
public function getName()
{
return 'pricingtype';
}
And in my Controller I have created my form like this:
$pricingForm = $this->createFormBuilder($prices)
->add('items','collection',array(
'required' => false,
'prototype' => true,
'type' => new PricingType(),
))
->getForm()
;
In my twig I do:
{% for price in form_pricing %}
<h2>Price</h2>
<div class="row">{{ form_widget(price) }}</div>
{% endfor %}
However it comes only with h2 Prices and empty div with class=row. I feel like I am half way there, but I've no idea how to move on. If someone knows how to get fields on submit as well, I will really appreciate it.
I found the solution,
the way I was creating the form in Controller was wrong! I had to do the following:
"allow_add => true" is necessary when working with collection, otherwise it will NOT add any of PricingType collection of entities to the form.
Then, because the form is built inside the controller "
$this->createFormBuilder(array('prices'=>$prices))
" ,$prices
array must be passed as an array with array keyname same as the one used in "->add('prices','collection',array(...)
" , which is'prices'
so Symfony will know what to bind where.$prices
is an array of Pricing objectsarray(0 => new Pricing())
.In my PricingType I have:
Here I need to have control over label attribute. I could not find the way for it( if anyone knows please post how to). I override my twig template as follows:
On the top we need next line of code:
Then override row and widget as follows (it was a nightmare to debug):
In the body then, render form elements as follows:
I really hope this will help you guyz. It was a real nightmare to debug especially the twig file, I did it thanks to my clever colleague.
I think you have missed a for loop in your twig file Check this example:
See the loop, I think that you need to add in your twig file.
In addition to loops you need to add JavaScript also.
Check this link:
http://symfony.com/doc/current/reference/forms/types/collection.html#adding-and-removing-items
Check the complete code. It will help you out to generate multiple entity forms from a single entity class using collection field type.