Symfony2: How to create entity form with creation of multiple subentities?
forms, symfony
Solution
Take a look at an example: AcmePizzaBundle. It has 4 entities you need: Pizza, Order, OrderItem, Customer.
Problem
This is propably a simple task to solve in Symfony2 but I am really stuck here: I am building a very simple shop. There are three entities: `Products`, `Customers`, and `Orders`. The last one contains three columns: `customer_id`, `product_id`, and `quantity`. The shop simply consists of a page listing all the products with a select field for each to chose the quantity, followed by a form to enter your customer data. I have no problem creating the form for the customer data nor listing the products itself (without the select fields). But how do I create a form including the select fields of the products, which then should become order entities? I played around with form collections and I do understand all the given examples with adding tags to an entity etc. But I can't get the hang of how to adjust it to my situation. What I have in mind goes something like this: ``` // Create new customer $customer = new Customer(); // At this point, create form and validate it. // Having trouble here, need a hint to get it right. ... // If form is ok, loop thru all the products. // Since I do not know yet how to define the form, // I don't know yet what to loop over, too. foreach( ..... ){ if($quantity > 0){ $order = new Order(); $order->setQuantity($quantity); $order->setProduct($product); $customer->addOrder($order); } } // then persist $customer, cascading its orders. ... ``` I have been spending hours on this. Any help is greatly appreciated. Thanks! Update: Eventually I got it working. I created an `OrderFactory` and a `OrderFormType` and had to change around the whole setting a bit. The AcmePizzaBundle which is mentioned in the responses below was actually a great help to get the missing parts right.