来自NodeJS环境,这似乎是一个无需动脑筋的事情,但我不知何故没有弄清楚。
给定函数:
/**
* @Route("/", name="create_stuff", methods={"POST"})
*/
public function createTouristAttraction($futureEntity): JsonResponse
{
...
}
让futureEntity具有与我的PersonEntity相同的结构。
将$futureEntity映射到PersonEntity的最佳方式是什么?
我试图手动分配它,然后运行我的验证,这似乎是有效的,但我认为这是麻烦的,如果一个模型有超过30个字段…
提示:我在Symfony 4.4
谢谢!
Doc:如何在Symfony中处理表单
-
你需要安装Form bundle:
composer require symfony/form
(或者composer require form
如果你已经安装了Flex bundle) -
创建一个新的AppFormPersonType类来设置表单的字段和更多内容:doc
在<<li>strong>应用程序控制器 PersonController ,当您实例化表单时,只需传递PersonType::class
作为第一个参数,并将一个新的空Person实体作为第二个参数(表单包将负责其余部分):
$person = new Person();
$form = $this->createForm(PersonType::class, $person);
整个控制器代码:
<?php
namespace AppController;
use AppEntityPerson;
use AppFormPersonType;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyBundleFrameworkBundleControllerAbstractController;
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();
// (optional) success notification
$this->addFlash('success', 'New person saved!');
// (optional) redirect
return $this->redirectToRoute('person_success');
}
return $this->renderForm('person/new.html.twig', [
'personForm' => $form->createView(),
]);
}
}
- 在templates/person/new.html.twig中显示表单的最小值:在你想要的地方添加
{{ form(personForm) }}
。