Symfony2根据复选框将表单中的实体设置为可选

时间:2013-03-28 16:04:58

标签: forms symfony symfony-2.2

我的表单类型如

class ApplicationFormType extends AbstractType
{
        public function buildForm(FormBuilderInterface $builder, array $options)
    {
            $nurse = new Type\NurseType();
            $builder
                ->add('nurse', $nurse)
                ->add('nurse_type', 'entity', array(
                    'class' => 'Acme\MainBundle\Entity\NurseType',
                    'expanded' => true,
                    'multiple' => false,
                ))
                ->add('nursing_support', 'checkbox', array(
                    'required' => false,
                ))
                ->add('nursing', new Type\NursingType());
            $builder->addEventSubscriber(new ApplicationDynamicNursingSubscriber());
        }
}

取决于NursingType看起来像

class NursingType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('street')
            ->add('zipcode')
            ->add('city')
            ->add('email')
            ->add('phone');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'Acme\MainBundle\Entity\Nursing'));
    }

事件看起来像(以及我想做的事)

class ApplicationDynamicNursingSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents() {
        return array(
            FormEvents::POST_BIND => 'onPostBind',
        );
    }

    public function onPostBind(FormEvent $event) {
        $data = $event->getData();
        $form = $event->getForm();
        if (!$data->getNursingSupport()) {
            $data->setNursing(NULL);
            $form->get('nursing')->setRequired(false);
        }
    }
}

字段没有方法setRequired,因此我的事件脚本在表单提交时失败。 当未选中复选框nursing时,如何让Symfony2不要求实体nursing_support

1 个答案:

答案 0 :(得分:1)

为什么不尝试使用Callback方法在实体上使用构建验证来确定是否需要某个字段,而不是挂钩到表单事件进行验证。

http://symfony.com/doc/current/reference/constraints/Callback.html