检查表单父级是否在Symfony2中有效

时间:2012-12-14 16:55:17

标签: symfony

有任何方法可以知道父表单是否有效。这是代码。它总是抛出:“你不能在未绑定的表单上调用isValid()。”谢谢!!

class FoorType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('field_1') // Required
            ->add('field_2') // Required
            ->add('field_3') // Required
            ->add('bar', 'my_custom_form_type') // Not required
    }
} 

class MyCustomFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::POST_BIND, function(DataEvent $event) {
            $form = $event->getForm();
            $data = $event->getData();

            if ($form->getParent()->isValid()) {
                // Do smething...
            }
        });
    }

    public function getParent()
    {
        return 'text';
    }

    public function getName()
    {
        return 'my_custom_form_type';
    }
}

1 个答案:

答案 0 :(得分:0)

您好找到了解决方案!!

在addEventListener中使用getParent():

$builder->getParent()->addEventListener(FormEvents::POST_BIND, function(DataEvent $event)   
{
     // Code
});