src/Controller/ProductController.php line 54

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Product;
  4. use App\Entity\ProductCategory;
  5. use App\Form\ProductType;
  6. use App\Repository\ProductRepository;
  7. use App\Repository\CategoryRepository;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. #[Route('/product')]
  14. class ProductController extends AbstractController
  15. {
  16.     /**
  17.      * サービスパラメータからボタンラベルやProduct情報に関連するパラメータを取得します。
  18.      *
  19.      * @return array ボタンラベルやProduct情報に関連するテンプレート用のラベル配列
  20.      */
  21.     private function getTemplateLabels(): array
  22.     {
  23.         // services.yaml labels配列を一括取得
  24.         return $this->getParameter('labels');
  25.     }
  26.     /**
  27.      * 指定された Product エンティティにラベルを適用した ProductType フォームを生成します。
  28.      *
  29.      * @param Product $product フォームの対象となる Product エンティティ
  30.      * @return \Symfony\Component\Form\FormInterface ラベルが適用された ProductType フォームインスタンス
  31.      */
  32.     private function createProductForm(Product $product): \Symfony\Component\Form\FormInterface
  33.     {
  34.         // ラベルを取得
  35.         $labels $this->getParameter('labels');
  36.         // フォームを作成してラベルを渡す
  37.         return $this->createForm(ProductType::class, $product, [
  38.             'labels' => $labels,
  39.         ]);
  40.     }
  41.     /**
  42.      * 商品一覧画面を表示します。
  43.      *
  44.      * @param ProductRepository $productRepository Product エンティティリポジトリ
  45.      * @return Response 商品一覧ページのレスポンス
  46.      */
  47.     #[Route('/'name'app_product_index'methods: ['GET'])]
  48.     public function index(ProductRepository $productRepository): Response
  49.     {
  50.         return $this->render(
  51.             'product/index.html.twig',
  52.             array_merge(
  53.                 [
  54.                     'products' => $productRepository->findAll(),
  55.                 ],
  56.                 $this->getTemplateLabels()
  57.             )
  58.         );
  59.     }
  60.     /**
  61.      * 新規商品を追加する画面を表示し、フォーム送信時にデータを保存します。
  62.      *
  63.      * @param Request $request HTTPリクエストオブジェクト
  64.      * @param CategoryRepository $categoryRepository Category エンティティリポジトリ
  65.      * @param EntityManagerInterface $entityManager エンティティマネージャ
  66.      * @return Response 新規商品追加ページまたは商品一覧ページのレスポンス
  67.      */
  68.     #[Route('/new'name'app_product_new'methods: ['GET''POST'])]
  69.     public function new(
  70.         Request $request,
  71.         CategoryRepository $categoryRepository,
  72.         EntityManagerInterface $entityManager
  73.     ): Response {
  74.         $product = new Product();
  75.         // 共通関数でフォームを作成        
  76.         $form $this->createProductForm($product);
  77.         $form->handleRequest($request);
  78.         if ($form->isSubmitted() && $form->isValid()) {
  79.             $selectedCategoryIds $form->get('categories')->getData();
  80.             // Productを保存
  81.             $entityManager->persist($product);
  82.             $entityManager->flush();
  83.             // カテゴリリレーションを構築
  84.             foreach ($selectedCategoryIds as $categoryId) {
  85.                 $category $categoryRepository->find($categoryId);
  86.                 if ($category) {
  87.                     $productCategory = new ProductCategory();
  88.                     $productCategory->setProduct($product);
  89.                     $productCategory->setCategory($category);
  90.                     $entityManager->persist($productCategory);
  91.                 }
  92.             }
  93.             $entityManager->flush();
  94.             return $this->redirectToRoute('app_product_index', [], Response::HTTP_SEE_OTHER);
  95.         }
  96.         return $this->renderForm(
  97.             'product/new.html.twig',
  98.             array_merge(
  99.                 [
  100.                     'product' => $product,
  101.                     'form' => $form,
  102.                 ],
  103.                 $this->getTemplateLabels()
  104.             )
  105.         );
  106.     }
  107.     // /**
  108.     //  * 商品詳細を表示します。
  109.     //  *
  110.     //  * @param int $id 商品のID
  111.     //  * @param ProductRepository $productRepository Product エンティティリポジトリ
  112.     //  * @return Response 商品詳細ページのレスポンス
  113.     //  */
  114.     // #[Route('/{id}', name: 'app_product_show', methods: ['GET'])]
  115.     // public function show(int $id, ProductRepository $productRepository): Response
  116.     // {
  117.     //     // 商品を取得
  118.     //     $product = $productRepository->findProductDetailsWithImages($id);
  119.     //     // 商品が見つからなかった場合、カスタムエラーページを表示
  120.     //     if (!$product) {
  121.     //         return $this->render('error.html.twig', [
  122.     //             'product_not_found' => $this->getParameter('labels')['product_not_found']
  123.     //         ]);
  124.     //     }
  125.     //     // 商品が見つかった場合、商品詳細ページを表示
  126.     //     return $this->render(
  127.     //         'product/show.html.twig',
  128.     //         array_merge(
  129.     //             [
  130.     //                 'product' => $product,
  131.     //             ],
  132.     //             $this->getTemplateLabels()
  133.     //         )
  134.     //     );
  135.     // }
  136.     /**
  137.      * 商品編集画面を表示し、フォーム送信時にデータを更新します。
  138.      *
  139.      * @param int $id 商品のID
  140.      * @param Request $request HTTPリクエストオブジェクト
  141.      * @param ProductRepository $productRepository Product エンティティリポジトリ
  142.      * @param CategoryRepository $categoryRepository Category エンティティリポジトリ
  143.      * @param EntityManagerInterface $entityManager エンティティマネージャ
  144.      * @return Response 商品編集ページまたは商品一覧ページのレスポンス
  145.      */
  146.     #[Route('/{id}/edit'name'app_product_edit'methods: ['GET''POST'])]
  147.     public function edit(
  148.         int $id,
  149.         Request $request,
  150.         ProductRepository $productRepository,
  151.         CategoryRepository $categoryRepository,
  152.         EntityManagerInterface $entityManager
  153.     ): Response {
  154.         // $product = $productRepository->find($id);
  155.         // 商品を取得
  156.         $product $productRepository->findProductDetailsWithImages($id);
  157.         // 商品が見つからなかった場合、カスタムエラーページを表示
  158.         if (!$product) {
  159.             return $this->render('error.html.twig', [
  160.                 'product_not_found' => $this->getParameter('labels')['product_not_found']
  161.             ]);
  162.         }
  163.         $price02Values $product->getPrice02();
  164.         $form $this->createForm(ProductType::class, $product, [
  165.             'labels' => $this->getTemplateLabels(),
  166.             'price02_initial' => isset($price02Values[0]) ? $price02Values[0] : // 初期値を設定
  167.         ]);
  168.         $form->handleRequest($request);
  169.         // 商品画像のリストを取得
  170.         $productImages $product->getProductImages();
  171.         // // $price02の値を取得
  172.         // $price02Values = $product->getPrice02();
  173.         // dump('edit関数',$price02Values);
  174.         // die;
  175.         if ($form->isSubmitted() && $form->isValid()) {
  176.             // 現在のProductCategoryリレーションを削除
  177.             // foreach ($product->getProductCategories() as $existingProductCategory) {
  178.             //     $entityManager->remove($existingProductCategory);
  179.             // }
  180.             $newPrice02 $form->get('price02')->getData();
  181.             foreach ($product->getProductClasses() as $ProductClass) {
  182.                 $ProductClass->setPrice02($newPrice02);
  183.             }
  184.     
  185.             $entityManager->flush();
  186.             // 新しいカテゴリリレーションを追加
  187.             $selectedCategoryIds $form->get('categories')->getData();
  188.             foreach ($selectedCategoryIds as $categoryId) {
  189.                 $category $categoryRepository->find($categoryId);
  190.                 if ($category) {
  191.                     $productCategory = new ProductCategory();
  192.                     $productCategory->setProduct($product);
  193.                     $productCategory->setCategory($category);
  194.                     $entityManager->persist($productCategory);
  195.                 }
  196.             }
  197.             $entityManager->flush();
  198.             return $this->redirectToRoute('app_product_index');
  199.         }
  200.         return $this->render(
  201.             'product/edit.html.twig',
  202.             array_merge(
  203.                 [
  204.                     'product' => $product,
  205.                     'form' => $form->createView(),
  206.                     // 画像リストをテンプレートに渡す
  207.                     'productImages' => $productImages,
  208.                     // ★
  209.                     'price02Values' => $price02Values,
  210.                 ],
  211.                 $this->getTemplateLabels()
  212.             )
  213.         );
  214.     }
  215.     /**
  216.      * 商品を削除します。
  217.      *
  218.      * @param int $id 商品のID
  219.      * @param Request $request HTTPリクエストオブジェクト
  220.      * @param ProductRepository $productRepository Product エンティティリポジトリ
  221.      * @param EntityManagerInterface $entityManager エンティティマネージャ
  222.      * @return Response 商品一覧ページへのリダイレクトレスポンス
  223.      */
  224.     #[Route('/{id}'name'app_product_delete'methods: ['POST'])]
  225.     public function delete(
  226.         int $id,
  227.         Request $request,
  228.         ProductRepository $productRepository,
  229.         EntityManagerInterface $entityManager
  230.     ): Response {
  231.         $product $productRepository->find($id);
  232.         // 商品が見つからなかった場合、カスタムエラーページを表示
  233.         if (!$product) {
  234.             // throw $this->createNotFoundException('登録商品はありません');
  235.             return $this->render('error.html.twig', [
  236.                 'product_not_found' => $this->getParameter('labels')['product_not_found']
  237.             ]);
  238.         }
  239.         if ($this->isCsrfTokenValid('delete' $product->getId(), $request->request->get('_token'))) {
  240.             $entityManager->remove($product);
  241.             $entityManager->flush();
  242.         }
  243.         return $this->redirectToRoute('app_product_index', [], Response::HTTP_SEE_OTHER);
  244.     }
  245. }