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

后端 未结 13 2140
鱼传尺愫
鱼传尺愫 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: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(),
        ]);
    });
    

提交回复
热议问题