首页 > 解决方案 > Symfony RedirectToRoute with array paramater

问题描述

I'm working on an upload system based on Symfony 4 and PHPSpreadsheet. My user uploads the excel file. I then create the products/categories... At the end I want to get all categories created. The following Doctrine query :

/**
* @param $user_id
* @return array
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function checkIfNew($user_id): ?array {
    return $this->createQueryBuilder('c')
        ->andWhere('c.categorie_parent_id is NULL')
        ->andWhere('c.created_by = :val')
        ->setParameter('val', $user_id)
        ->getQuery()
        ->getResult()
        ;
}

gets all my categories where created_by is by the user ID, and where Parent is null.

What I want to do is to get an array of all those categories and then redirect the user to a rendered Twig template page where he can make the link. But I don't really understand how to use the parameters... In my Upload I've set this :

$isNew = $this->getDoctrine()
       ->getRepository(Categorie::class)
       ->checkIfNew($this->getUser()->getId());
         if (!is_null($isNew)){
          $this->addFlash('success', 'Catalogue crée avec succès');
          return $this->redirectToRoute('admin.categorie.link', $this->getUser()->getId());
        }

I don't understand how I can use the request to redirect the user correctly using the route :

/**
* @Route("/admin/categories/import", name="admin.categorie.link", methods={"GET|POST"})
* @param Categorie $categories
*/
public function linkImport()
{
    // What TODO here ?
    return $this->render('admin/categories/link.html.twig', compact('categories'));
}

Well I suppose I have to add $isNew as a parameter for my request ? But did I reuse the array after to use this in my twig, and display the element from this array inside my twig.

标签: phpsymfony

解决方案


There is a small error:

If your route is "/admin/categories/import" and you want to transfer a value like "$this->getUser()->getId()" then this should be like

Route "/admin/categories/import/{userId}" and your return would be:

return $this->redirectToRoute('admin.categorie.link', ['userId' => $this->getUser()->getId()]);

and your controller could take the userId as var:

/**
 * @Route("/admin/categories/import/{userId}", name="admin.categorie.link", methods={"GET|POST"})
 */
public function linkImport(int $userId, EntityManagerInterface $em) // var name must be the same as in the route
{
    // What TODO here ?
    $categories = $em->getRepository(Categories::class)->findByUserId($userId);

    return $this->render('admin/categories/link.html.twig', ['categories' => $categories]);
}

Now you can access your categories in twig with {{categories}}


推荐阅读