title: Symfony2 forms and collections - an Order, OrderItem implementation
body: <p>So I've spent around 5 or 6 hours today battling with Symfony2 forms and am at the point where I'd like some advice from other members of the community.  I've tried over 3 different methods to achieve what I'm after and had no success.  I've read through the docs, googled everything, asked others, and I'm only a little bit better off than when I started.</p>
  <h2>My use case</h2>
  <p>I'm building a system where you can order tickets.  But the core problem is how to design the order part of the system.</p>
  <ul>
  <li>a <strong>Ticket</strong> has a name, and start and end dates where it's available (other stuff as well but lets keep the example simple.</li>
  <li>an <strong>Order</strong> may have multiple Tickets selected and for each Ticket there is a quantity.</li>
  <li>an Order has a <strong>Customer</strong>.  <em>This part is fine and works dandy</em>!</li>
  </ul>
  <p>After reading around and trying different things, I gathered that to represent the Order's Ticket and quantity, I needed another entity <strong>OrderTicket</strong> corresponds to an OrderItem from <a href="https://github.com/beberlei/AcmePizzaBundle" rel="nofollow noreferrer">https://github.com/beberlei/AcmePizzaBundle</a> and the Pizza is my Ticket.</p>
  <ul>
  <li>an <strong>OrderTicket</strong> has a Ticket and quantity.</li>
  </ul>
  <p>On my order page where an order is created, I want the following:</p>
  <ul>
  <li>a <strong>form for Customer details</strong> - name, email, address.  <em>This part works fine</em>.</li>
  <li>a <strong>form for the Tickets</strong>.  I want the Ticket name displayed, in a textbox or even a string; <strong>not in a select box</strong> (which is what is happening now).  I want the <strong>quantity</strong> to be specified next to the ticket name.  If there's no quantity set, this means that ticket is not selected.</li>
  <li>the <strong>Tickets should be filtered</strong> where they are available depending on todays date - this is achieved elsewhere (in the backend admin where they're created) by using a custom repository method on a form type with a query builder closure.</li>
  </ul>
  <h2>My back end</h2>
  <p>The Order/OrderTicket/Ticket design is largely based on <a href="https://github.com/beberlei/AcmePizzaBundle" rel="nofollow noreferrer">https://github.com/beberlei/AcmePizzaBundle</a></p>
  <h3>Ticket</h3>
  <pre><code>/**
   * @ORM\Entity(repositoryClass=&quot;Foo\BackendBundle\Entity\TicketsRepository&quot;)
   * @ORM\HasLifecycleCallbacks
   * @ORM\Table(name=&quot;tickets&quot;)
   */
  class Tickets
  {
      // id fields and others
      
      /**
       * @Assert\NotBlank
       * @ORM\Column(type=&quot;string&quot;, nullable=true)
       */
      protected $name;
  
      /**
       * @ORM\Column(type=&quot;date&quot;, name=&quot;available_from&quot;, nullable=true)
       */    
      protected $availableFrom;
  
      /**
       * @ORM\Column(type=&quot;date&quot;, name=&quot;available_to&quot;, nullable=true)
       */    
      protected $availableTo;
  }
  </code></pre>
  <h3>OrderTicket</h3>
  <pre><code>/**
   * @ORM\Table()
   * @ORM\Entity
   */
  class OrderTicket
  {
      // id field
  
      /**
       * @ORM\Column(name=&quot;quantity&quot;, type=&quot;integer&quot;)
       */
      private $quantity;
  
      /**
       * @ORM\ManyToOne(targetEntity=&quot;Tickets&quot;)
       */
      protected $ticket;
  
      /**
       * @ORM\ManyToOne(targetEntity=&quot;Orders&quot;, inversedBy=&quot;tickets&quot;)
       */
      protected $order;
      
      // getters and setters for quantity, ticket and order
  }
  </code></pre>
  <h3>Order</h3>
  <pre><code>/**
   * @ORM\Entity
   * @ORM\HasLifecycleCallbacks
   * @ORM\Table(name=&quot;orders&quot;)
   */
  class Orders
  {   
      // id field and other stuff
      
      /**
       * @ORM\OneToMany(targetEntity=&quot;OrderTicket&quot;, mappedBy=&quot;order&quot;, cascade={&quot;persist&quot;})
       **/
      protected $tickets;
  
      /**
       * @ORM\ManyToOne(targetEntity=&quot;Customer&quot;, cascade={&quot;persist&quot;})
       */
      protected $customer;
  
      public function __construct()
      {
          $this-&gt;tickets = new \Doctrine\Common\Collections\ArrayCollection();
      }
      
      // getters, setters, add for Tickets and Customer
  }
  </code></pre>
  <h3>Customer</h3>
  <pre><code>/**
   * @ORM\Table()
   * @ORM\Entity
   */
  class Customer
  {
      // id, name, email, address fields
  
  }
  </code></pre>
  <p>This creates a schema like so (table naming differences are from auto generation):</p>
  <pre><code>CREATE TABLE `tickets` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
    `available_from` date DEFAULT NULL,
    `available_to` date DEFAULT NULL,
    PRIMARY KEY (`id`)
  );
  CREATE TABLE `Customer` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `address` longtext COLLATE utf8_unicode_ci NOT NULL,
    PRIMARY KEY (`id`)
  );
  CREATE TABLE `OrderTicket` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `ticket_id` int(11) DEFAULT NULL,
    `order_id` int(11) DEFAULT NULL,
    `quantity` int(11) NOT NULL,
    PRIMARY KEY (`id`)
  );
  CREATE TABLE `orders` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `customer_id` int(11) DEFAULT NULL,
    PRIMARY KEY (`id`)
  );
  </code></pre>
  <h3>Forms</h3>
  <pre><code>class CustomerType extends AbstractType
  {
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder
              -&gt;add('email')
              -&gt;add('name')
              -&gt;add('address')
          ;
      }
  
      public function setDefaultOptions(OptionsResolverInterface $resolver)
      {
          $resolver-&gt;setDefaults(array(
              'data_class' =&gt; 'Foo\BackendBundle\Entity\Customer'
          ));
      }
  
      public function getName()
      {
          return 'foo_backendbundle_customertype';
      }
  }
  
  class OrderTicketType extends AbstractType
  {
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder
              -&gt;add('quantity', 'integer')
              -&gt;add('ticket')
          ;
      }
  
      public function setDefaultOptions(OptionsResolverInterface $resolver)
      {
          $resolver-&gt;setDefaults(array(
              'data_class' =&gt; 'Foo\BackendBundle\Entity\OrderTicket'
          ));
      }
  
      public function getName()
      {
          return 'foo_backendbundle_ordertickettype';
      }
  }
  
  class OrdersType extends AbstractType
  {
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder
              -&gt;add('customer', new CustomerType())
              -&gt;add('tickets', 'collection', array(
                  'type' =&gt; new OrderTicketType(),
                  'allow_add'    =&gt; true,
                  'allow_delete' =&gt; true,
                  'prototype'    =&gt; true,
              ))
          ;
      }
  
      public function setDefaultOptions(OptionsResolverInterface $resolver)
      {
          $resolver-&gt;setDefaults(array(
              'data_class' =&gt; 'Foo\BackendBundle\Entity\Orders',
          ));
      }
  
      public function getName()
      {
          return 'foo_backendbundle_orderstype';
      }
  }
  </code></pre>
  <h3>The form</h3>
  <pre><code>&lt;form action=&quot;{{ path('index') }}&quot; method=&quot;post&quot; {{ form_enctype(form) }}&gt;
      &lt;h3&gt;Tickets&lt;/h3&gt;
  
      {{ form_errors(form) }}
  
      &lt;table&gt;
          &lt;thead&gt;
              &lt;tr&gt;
                  &lt;td&gt;Ticket&lt;/td&gt;
                  &lt;td&gt;Quantity&lt;/td&gt;
          &lt;/thead&gt;
          &lt;tbody&gt;
              {% for ticketrow in form.tickets %}
              &lt;tr&gt;
                  &lt;td&gt;{{ form_widget(ticketrow.ticket) }}&lt;/td&gt;
                  &lt;td&gt;{{ form_widget(ticketrow.quantity) }}&lt;/td&gt;
              &lt;/tr&gt;
              {% endfor %}
          &lt;/tbody&gt;
      &lt;/table&gt;
  
      &lt;h3&gt;Customer&lt;/h3&gt;
  
      {% for customer in form.customer %}
          {{ form_row(customer) }}
      {% endfor %}
  &lt;/form&gt;
  </code></pre>
  <h3>And finally the controller</h3>
  <pre><code>class DefaultController extends Controller
  {
      /**
       * @Route(&quot;/&quot;, name=&quot;index&quot;)
       * @Template()
       */
      public function indexAction(Request $request)
      {
          $em = $this-&gt;getDoctrine()-&gt;getManager();
          // IMPORTANT - the Tickets are prefiltered for active Tickets, these have to be injected into the Order atm. In other places I use this method on the query builder
          $tickets = $em-&gt;getRepository('FooBackendBundle:Tickets')-&gt;findActive();
  
          // check no tickets
  
          $order = new Orders();
  
          // To prepopulate the order with the available tickets, we have to do it like this, due to it being a collection,
          // rather than using the forms query_builder like everywhere else
          foreach($tickets as $ticket) {
              $ot = new OrderTicket();
              $ot-&gt;setTicket($ticket);
              $ot-&gt;setQuantity(0);
              $ot-&gt;setOrder($order);
              $order-&gt;addTicket($ot);
          }
  
          $form = $this-&gt;createForm(new OrdersType(), $order);
  
          if ($request-&gt;isMethod('POST')) {
  
              $form-&gt;bind($request);
              
              // IMPORTANT here I have to remove the previously added Tickets where the quantity is 0 - as they're not wanted in the Order.  Is there a better way to do this?
              // if the quantity of Ticket is 0, do not add to order
              // note we use the validation callback in Order to check total quantity of OrderTickets is &gt; 0
              $order-&gt;removeTicketsWithNoQuantity();
  
              if ($form-&gt;isValid()) {
              
                  $em-&gt;persist($order);
                  $em-&gt;flush();
  
                  return $this-&gt;redirect($this-&gt;generateUrl('order_show', array('id' =&gt; $order-&gt;getId())));
              }
          }
  
          return array('form' =&gt; $form-&gt;createView());
      }
  }
  </code></pre>
  <h2>Summary</h2>
  <p>This works and will save the Order correctly, but <em>I'm not sure it is the correct way to do what I want</em>, and it <strong>does not display as I want</strong>.</p>
  <p>You can see below in the images how it looks and how the Order goes through.  It is worth noting that in each of the Ticket drop downs is the rest of the Tickets but which are not active.</p>
  <p>The Order page:</p>
  <p><img src="https://i.stack.imgur.com/VCq1H.jpg" alt="order1" /></p>
  <p>The Order summary page after save:</p>
  <p><img src="https://i.stack.imgur.com/Tu162.jpg" alt="order2" /></p>
  <p>The 3 Tickets displayed are the ones that have been filtered, and I only want these Tickets on the form.  <strong>I ONLY WANT TO SEE THE TICKET NAME, NOT AN EDITABLE DROP DOWN</strong>.</p>
  <p>The core problem is that they are presented as editable drop downs.  I may just want a text string of the Ticket name, or maybe even the Ticket price in the future.  I'm not sure how to achieve this.  I know that the ticket field and relationship must be rendered somehow so that it can be bound in the controller.  So basically I want to be able to use the Ticket entity and it's fields on the same row as the quantity text box.</p>
  <p>So let's step out of the crapstorm of Symfony2's forms and put this in perspective - in the normal world, obviously I'd just retrieve the Tickets, then for each Ticket, I'd print the Ticket name, any other stuff I wanted, a hidden Ticket id, then an input for the Ticket quantity.  Back into SF2 a little - I guess I need the Ticket entity available whilst looping the OrderTicket collection.</p>
  <p>Please help me!</p>