multiple rows in form for the same entity in symfony2

前端 未结 1 1614
春和景丽
春和景丽 2020-12-11 20:44

I create a simple form with multiple rows:

Controller:

public function indexAction() 
{
    $repository = $this->getDoctrine()->getRepository(\         


        
1条回答
  •  一向
    一向 (楼主)
    2020-12-11 21:21

    Ok Cerad was right with his comment and we have to use collection for this. It may sound like a nonsense at first but it kinda is right. It took me a while to get head around it.

    So i had to create a ProductsType which is an arrayCollection and inserts each Product. (just like in documentation with Task and tags)

    I used that:

    $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:

    {% for product in collection.products %} {{ form_row(product.id) }} {{ form_row(product.name) }} {{ form_row(product.description) }}
    {% endfor %}

    Job done.

    And even you can apply themes to each row by this:

    {% block _productsType_products_entry_name_row %}
        
    {{ block('form_widget') }}
    {% endblock %} {% block _productsType_products_entry_description_row %}
    {{ block('form_widget') }}
    {% endblock %}

    Cool stuff!

    0 讨论(0)
提交回复
热议问题