25

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?

Mick
  • 30,759
  • 16
  • 111
  • 130
madc
  • 1,674
  • 2
  • 26
  • 41

14 Answers14

47

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

$builder->add('isPublic', CheckboxType::class, array(
    'attr' => array('checked'   => 'checked'),
));
Astronaute
  • 219
  • 3
  • 19
Simon Kerr
  • 566
  • 1
  • 4
  • 3
  • 1
    works for me, I am looking now for the same thing but for a radiobutton – linuxatico Jul 25 '12 at 08:49
  • 3
    That's interesting. You are telling symfony to add checked="checked" to the attributes of the checkbox, rather than telling symfony that the value of the checkbox is true and that it should therefore be adding checked="checked" itself. – rjmunro Aug 06 '12 at 14:20
  • Works for me in Symfony2.0. Thanks! – James Sep 05 '12 at 15:23
  • Simple and efficient solution for Symfony 3. Many thanks ! – YumeYume Jun 30 '16 at 12:02
  • 5
    Won't work if you want to use the form for editing an entity, too. A value of "false" will still have a "checked" attribute. Sgoettschkes' solution is better – CunningFatalist Oct 26 '17 at 08:44
24

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

So:

$builder->add('checkboxName', 'checkbox', array('mapped' => false,
    'label' => 'customLabel',
    'data' => true, // Default checked
));
Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
Leto
  • 2,594
  • 3
  • 24
  • 37
21

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.

Sgoettschkes
  • 13,141
  • 5
  • 60
  • 78
  • Well, i already do set a value of the form this way, but I was simply too focused on finding an attribute to set the checkbox that I did not even thought in this direction. Thanks for the fast and perfect answer, solved the problem! – madc Mar 06 '12 at 13:22
  • 5
    +1 - Another way, if `true/checked` is the default value for any new entity, is simply to set the value in the `__construct()`-method like: `public function __construct() { $this->attribute = true; }`. – insertusernamehere Nov 21 '12 at 14:51
15

Setting the 'data' option works for me. I'm creating a non entity based form:

$builder->add('isRated','checkbox', array(
    'data' => true
));
Taz
  • 3,718
  • 2
  • 37
  • 59
lackovic10
  • 994
  • 1
  • 8
  • 11
  • 2
    In Symfony 2.8, this doesn't work if the model has an explicit false value when creating the form. The checkbox would still be checked. – Peter Jul 06 '16 at 06:14
  • Yes, thanks Peter. Any idea on what *will* work in Symfony >=2.8? – cg. Aug 17 '16 at 08:24
10

In TWIG

If you wish to do this in the template directly:

{{ form_widget(form.fieldName, { 'attr': {'checked': 'checked'} }) }}
Mick
  • 30,759
  • 16
  • 111
  • 130
5

Use the FormBuilder::setData() method :

$builder->add('fieldName', 'checkbox', array('property_path' => false));
$builder->get('fieldName')->setData( true );

"property_path" to false cause this is a non-entity field (Otherwise you should set the default value to true using your entity setter).

Checkbox will be checked by default.

eDoV
  • 134
  • 1
  • 3
5

To complete a previous answer, with a multiple field you can do that to check all choices :

   'choice_attr' => function ($val, $key, $index) {
       return ['checked' => true];
   }

https://symfony.com/doc/3.3/reference/forms/types/choice.html#choice-attr

Gautier
  • 1,066
  • 1
  • 13
  • 24
2

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
            ));
    }
}
metamaker
  • 2,307
  • 2
  • 19
  • 18
1

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.

R Sun
  • 1,353
  • 14
  • 17
  • But be aware that in the cases when you are showing the already existing object (with possibly this value NOT checked), your `'data' = true` would still force it to be shown as checked. From the same doc page: *"The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overriden when the form edits an already persisted object, causing it to lose its persisted value when the form is submitted."* – userfuser Aug 16 '17 at 19:28
1
UserBundle\Entity\User

let's assume that you have an entity called ( User ) and it has a member named isActive, You can set the checkbox to be checked by default by setting up isActive to true:

