Reputation: 345
I'm doing a filter form in symfony2 and I try to preselect some filds.
I got two choices:
$formBuilder->add('first', 'choice',
array('choices' => $choiceFirst,
'expanded' => false,
'multiple' => true,
'data' => explode(' ', $this->getRequest()->get('first'))
));
$formBuilder->add('second', 'choice',
array('choices' => $choiceSecond,
'expanded' => true,
'multiple' => true,
'data' => explode(' ', $this->getRequest()->get('second'))));
For the first choice which is not expanded the datas pass by url are preselect. But not for the second which is expanded.
There is any ways to preselect checkboxs from a field choice?
Upvotes: 0
Views: 4875
Reputation: 51
Try:
$formBuilder->add('first', 'choice',
array('choices' => array('0' => 'first option', '1' => 'second option'),
'expanded' => false,
'multiple' => true,
'data' => explode(' ', $this->getRequest()->get('first'))
));
And view:
{{ form_widget(form.first.0) }}
{{ form_widget(form.first.1) }}
For me works.
Upvotes: 1
Reputation: 2444
The best solution i find for this issue is to simply set the default value to your object before generate the form.
Like : $myEntity->setMyfieldchoice(1);
This way symfony will understand this value is the default value (worked for my on a select field).
Hope this help !
Upvotes: 1
Reputation: 12727
You must provide an array of selected values as data for a multiple choice field.
edit: irrelevant answer, my mistake
Try to provide a key => boolean array as the checked state depends on a boolean value.
I think you only have to put checked value in your array, so those one that are true ;)
Upvotes: 1