Answer the question
In order to leave comments, you need to log in
How to merge two routes correctly?
There are two routes:
/**
* @Route("/create", name="create")
*/
public function createAction(Request $request) {
$post = new Post();
$form = $this->createForm(PostType::class, $post);
if ($request->isMethod($request::METHOD_POST)) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $post->getImage();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getParameter('images_directory'), $fileName);
$post->setImage($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirect($this->generateUrl('home'));
}
}
return $this->render('ImagenariumBundle:Post:create.html.twig', ['form' => $form->createView(),]);
}
/**
* @Route("/{id}/edit", requirements={"id": "[1-9]\d*"}, name="edit")
*/
public function editAction(Request $request, Post $post) {
$form = $this->createForm(PostType::class, $post);
if ($request->isMethod($request::METHOD_POST)) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $post->getImage();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getParameter('images_directory'), $fileName);
$post->setImage($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirect($this->generateUrl('home'));
}
}
return $this->render('ImagenariumBundle:Post:edit.html.twig', ['form' => $form->createView(),]);
}
Answer the question
In order to leave comments, you need to log in
I don’t see anything wrong with different actions for creating and editing an entity, but if you really need it, then try using the default value in the routing:
And in the action, check if the post is not found, then create a new one.
Notes on the code:
1) Saving the file to the server should be moved to a separate service.
2) $em->persist($post);
in case of editing is not required.
3) $form->isSubmitted()
can be removed, because checked inside$form->isValid()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question