來自 NodeJS 環境,這似乎很簡單,但我不知何故沒有弄明白。
給定功能:
/**
* @Route("/", name="create_stuff", methods={"POST"})
*/
public function createTouristAttraction($futureEntity): JsonResponse
{
...
}
讓futureEntity與我的 PersonEntity 具有相同的結構。
將 $futureEntity 映射到 PersonEntity的最佳方法是什么?
我嘗試手動分配它,然后運行我的驗證,這似乎有效,但我認為如果模型有超過 30 個欄位,這很麻煩......
提示:我在 Symfony 4.4 上
謝謝!
uj5u.com熱心網友回復:
檔案:如何在 Symfony 中處理表單
您需要安裝 Form 捆綁包:(
composer require symfony/form或者composer require form如果您安裝了 Flex 捆綁包)創建一個新的App\Form\PersonType類來設定表單的欄位等等:doc
在App\Controller\PersonController中,當您實體化 Form 時,只需將
PersonType::class其作為第一個引數傳遞,并將一個新的空 Person 物體作為第二個引數傳遞(Form 包將處理其余部分):
$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(),
]);
}
}
- 在templates/person/new.html.twig中顯示表單的最低要求:只需添加
{{ form(form) }}您想要的位置。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/461388.html
上一篇:在SpringAuthorizationServer(0.2.3 )中支持并發全堆疊MVC(session)認證以及無狀態JWT認證
