【问题标题】:Symfony: how to get values from parameters.yml in an AbstractTypeSymfony:如何从 AbstractType 中的 parameters.yml 中获取值
【发布时间】:2017-03-01 15:25:21
【问题描述】:

我正在尝试从我在 parameters.yml 中声明的数组中获取值

# parameters.yml
parameters:
    ...
    objects: {object1: 1, object2: 2, object3: 3}

但是一旦我尝试使用此代码从该文件中获取“对象”

$builder->add('list', ChoiceType::class, array ('objects' => $this->container->getParameter('categories') ));

我收到以下错误

Notice: Undefined property: Project\Bundle\Form\EntityType::$container

有什么建议吗?

【问题讨论】:

    标签: php forms symfony formbuilder


    【解决方案1】:

    您必须在您的类中注入 ContainerInterface。

    services.yml

    form.my_entity_type:
      class: AppBundle\Form\MyEntityType
      arguments:
        - '@service_container'
      tags:
        - { name: form.type }
    

    MyEntityType

    /** @var ContainerInterface */
    protected $container;
    
    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }
    
    **
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $params = $this->container->getParameter('my-params');
        ....
    

    【讨论】:

    • 只是补充一点,你必须包含(使用):使用 Symfony\Component\DependencyInjection\ContainerInterface;
    【解决方案2】:

    如果您将Project\Bundle\Form\EntityType 声明为a service,您将能够将数据以及它需要的任何其他服务注入其中。当您包含它时,您仍然可以将类型称为EntityType::class,因为 Symfony 将识别该类被定义为服务。

    这会让测试变得更“有趣”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 2012-12-03
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      相关资源
      最近更新 更多