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

后端 未结 13 2142
鱼传尺愫
鱼传尺愫 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:18

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

    $builder->add('isRated','checkbox', array(
        'data' => true
    ));
    
    0 讨论(0)
  • 2020-12-17 10:18

    In TWIG

    If you wish to do this in the template directly:

    {{ form_widget(form.fieldName, { 'attr': {'checked': 'checked'} }) }}
    
    0 讨论(0)
  • 2020-12-17 10:20

    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.

    0 讨论(0)
  • 2020-12-17 10:23

    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
                ));
        }
    }
    
    0 讨论(0)
  • 2020-12-17 10:28

    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

    0 讨论(0)
  • 2020-12-17 10:28

    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(),
        ]);
    });
    
    0 讨论(0)
提交回复
热议问题