首页 > 解决方案 > 如何在 symfony 5 中不使用表单创建更新功能

问题描述

我想在不使用表单的情况下更新示例联系人实体,我不知道这是我的代码:

/** 
 * @Route("/UpdateContact/{id}",name="editcontact")
 */
public function EditContact(Contact $Contact , Request $request ,ManagerRegistry $manager)
{

    $contact = $this->getDoctrine()
        ->getRepository(Contact::class)
        ->findAll();

    $request->get('responsable');
    $request->get('telephone');
    $request->get('email');
    $request->get('note');
     
    $contact->setResponsable($request->request->get('responsable'))
            ->setTelephone ($request->request->get('telephone'))
            ->setEmail ($request->request->get('email'))
            ->setNote ($request->request->get('note'));
            $manager->persist($contact);
            $manager->flush();
    return $this->render('companyProfile.html.twig', [
        // 'contactform'=>$contactform->createView(),
        'Contact' => $contact,
     ]);
  }

它不起作用,所以如果有人知道如何在没有表格的情况下更新,请帮助我,我现在被卡住了

标签: sql-updateeditsymfony-formssymfony5

解决方案


你需要EntityManagerInterface而不是ManagerRegistry

所以你的代码需要是这样的:

<?php

public function EditContact(Contact $contact, Request $request, EntityManagerInterface $em)
{
        $contact
            ->setResponsable($request->get('responsable'))
            ->setTelephone($request->get('telephone'))
            ->setEmail($request->get('email'))
            ->setNote($request->get('note'))
        ;

        $em->persist($contact);
        $em->flush();

        // rest of your code
}

请参阅https://symfony.com/doc/current/doctrine.html#persisting-objects-to-the-database


推荐阅读