将 POST 请求转换为 Doctrine 实体

Convert POST Request to Doctrine Entity

来自 NodeJS 环境,这似乎很容易,但我不知何故没有弄明白。

给定函数:

    /**
     * @Route("/", name="create_stuff", methods={"POST"})
     */
    public function createTouristAttraction($futureEntity): JsonResponse
    {
      ...
     }

futureEntity 与我的 PersonEntity 具有相同的结构。

将 $futureEntity 映射到 PersonEntity 的最佳方法是什么?

我尝试手动分配它,然后 运行 我的验证似乎有效,但我认为如果模型有超过 30 个字段,这会很麻烦...

提示:我正在使用 Symfony 4.4

谢谢!

文档:How to process forms in Symfony

  1. 您需要安装 Form 捆绑包:composer require symfony/form(或者 composer require form 如果您安装了 Flex 捆绑包)

  2. 创建一个新的 App\Form\PersonType class 来设置您的表单的字段和更多:doc

  3. App\Controller\PersonController中,当你实例化Form时,只需将PersonType::class作为第一个参数传递,并新建一个空的Person实体作为第二个(表单包将处理其余部分):


$person = new Person();
$form = $this->createForm(PersonType::class, $person);

整个控制器代码:

<?php

namespace App\Controller;

use App\Entity\Person;
use App\Form\PersonType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class PersonController extends AbstractController
{

    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager) {
        $this->entityManager = $entityManager;
    }

    /**
     * @Route("/person/new", name="person_new")
     */
    public function new(Request $request): Response
    {
        $person = new Person(); // <- new empty entity
        $form = $this->createForm(PersonType::class, $person);

        // handle request (check if the form has been submited and is valid)
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) { 

            $person = $form->getData(); // <- fill the entity with the form data

            // persist entity
            $this->entityManager->persist($person);
            $this->entityManager->flush();

            // (optionnal) success notification
            $this->addFlash('success', 'New person saved!');

            // (optionnal) redirect
            return $this->redirectToRoute('person_success');
        }

        return $this->renderForm('person/new.html.twig', [
            'personForm' => $form->createView(),
        ]);
    }
}
  1. templates/person/new 中显示您的表单的最小值。html.twig:只需在您想要的地方添加 {{ form(personForm) }}