3.2Symfony控制器(Controller)之CRUD

index

/**
 * @Route("/article", name="article_index")
 */
public function index(ArticleRepository $articleRepository): Response
{
    return $this->render('article/index.html.twig', [
        'articles' => $articleRepository->findAll(),
    ]);
}

show

public function show(Product $product): Response
{
    return $this->render('product/show.html.twig', ['product' => $product]);
}

new/create

public function new(Request $request): Response
{
    $product = new Product();
    $form = $this->createForm(ProductType::class, $product);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($product);
        $entityManager->flush();

        return $this->redirectToRoute('product_index', [], Response::HTTP_SEE_OTHER);
    }

    return $this->render('product/new.html.twig', [
        'product' => $product,
        'form' => $form->createView(),
    ]);
}

edit/update

public function edit(Request $request, Product $product): Response
{
    $form = $this->createForm(ProductType::class, $product);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('product_index', [], Response::HTTP_SEE_OTHER);
    }

    return $this->render('product/edit.html.twig', [
        'product' => $product,
        'form' => $form->createView(),
    ]);
}

delete

public function delete(Request $request, Product $product): Response
{
    if ($this->isCsrfTokenValid('delete'.$product->getId(), $request->request->get('_token'))) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->remove($product);
        $entityManager->flush();
    }

    return $this->redirectToRoute('product_index', [], Response::HTTP_SEE_OTHER);
}

原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/php/symfony/6326.html

发表评论

登录后才能评论