Reputation: 93
I have a form with a multiple checkBox list (choice list is prepared dynamically). I want them to be selected from the beginning (so that user can uncheck them). I have prepared an array with choices and checked_choices, but during the form rendering only the first checkbox is selected. Any suggestions about how to fix it?
$choices = array();
$choices_check= array();
foreach($user[0]->getShops() as $shop)
{
$choices[$shop->getId()] = $shop->getName();
$choices_check[] = true;
}
//return $this->render('GLPolicyBundle:Policy:tmp.html.twig', array('entities' => var_dump($choices_p)));
$searchby = array();
$form = $this->createFormBuilder($searchby)
->add('shop', 'choice', array('choices' => $choices,
'multiple' => true,
'expanded' => true,
'required' => true,
'data' => $choices_check)
)
->add('date_from', 'date', array('data' => $date_from))
->add('date_to', 'date', array('data' => new \DateTime()))
->getForm();
Upvotes: 0
Views: 116
Reputation: 1962
The data needs to be an array who's values are the keys of the choices that you want selected.
Changing $choices_check[] = true to the following should do it.
$choices_check[] = $shop->getId();
Note that after you POST the form, $form->getData() is the same format.
Upvotes: 2
Reputation: 2850
A solution is to set checked attribute in the Twig view :
{% for shop in form.shop %}
{{ form_label(shop) }}
{{ form_widget(shop, { 'attr': {'checked': 'checked'} }) }}
{% endfor %}
Upvotes: 1