0

我的表单类型看起来像

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字段方法,所以我的事件脚本在表单提交时失败。当未选中复选框时,如何让 Symfony2 使实体nursing不需要nursing_support

4

1 回答 1

1

与其挂钩表单事件进行验证,不如尝试使用 Callback 方法在实体上使用内置验证来确定是否需要某个字段。

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

于 2013-03-28T16:18:07.580 回答