我的表单类型看起来像
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
?