Php 在表单事件symfony中动态禁用表单

Php 在表单事件symfony中动态禁用表单,php,symfony,symfony-forms,Php,Symfony,Symfony Forms,我有很多实体,每个实体都有自己的表单类型。一些实体实现了包含方法FooBarInterface::isEnabled()的FooBarInterface 我想创建一个表单扩展,在所有表单上检查数据类,如果实体实现了FooBarInterface和entity::isEnabled()返回false,则禁用表单 <?php namespace AppBundle\Form\Extension; use Symfony\Component\Form\AbstractTypeExtension

我有很多实体,每个实体都有自己的表单类型。一些实体实现了包含方法
FooBarInterface::isEnabled()的
FooBarInterface

我想创建一个表单扩展,在所有表单上检查数据类,如果实体实现了
FooBarInterface
entity::isEnabled()
返回false,则禁用表单

<?php
namespace AppBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class MyExtension extends AbstractTypeExtension
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $dataClass = $builder->getDataClass();
        if ($dataClass) {
            $reflection = new \ReflectionClass($dataClass);

            if ($reflection->implementsInterface(FooBarInterface::class)) {
                $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $formEvent) {
                    $data = $formEvent->getData(); 
                    if ($data && !$data->isEnabled()) {
                        // todo this need disable all form with subforms
                    }
                });
            }
        }
    }

    public function getExtendedType()
    {
        return 'form';
    }
}

我用方法创建了表单扩展

    public function finishView(FormView $view, FormInterface $form, array $options) 
    {
        $dataClass = $form->getConfig()->getDataClass();
        if ($dataClass) {
            $reflection = new \ReflectionClass($dataClass);

            if ($reflection->implementsInterface(FooBarInterface::class)) {
                /** @var FooBarInterface$data */
                $data = $form->getData();

                if ($data && !$data ->isEnabled()) {
                   $this->recursiveDisableForm($view);
                }
            }
        }
    }

    private function recursiveDisableForm(FormView $view) 
    {
        $view->vars['disabled'] = true;
        foreach ($view->children as $childView) {
            $this->recursiveDisableForm($childView);
        }
    }
对于在提交数据时禁用更改,我使用
FormEvents::PRE_UPDATE
Event:

    /**
     * @param PreUpdateEventArgs $args
     */
    public function preUpdate(PreUpdateEventArgs $args)
    {
        $entity = $args->getEntity();

        if (!$entity instanceof DataStateInterface) {
            return;
        }

        if (!$entity->isEnabled()) {
            $args->getEntityManager()->getUnitOfWork()->clearEntityChangeSet(spl_object_hash($entity));
        }
    }