Symfony sylius如何在不使用构造函数的情况下在表单类型类中获取容器?

Symfony sylius如何在不使用构造函数的情况下在表单类型类中获取容器?,symfony,sylius,Symfony,Sylius,我想在表单类型类中使用服务容器,但是$this->container总是返回null 这是我的表格 <?php namespace St\AppBundle\Form\Type; use Sylius\Bundle\CoreBundle\Form\Type\ShippingMethodType as BaseShippingMethodType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Componen

我想在表单类型类中使用服务容器,但是$this->container总是返回null

这是我的表格

<?php

namespace St\AppBundle\Form\Type;

use Sylius\Bundle\CoreBundle\Form\Type\ShippingMethodType as BaseShippingMethodType;
use Symfony\Component\Form\FormBuilderInterface;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

class ShippingMethodType extends BaseShippingMethodType implements ContainerAwareInterface
{

    protected $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder
            ->add('file', 'file', ['required' => false])
        ;

        var_dump($this->container);

        $builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event)  {

            $data = $event->getData();

            $tools = $this->container->get('a_tools');
            $tools->saveImage($data);
        });
    }

}

为什么setter注入在这种情况下不起作用?

我猜您的代码使用的是新操作符$shippingMethodType=新的shippingMethodType();原则上,可以通过表单类型的选项将变量传递给表单类型。如果
a_-tools
parameters.yml
中的一个参数,那么它在控制器中可用
$tools=$this->container->getParameter('a_-tools')。然后可以使用
$tools=null,
在表单type
configureOptions()
中设置变量
$tools
。设置好后,可以使用
ShippingMethodType():class,['tools'=>$tools]
调用表单。或者类似的:)!表单由资源控制器通过updateAction创建:$form=$this->resourceFormFactory->create($configuration,$resource);a_tools是服务我猜你的代码使用的是新的操作符$shippingMethodType=新的shippingMethodType();原则上,可以通过表单类型的选项将变量传递给表单类型。如果
a_-tools
parameters.yml
中的一个参数,那么它在控制器中可用
$tools=$this->container->getParameter('a_-tools')。然后可以使用
$tools=null,
在表单type
configureOptions()
中设置变量
$tools
。设置好后,可以使用
ShippingMethodType():class,['tools'=>$tools]
调用表单。或者类似的:)!表单由资源控制器通过updateAction创建:$form=$this->resourceFormFactory->create($configuration,$resource);a_工具是一种服务
a_shipping_method.form.type:
    class: St\AppBundle\Form\Type\ShippingMethodType
    calls:
      - [setContainer, ['@service_container']]
    tags:
      - { name: form.type, alias: sylius_shipping_method }