title: Add array of options as checkbox list to Symfony 2 forms
body: <p>I want to do something really simple (theoretically ;-)):</p>
  
  <ol>
  <li>select a list of options from the database</li>
  <li>show a checkbox for each of the options</li>
  <li>do something for each selected options</li>
  </ol>
  
  <p>I am using Symfony 2.2.2.</p>
  
  <p>This is how I add the list dynamically to the form object:</p>
  
  <pre><code>// MyformType
  public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $formFactory = $builder-&gt;getFormFactory();
          $builder-&gt;addEventListener(
              FormEvents::PRE_SET_DATA,
              function (\Symfony\Component\Form\FormEvent $event) use ($formFactory) {
                  $options = $event-&gt;getData();
                  $items = $options["items"];
                  foreach ($items as $item) {
                      $event-&gt;getForm()-&gt;add(
                          $formFactory-&gt;createNamed($item-&gt;getId(), "checkbox", false, array(
                                  'label'     =&gt; $item-&gt;getName()                                   
                              )
                          )
                      );
                  }
              }
          );
      }
  
   public function getName()
   {
          return 'items';
   }
  </code></pre>
  
  <p>Symfony generates HTML which looks like that:</p>
  
  <pre><code>&lt;input type="checkbox" id="items_17" name="items[17]" value="1"&gt;
  &lt;input type="checkbox" id="items_16" name="items[16]" value="1"&gt;
  </code></pre>
  
  <p>Now when I try to save the submitted data I can't access an element "items" - Symfony throws an exception that the child 'items' does not exist.</p>
  
  <pre><code>// controller action
  ...
  if ($request-&gt;isMethod('POST')) {
    $form-&gt;bind($request);
    if ($form-&gt;isValid()) {
      $form-&gt;get('items')-&gt;getData(); // exception: child 'items' does not exist
    }
  }
  </code></pre>
  
  <p>What am I doing wrong?</p>
  
  <p><strong>Solution</strong>:</p>
  
  <p>As outlined by @nifr a list of checkboxes is added dynamically like this:</p>
  
  <pre><code>$items = array(1 =&gt; "foo", 2 =&gt; "bar"); 
  $event-&gt;getForm()-&gt;add(
    $formFactory-&gt;createNamed("selecteditems", "choice", null, array(
                              "multiple" =&gt; true,
                              "expanded" =&gt; true,
                              "label" =&gt; "List of items:",
                              "choices" =&gt; $items
                          )
  
  
    )
  );
  </code></pre>