$user = new User();

// This will set the checkbox to be checked by default
$user->setIsActive(true);

// Create the user data entry form
$form = $this->createForm(new UserType(), $user);
Nezar Fadle
  • 1,335
  • 13
  • 11
1

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(),
    ]);
});
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
0

This works as well, but aware of persistent "checked" state

$builder->add('isPublic', 'checkbox', array(
    'empty_data' => 'on',
));
Stanislav Terletskyi
  • 2,072
  • 20
  • 17
  • 1
    This solutions works for new AND edit ; from symfony2.3 to 4+ ; and is brilliantly simple! many thanks @stanislav ; The only modification I have (symfony 2.8) is to use CheckboxType::class instead of 'checkbox' – nicolallias Apr 11 '18 at 10:09
  • 1
    symfony 4: this option determines what value the field will return when the submitted value is empty (or missing). **It does not set an initial value if none is provided when the form is rendered in a view.** – Zoltán Süle Feb 27 '19 at 14:54
0

This is how you can define the default values for multiple and expanded checkbox fields. Tested in Symfony4, but it has to work with Symfony 2.8 and above.

if you want to active the 1st and the 2nd checkboxes by default

class MyFormType1 extends AbstractType
{
    CONST FIELD_CHOICES = [
        'Option 1' => 'option_1',
        'Option 2' => 'option_2',
        'Option 3' => 'option_3',
        'Option 4' => 'option_4',
        'Option 5' => 'option_5',
    ];

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $this->addSettingsField('my_checkbox_field', ChoiceType::class, [
            'label'    => 'My multiple checkbox field',
            'choices'  => self::FIELD_CHOICES,
            'expanded' => true,
            'multiple' => true,
            'data'     => empty($builder->getData()) ? ['option_1', 'option_2'] : $builder->getData(),
        ]);

    }
}

if you want to active every checkbox by default

class MyFormType2 extends AbstractType
{
    CONST FIELD_CHOICES = [
        'Option 1' => 'option_1',
        'Option 2' => 'option_2',
        'Option 3' => 'option_3',
        'Option 4' => 'option_4',
        'Option 5' => 'option_5',
    ];

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $this->addSettingsField('my_checkbox_field', ChoiceType::class, [
            'label'    => 'My multiple checkbox field',
            'choices'  => self::FIELD_CHOICES,
            'expanded' => true,
            'multiple' => true,
            'data'     => empty($builder->getData()) ? array_values(self::FIELD_CHOICES) : $builder->getData(),
        ]);

    }
}
Zoltán Süle
  • 1,482
  • 19
  • 26
0

The only watertight solution for me in Symfony 4, 2022 is:

OPTION 1:

First, set it default to "true" on the entity parameter itself:

class MyEntity {
    /**
     * @ORM\Column(name="my_param", type="boolean", nullable=true)
     */
    private $myParameter = true;

    ...
}

Secondly, in the form, first see if you can get it from the entity itself. If Not, set the default

public function buildForm(FormBuilderInterface $builder, array $options)
{
    /** @var MyEntity $entity */
    $entity = $builder->getData();

    $builder->add('myParameter', CheckboxType::class, [
        'required' => false,
        'data' => $entity ? $entity->getMyParameter() : true,
    ]);
}

This way the real value (coming from the database) has precedence over the default value.
Also good to know is: Submitted data has precedence over the 'data' => true but initially loaded data before submit gets overridden by 'data' => true

OPTION 2:

An alternative way of setting it default true on the MyEntity Class you can choose to set it as default only just before creating the form. But then you always need the object to create the form with. So you then may not create a form without a given object

if (empty($entity)) {
    // Warning: Only if it's a new object, set the default
    $entity = new MyEntity();
    $entity->setMyParameter(true);
}

// For this option you must always give the form an entity
$form = $this->createForm(MyType::class, $entity);
$form->handleRequest($request);

So for this option you don't need to do anything special in the FormType

$builder->add('myParameter', CheckboxType::class, [
    'required' => false,
]);
Julesezaar
  • 2,658
  • 1
  • 21
  • 21