How to render a checkbox that is checked by default with the symfony2 Form Builder? How to render a checkbox that is checked by default with the symfony2 Form Builder? symfony symfony

How to render a checkbox that is checked by default with the symfony2 Form Builder?


You can also just set the attr attribute in the form builder buildForm method:

$builder->add('isPublic', CheckboxType::class, array(    'attr' => array('checked'   => 'checked'),));


In Symfony >= 2.3 "property_path" became "mapped".

So:

$builder->add('checkboxName', 'checkbox', array('mapped' => false,    'label' => 'customLabel',    'data' => true, // Default checked));


You would simply set the value in your model or entity to true and than pass it to the FormBuilder then it should be checked.

If you have a look at the first example in the documentation:

A new task is created, then setTask is executed and this task is added to the FormBuilder. If you do the same thing with your checkbox

$object->setCheckboxValue(true);

and pass the object you should see the checkbox checked.

If it's not working as expected, please get back with some sample code reproducing the error.