I want to do something really simple (theoretically ;-)):
- select a list of options from the database
- show a checkbox for each of the options
- 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
)
)
);