在管理后端,我想提供以下功能:
我相信这是一项微不足道的任务。我创建了实体和表单类型,但我对控制器应该如何表现完全空白。
这是我的控制器:
<?php
declare(strict_types=1);
namespace App\Controller;
// use statements...
class RecipeController extends Controller
{
/**
* @Route("/admin/recipes", name="recipe_index")
* @Method("GET")
*/
public function indexAction(Request $request) : Response
{
// code to fetch paginated list of recipes
// and render it
}
/**
* @Route("/admin/recipes/new", name="recipe_new")
* @Method("POST")
*/
public function newAction(Request $request) : Response
{
$form = $this->createForm(RecipeType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$recipe = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($recipe);
$entityManager->flush();
$this->addFlash(
'success',
'Recipe successfully added!');
return $this->redirectToRoute('recipe_index');
}
return $this->render('Admin/recipe_form.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/admin/recipes/{id}", name="recipe_detail")
* @Method({"GET"})
*/
public function editAction(Request $request, Recipe $recipe) : Response
{
$form = $this->createForm(RecipeType::class,$recipe);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$recipe = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($recipe);
$entityManager->flush();
$this->addFlash(
'success',
'Recipe successfully updated!');
return $this->redirectToRoute('recipe_index');
}
return $this->render('Admin/recipe_form_edit.html.twig', [
'form' => $form->createView(),
'recipe' => $recipe
]);
}
}
这种方法存在一些问题:
由于创建和更新表单没有区别,我想知道如何重用代码?
答案 0 :(得分:1)
我在代码中更正了一些内容:更新表单时不需要保留,在编辑表单时不需要添加对象,表单已经包含数据。您可以为两个视图使用相同的模板和相同的表单。
{{1}}