Add an array of options as a list of checkboxes to Symfony 2 forms

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

  • select the parameter list from the database
  • check the box for each of the options
  • do something for each selected parameter

I am using Symfony 2.2.2.

This is how I dynamically add a list to a 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 that looks like this:

 <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 provided data, I can not access the elements "elements" - Symfony throws an exception that the child elements do 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?

Decision

As pointed out by @nifr, the list of flags is added dynamically as follows:

 $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 ) ) ); 
+4
source share
1 answer

You add several fields, not just parameters.

Instead, you should change the choices or choices_list your items field.

See the documentation for the type selection field .

Check boxes will be displayed in the selection box if the multiple parameter is set to true

+3
source

Source: https://habr.com/ru/post/1491835/


All Articles