Search code examples
formssymfonysymfony-2.2

Symfony2 set entity in form to be optional depending on checkbox


My form type looks like

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

Depending NursingType looks like

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'));
    }

The event looks like (and what I want to do)

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);
        }
    }
}

There is no method setRequired for fields, so my event script fails on form submit. How can I get Symfony2 to make the entity nursing not required, when checkbox nursing_support is not checked?


Solution

  • Instead of hooking into the form event to validate, why don't you try using the build in validation on the entity using the Callback method to determine if a certain field is required or not.

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