【问题标题】:How to access Sonata admin pool in form type如何以表单类型访问 Sonata 管理池
【发布时间】:2017-06-11 00:43:19
【问题描述】:

用例

我正在尝试通过在我的 Entity FormType 的 buildForm 方法中定义它来在我的网站的前台管理中重用 sonata_type_model_list :

[...]
->add('position', 'sonata_type_model_list', array(
      'model_manager' => $categoryManager,
))
[...]

但是我不能用

$categoryAdmin = $this
    ->getConfigurationPool()
    ->getAdminByClass("\\Application\\Sonata\\ClassificationBundle\\Entity\\Category");

因为我需要在 AdminClass 中才能使用 getConfigurationPool()

如果有人知道如何在 AdminClass 之外使用 getConfigurationPool(),或者您知道如何声明 sonata_type_model_list 以便在管理类之外使用它?

【问题讨论】:

    标签: symfony sonata-admin sonata


    【解决方案1】:

    解决方案


    感谢@pbenard & @Mawcel 的回答,我将它们结合起来以实现我的目标如下:


    在我的控制器中我创建了我的表单并将$this->container->get('sonata.admin.pool') 注入到它,如下所示:

    $form = $this->createForm(
        new FormType($this->container->get('sonata.admin.pool')), 
        $entity, 
        $options
    );
    

    在我的 formType 中,我添加了属性 $adminPool && __construct 方法:

    private $adminPool;
    
    public function __construct(Pool $adminPool) {
        $this->adminPool = $adminPool;
    }
    

    所以我现在可以通过 buildForm 方法访问 adminPool

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        [...]
        $categoryAdmin = $this
            ->getConfigurationPool()
            ->getAdminByClass("\\Application\\Sonata\\ClassificationBundle\\Entity\\Category"        );
        [...]
    }
    

    【讨论】:

      【解决方案2】:

      您需要在表单类型中注入管理池。

      这是一个例子:

      #services.yml
      
      blast_base_entities.form.type.my:
              class: Blast\BaseEntitiesBundle\Form\Type\MyformType
              tags:
                  - { name: form.type, alias: blast_search_index_autocomplete }
              arguments: [@sonata.admin.pool]
      

      并且在表单类型中:

      use Sonata\AdminBundle\Admin\Pool
      
      Class MyFormType
      {
          private $adminPool;
      
          public function construct(Pool $adminPool)
          {
              $this->adminPool = $adminPool;
          }
      }
      

      然后你就可以检索管理员了

      $this->adminPool->getAdminByClass('Foo');

      【讨论】:

        【解决方案3】:

        正如the doc 所写,也许您可​​以使用sonata.admin.pool 服务。

        $configurationPool = $this->container->get('sonata.admin.pool');
        

        【讨论】:

        • 我没有像 SonataAdmin 那样创建管理员,而是将常规首页转换为“前台管理员”。我正在使用由 app/console 生成的 CRUD,并使用提供的 FormType。在 FormType $this->container 内不可访问,因为它不存在。
        • 问题出在FormType内$this->container不可访问。
        • 当然,这是一个例子,你只需要通过服务发送或者......
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-08
        • 2020-02-18
        • 2015-08-13
        • 2011-04-03
        • 2013-11-25
        • 1970-01-01
        • 2012-07-05
        相关资源
        最近更新 更多