Skip to content
Advertisement

Symfony 4 – Autowiring not working

I have a form that write values to an specific Entity, and I am trying to edit the information through a function in the controller, pretty simple.

BancoController.php

<?php

namespace AppController;

use AppEntityBanco;
use AppFormBancoType;
use AppRepositoryBancoRepository;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentFormFormFactoryInterface;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationRedirectResponse;
use SymfonyComponentHttpFoundationSessionFlashFlashBagInterface;
use SymfonyComponentHttpFoundationSessionSessionInterface;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentRoutingRouterInterface;
use SymfonyComponentSecurityCoreAuthorizationAuthorizationCheckerInterface;
use SymfonyComponentHttpKernelExceptionUnauthorizedHttpException;
use SensioBundleFrameworkExtraBundleConfigurationSecurity;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;

class BancoController{

    private $twig;

    private $bancoRepository;

    private $formFactory;

    private $entityManager;

    private $router;

    private $flashBag;

    private $authorizationChecker;

    public function __construct(
        Twig_Environment $twig, 
        BancoRepository $bancoRepository, 
        FormFactoryInterface $formFactory, 
        EntityManagerInterface $entityManager, 
        RouterInterface $router,
        FlashBagInterface $flashBag,
        AuthorizationCheckerInterface $authorizationChecker
    ){
        $this->twig = $twig;
        $this->bancoRepository = $bancoRepository;
        $this->formFactory = $formFactory;
        $this->entityManager = $entityManager;
        $this->router = $router;
        $this->flashBag = $flashBag;
        $this->authorizationChecker = $authorizationChecker;
    }

    /**
    * @Route("/cadastro/bancos", name="cadastro_banco")
    */
    public function index(TokenStorageInterface $tokenStorage){

        $usuario = $tokenStorage->getToken()->getUser();

        $html = $this->twig->render('bancos/index.html.twig', [
            'bancos' => $this->bancoRepository->findBy(array('usuario' => $usuario))
        ]);

        return new Response($html);
    }

    /**
    * @Route("/banco/{id}", name="editar")
    */
    public function editarBanco(Banco $banco, Request $request) {

        $form = $this->formFactory->create(
            BancoType::class,
            $banco
        );
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()){
            $this->entityManager->flush();

            return new RedirectResponse($this->router->generate('cadastro_banco'));
        }

        return new Response(
            $this->twig->render(
                'bancos/cadastro.html.twig',
                ['form' => $form->createView()]
            ));
    }

    /**
    * @Route("/cadastro/cadastrar-banco", name="cadastro_banco-nova")
    */
    public function cadastrar(Request $request, TokenStorageInterface $tokenStorage){

        $usuario = $tokenStorage->getToken()->getUser();

        $banco = new Banco();
        $banco->setUsuario($usuario);

        $form = $this->formFactory->create(BancoType::class, $banco);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()){
            $this->entityManager->persist($banco);
            $this->entityManager->flush();

            return new RedirectResponse($this->router->generate('cadastro_banco'));
        }

        return new Response(
            $this->twig->render(
                'bancos/cadastro.html.twig',
                ['form' => $form->createView()]
        )
        );
    }
}

The problem is, when I access /banco/{id}, I get the error:

"Cannot autowire argument $banco of "AppControllerBancoController::editarBanco()": it references class "AppEntityBanco" but no such service exists."

My service.yaml is all default, so I guess it should work automatically. The entities doesn’t show in bin/console debug:container.

If I declare manually the Entity in services.yaml like this

AppEntityBanco:
    autowire: true
    autoconfigure: true
    public: false

it works, but now when I access /banco/{id} the form comes empty without the information that exists in the database, and if I type something and submit it, nothing changes in the database.

If I go to the debug toolbar and check the query, it appears that it is querying the ID of the user logged in, and not the ID of the Entity ‘Banco’.

Btw, this Entity Table has a FK user_id. Maybe that’s where lies the problem? I am lost so I need a little help. I am new to PHP/Symfony. Thank you

Advertisement

Answer

The Symfony will autowire the Entity but it will be an empty one. Better way is to autowire the Repository, get the ID from the Request and fetch the Banco from the Repository by it’s ID.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement