可捕获的致命错误 - __construct() 必须是给定的 Symfony\Component\Security\Core\SecurityContext、none 的实例

Catchable Fatal Error - __construct() must be an instance of Symfony\Component\Security\Core\SecurityContext, none given

我想将当前用户传递给 AbstractType。我在这里遵循了此页面的帮助:Access currently logged in user in EntityRepository

不幸的是 - 它对我不起作用。我正在使用 Symfony 2.6。

Catchable Fatal Error: Argument 1 passed to Checkout\Bundle\ItemBundle\Form\ItemType::__construct() must be an instance of Symfony\Component\Security\Core\SecurityContext, none given, called in /vagrant/src/Checkout/Bundle/ItemBundle/Controller/ItemController.php on line 231 and defined

这是我的类型:

<?php

namespace Checkout\Bundle\ItemBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Doctrine\ORM\EntityRepository;

class ItemType extends AbstractType
{
    protected $securityContext;

    public function __construct(SecurityContext $securityContext)
    {
        $this->securityContext = $securityContext;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $currentUser = $this->securityContext->getToken()->getUser();

        $builder (...)

服务:

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="form.type.item" class="Checkout\Bundle\ItemBundle\Form\ItemType">
            <argument type="service" id="security.context" />
            <tag name="form.type" alias="item" />
        </service>
    </services>
</container>

我想弄清楚,但我不太明白错误信息。有人可以帮忙吗? :-)

看看http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html#creating-your-field-type-as-a-service

您需要将服务标记为表单类型,并且只能通过别名使用它。根据您的错误消息,您可能正在实例化该对象。 Post 你的 ItemController 的内容在 231 左右