繁体   English   中英

通过关系发现了一个新实体-Symfony 4

[英]A new entity was found through the relationship - Symfony 4

我在通过表单保留一个实体时遇到麻烦。

我的情况是:

在索引页面中,我有一个简单的表单,该表单使用EntityType检索实体。 此表单没有数据类,我只是在使用它来保存包含此Entity的会话变量,并且希望它可以通过我的App插入表单中。 这是完整的控制器:

class HomeController extends Controller{

/**
* @Route("/", name="index")
*/
public function index(Request $request) {
    $session = $this->get('session');
    dump($session->get('empresa'));

    $usuario = $this->getUser();

    $empresas = $usuario->getEmpresas();

    $form = $this->createFormBuilder()
        ->add('empresa', EntityType::class, [
                'class' => Empresa::class,
                'choice_label' => 'razaoSocial',
                'choice_value' => 'id',
                'label' => 'Empresa:',
                'choices' => $usuario->getEmpresas()
            ])
        ->add('selecionar', SubmitType::class, ['label' => 'Selecionar'])
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
        $session->set('empresa', $data['empresa']);
        return $this->redirectToRoute('index');
    }

    return $this->render('home/index.html.twig', ['form' => $form->createView()]);
}

它可以按预期工作,重新加载页面时,所有数据都会出现在转储中。

现在在另一个控制器中,我有一个表单,该表单可以持久保存与我在转储中保存的实体相关的实体(其OneToMany关系)。

public function cadastrarRapido(Request $request){

    $usuario = $this->getUser();

    $session = $this->get('session');
    dump($session->get('empresa'));

    $produto = new Produto();

    $form = $this->formFactory->create(ProdutoRapidoType::class, $produto);
    $form->add('cadastrar', SubmitType::class, ['label' => 'Cadastrar']);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()){
        $produto = $form->getData();
        $empresa = $session->get('empresa');
        $produto->setEmpresa($empresa);
        $this->entityManager->persist($produto);
        $this->entityManager->flush();

        $this->flashBag->add('success', 'Produto adicionado!');

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

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

因此,当我尝试提交此表单时,出现以下错误

A new entity was found through the relationship 'App\Entity\Produto#empresa' that was not configured to cascade persist operations for entity: 
App\Entity\Empresa@000000006e7adf9a000000004feede5f. 
To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). 

我没有尝试更新我的其他实体,因此不是使用cascade = persist的情况。 我要做的就是将外键保存在我要保留的实体中,并将​​其对象ID保存在会话变量中。

我是否可以正确地在会话变量中捕获对象? 如果我使用$session->set('empresa', $data['empresa']->getId()); 提交表单时出现此错误

Argument 1 passed to App\Entity\Produto::setEmpresa() must be an instance of App\Entity\Empresa or null, integer given

我想我想做的事情很简单,但是我不知道这是否是正确的方法。 谢谢您的帮助

(注:教义关系是实体到实体),因此,当您将变量$ empresa分配给produto时,它应该是一个对象(实体)

$produto->setEmpresa($empresa); //$empressa should be App\Entity\Empresa object

但是,您可以将empresaId保存在会话中,但这不起作用。

你能做的是

public function cadastrarRapido(Request $request){

    $usuario = $this->getUser();

    $session = $this->get('session');

    $empresaId = $session->get('empresa');
    $repository = $this->getDoctrine()->getRepository(Empresa::class);

    // look for a single Empresa by its primary key (usually "id")
    $empresa = = $repository->find($id);

    $produto = new Produto();

    $form = $this->formFactory->create(ProdutoRapidoType::class, $produto);
    $form->add('cadastrar', SubmitType::class, ['label' => 'Cadastrar']);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $produto = $form->getData();
        $empresa = $session->get('empresa'); // now this embpresa is an object
        $produto->setEmpresa($empresa);
        $this->entityManager->persist($produto);
        $this->entityManager->flush();

        $this->flashBag->add('success', 'Produto adicionado!');

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM