I have not found any easy way to accomplish to simply check a Checkbox by default. That can not be that hard, so what am i missing?
Setting the 'data'
option works for me. I'm creating a non entity based form:
$builder->add('isRated','checkbox', array(
'data' => true
));
If you wish to do this in the template directly:
{{ form_widget(form.fieldName, { 'attr': {'checked': 'checked'} }) }}
As per documentation: http://symfony.com/doc/current/reference/forms/types/checkbox.html#value
To make a checkbox or radio button checked by default, use the data option.
You should make changes to temporary object where entity is stored before displaying it on form. Something like next:
<?php
namespace KPI\AnnouncementsBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class AnnouncementType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
if ($options['data']->getDisplayed() === null) {
$options['data']->setDisplayed(true);
}
// ...
$builder
->add('displayed', 'checkbox', array(
'required' => false
));
}
}
To complete a previous answer, with a multiple field you can do that to check all choices :
'choice_attr' => function ($val, $key, $index) {
return array('checked' => true);
}
https://symfony.com/doc/3.3/reference/forms/types/choice.html#choice-attr
I had the same problem as you and here is the only solution I found:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$entity= $event->getData();
$form = $event->getForm();
$form->add('active', CheckboxType::class, [
'data' => is_null($entity) ? true : $entity->isActive(),
]);
});