6
votes

I am trying to call entityManager in formType. I don't get why this is not working.

FormType :

private $manager;

public function __construct(ObjectManager $manager)
{
    $this->manager = $manager;
}

Controller:

$form = $this->createForm(ProductsType::class, $products);

Services:

apx.form.type.product:
    class: ApxDev\UsersBundle\Form\ProductType
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: form.type }

Error:

Catchable Fatal Error: Argument 1 passed to MyBundle\Form\FormType::__construct() must implement interface Doctrine\Common\Persistence\ObjectManager, none given, called in vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php on line 90 and defined

4
Your code looks right. I am guessing you are not loading the services.yml file. Are you able to access other services from your services.yml file? Use bin/console container::debug to verify the service exists. Also checks ProductsType vs ProductType. In fact, the spelling is probably the problem.Cerad

4 Answers

3
votes

Assuming your services.yml file is being loaded and that you copied pasted in the contents then you have a simple typo:

# services.yml
class: ApxDev\UsersBundle\Form\ProductType
should be
class: ApxDev\UsersBundle\Form\ProductsType
1
votes

Let's look at your error

Argument 1 passed to MyBundle\Form\FormType::__construct()

So when you're instantiating FormType we're talking about the argument you pass like so

$form = new \MyBundle\Form\FormType($somearg);

Your definition says

public function __construct(ObjectManager $manager)

Based on the second part of the error

must implement interface Doctrine\Common\Persistence\ObjectManager

it's obvious that ObjectManager is an interface. So what that means is you have to implement that interface in the object you're injecting into your class because that's what you told PHP to expect. What that looks like is this

class Something implements \Doctrine\Common\Persistence\ObjectManager {
    // Make sure you define whatever the interface requires within this class
}
$somearg = new Something();
$form = new \MyBundle\Form\FormType($somearg);
1
votes

You defined your form as a service (in services.yml) but you're not using it as a service. Instead of createForm you should use service container to create form, so change:

$form = $this->createForm(ProductsType::class, $products);

into:

$form = $this->get('apx.form.type.product')

and read more about defining forms as a service

0
votes

Try in services.yml:

apx.form.type.product:
    class: ApxDev\UsersBundle\Form\ProductType
    arguments: 
        - '@doctrine.orm.entity_manager'
    tags:
        - { name: form.type }

Symfony 3.4