tokuimo
tokuimo

Reputation: 95

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

I want to pass the current user into AbstractType. I followed the help from this page here: Access currently logged in user in EntityRepository

Unfortunately - It is not working by me. I'm using 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

That is my Type:

<?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 (...)

Service:

<?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>

I tried to figure out, but I don't really understand the error message. Can someone help? :-)

Upvotes: 1

Views: 2168

Answers (1)

John Cartwright
John Cartwright

Reputation: 5084

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

You need to tag the service as a form type, and only use it by it's alias. Base on your error message, you are probably instantiating the object. Post the contents of your ItemController around 231

Upvotes: 1

Related Questions