T
T
tvsjke2017-08-09 15:06:30
symfony
tvsjke, 2017-08-09 15:06:30

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(),]);
  }

and
/**
   * @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(),]);
  }

In fact, they differ only in two lines. How to write them beautifully (I just started with Symfony)? So far, apart from switch by the name of the route, nothing comes to mind.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg, 2017-08-09
@tvsjke

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()

J
jaxel, 2017-08-09
@jaxel

You do not need to combine routes, but take logic out of controllers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question