Symfony 4 - 自动装配不起作用 [英] Symfony 4 - Autowiring not working

查看:31
本文介绍了Symfony 4 - 自动装配不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将值写入特定实体的表单,我正在尝试通过控制器中的函数编辑信息,非常简单.

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

BancoController.php

<?php

namespace App\Controller;

use App\Entity\Banco;
use App\Form\BancoType;
use App\Repository\BancoRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

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()]
        )
        );
    }
}

问题是,当我访问/banco/{id} 时,出现错误:

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

"Cannot autowire argument $banco of "App\Controller\BancoController::editarBanco()": it references class "App\Entity\Banco" but no such service exists."

我的 service.yaml 都是默认的,所以我想它应该可以自动工作.实体未显示在 bin/console debug:container 中.

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

如果我像这样在 services.yaml 中手动声明实体

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

App\Entity\Banco:
    autowire: true
    autoconfigure: true
    public: false

它可以工作,但现在当我访问/banco/{id} 时,表单变空,没有数据库中存在的信息,如果我输入内容并提交,数据库中没有任何变化.

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.

如果我转到调试工具栏并检查查询,它似乎查询的是登录用户的 ID,而不是实体Banco"的 ID.

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'.

顺便说一句,这个实体表有一个 FK user_id.也许这就是问题所在?我迷路了,所以我需要一点帮助.我是 PHP/Symfony 的新手.谢谢

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

推荐答案

Symfony 将自动装配实体,但它将是一个空实体.更好的方法是自动装配 Repository,从 Request 中获取 ID,然后通过它的 ID 从 Repository 中获取 Banco.

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.

这篇关于Symfony 4 - 自动装配不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