phparrayssymfonysession

Symfony 5.2 add to session array


I want to add product to my session array but always it overwriting existing product and is only one.

    /**
     * @Route("/{id}", name="add", methods={"GET"})
    */

  public function add(Product $product, Request $request): Response
   {
       $session= $request->getSession();
       $session->set('products', array(
           'list' => $product,
       ));
       $this->addFlash('success', 'add');
       return $this->render('index.html.twig', [
           'product' => $product
        ]);
    }

any suggestion?


Solution

  • You overwrite the session variable each time instead of adding a new product. Try to get the product, add new product, then set the session:

    public function add(Product $product, Request $request): Response
    {
       $session= $request->getSession();
       $products = $session->get('products', []);
       $session->set('products', array(
           'list' => array_merge($products['list'] ?? [], [$product]) 
       ));
       $this->addFlash('success', 'add');
       return $this->render('index.html.twig', [
           'product' => $product
        ]);
    }
    

    If you want to have distinct products you may use product['id'] as the key

    public function add(Product $product, Request $request): Response
    {
       $session= $request->getSession();
       $products = $session->get('products', []);
       $products[$product['id']] = $product;
       $session->set('products', products);
       $this->addFlash('success', 'add');
       return $this->render('index.html.twig', [
           'product' => $product
        ]);
    }