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

我怕爱的太早我们不能终老 提交于 2019-11-29 05:38:14

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.

Simon Kerr

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

$builder->add('isPublic', 'checkbox', array(
    'attr' => array('checked'   => 'checked'),
));
Leto

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

So:

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

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

$builder->add('isRated','checkbox', array(
    'data' => true
));

In TWIG

If you wish to do this in the template directly:

{{ form_widget(form.fieldName, { 'attr': {'checked': 'checked'} }) }}

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.

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

$builder->add('isPublic', 'checkbox', array(
    'empty_data' => 'on',
));

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
            ));
    }
}

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.

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);

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

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(),
        ]);

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!