Multiple form lines for the same object in symfony2

I am creating a simple form with several lines:

Controller:

public function indexAction() { $repository = $this->getDoctrine()->getRepository('MyBundle:Product'); $products = $repository->findAll(); foreach ($products as $product) { $forms[] = $this->createForm(new ProductType, $product)->createView(); } return $this->render('MBundle:Default:index.html.twig', array('form' => $forms); } 

I am doing this in a branch:

 <form action="{{ path('_submit') }}" method="post"> {% for key, formData in forms %} {{ form_row(formData.id) }} {{ form_row(formData.name) }} {{ form_row(formData.nameEnglish) }} <br clear="all" /> {% endfor %} </form> 

When I submit the form, each of my input fields has the same name attributes, and I only get the last one. How to capture all lines and check them in my submitAction () controller? Each input must have a unique name, right? ... and maybe I need to somehow set name = "something [name] []", but how to do it?

+4
source share
1 answer

Ok Cerad was right with his comment, and we must use the collection for this. At first this may seem silly, but itโ€™s right. It took me a while to get around it.

So I had to create a ProductType, which is an arrayCollection and inserts each Product. (same as in documentation with Task and tags)

I used this:

 $repository = $this->getDoctrine()->getRepository('ExampleBundle:Product'); $products = $repository->findAll(); $productCollection = new Products; foreach ($products as $product) { $productCollection->getProducts()->add($product); } $collection = $this->createForm(new ProductsType, $productCollection); return $this->render('ExampleBundle:Default:index.html.twig', array( 'collection' => $collection->createView() )); 

Then in twig I do:

 <div class="products"> {% for product in collection.products %} {{ form_row(product.id) }} {{ form_row(product.name) }} {{ form_row(product.description) }} <br clear="all" /> {% endfor %} </div> 

The task is completed.

And even you can apply themes to each line as follows:

 {% block _productsType_products_entry_name_row %} <div class="yourDivName">{{ block('form_widget') }}</div> {% endblock %} {% block _productsType_products_entry_description_row %} <div class="yourDivDescription">{{ block('form_widget') }}</div> {% endblock %} 

Cool stuff!

+6
source

Source: https://habr.com/ru/post/1433468/


All Articles