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 ) ) );