Last active
February 13, 2025 18:27
-
-
Save lodestar-sr/d9b7922700cfc3df1176bb5a73b4f6ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Controller; | |
use App\Entity\Product; | |
use App\Form\ProductType; | |
use App\Repository\ProductRepository; | |
use Doctrine\ORM\EntityManagerInterface; | |
use Psr\Log\LoggerInterface; | |
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\HttpFoundation\Response; | |
use Symfony\Component\Routing\Annotation\Route; | |
use Symfony\Component\Validator\Validator\ValidatorInterface; // For manual validation | |
class ProductController extends AbstractController | |
{ | |
/** | |
* @Route("/product/new", name="product_new", methods={"GET","POST"}) | |
*/ | |
public function new(Request $request, EntityManagerInterface $entityManager, LoggerInterface $logger, ValidatorInterface $validator): Response | |
{ | |
$product = new Product(); | |
$form = $this->createForm(ProductType::class, $product); | |
$form->handleRequest($request); | |
if ($form->isSubmitted() && $form->isValid()) { // Form validation | |
// Manual Validation (if needed for more complex checks not covered by annotations) | |
$errors = $validator->validate($product); | |
if (count($errors) > 0) { | |
foreach ($errors as $error) { | |
$this->addFlash('error', $error->getMessage()); // Display errors to the user | |
} | |
return $this->render('product/new.html.twig', [ | |
'form' => $form->createView(), | |
]); // Re-render the form with error messages | |
} | |
try { | |
$entityManager->persist($product); | |
$entityManager->flush(); | |
$this->addFlash('success', 'Product created successfully!'); // User feedback | |
return $this->redirectToRoute('product_index'); // Redirect after successful save | |
} catch (\Exception $e) { // Catch database exceptions | |
$logger->error(sprintf('Error saving product: %s', $e->getMessage()), ['exception' => $e, 'product' => $product]); | |
$this->addFlash('error', 'An error occurred while saving the product. Please try again later.'); // User-friendly message | |
return $this->render('product/new.html.twig', [ | |
'form' => $form->createView(), | |
]); // Re-render the form | |
} | |
} | |
return $this->render('product/new.html.twig', [ | |
'form' => $form->createView(), | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment