Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to do something really simple (theoretically ;-)):

  1. select a list of options from the database
  2. show a checkbox for each of the options
  3. do something for each selected options

I am using Symfony 2.2.2.

This is how I add the list dynamically to the form object:

// MyformType
public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $formFactory = $builder->getFormFactory();
        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (\Symfony\Component\Form\FormEvent $event) use ($formFactory) {
                $options = $event->getData();
                $items = $options["items"];
                foreach ($items as $item) {
                    $event->getForm()->add(
                        $formFactory->createNamed($item->getId(), "checkbox", false, array(
                                'label'     => $item->getName()                                   
                            )
                        )
                    );
                }
            }
        );
    }

 public function getName()
 {
        return 'items';
 }

Symfony generates HTML which looks like that:

<input type="checkbox" id="items_17" name="items[17]" value="1">
<input type="checkbox" id="items_16" name="items[16]" value="1">

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.

// controller action
...
if ($request->isMethod('POST')) {
  $form->bind($request);
  if ($form->isValid()) {
    $form->get('items')->getData(); // exception: child 'items' does not exist
  }
}

What am I doing wrong?

Solution:

As outlined by @nifr a list of checkboxes is added dynamically like this:

$items = array(1 => "foo", 2 => "bar"); 
$event->getForm()->add(
  $formFactory->createNamed("selecteditems", "choice", null, array(
                            "multiple" => true,
                            "expanded" => true,
                            "label" => "List of items:",
                            "choices" => $items
                        )


  )
);
share|improve this question

1 Answer

up vote 0 down vote accepted

You're adding multiple fields instead of just the options.

You should modify the choices or choices_list option of your items field instead.

See the documentation for choice field-type.

The choice field will render checkboxes if the multiple option is set to true

share|improve this answer
 
note (for anybody else interested in the solution): you have to set both multiple and expanded to true to get checkboxes –  jamie0726 Jul 17 at 15:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.