5

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
                        )


  )
);

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

note (for anybody else interested in the solution): you have to set both multiple and expanded to true to get checkboxes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.