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

后端 未结 13 2202
鱼传尺愫
鱼传尺愫 2020-12-17 09:30

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?

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 10:07

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

提交回复
热议问题