Search code examples
phpsymfonyroutescontrollercart

redirectToRoute Previous page on Symfony5


I have a cart functionnality on my website.
I display the cart on two different page (cart.html.twig and home.html.twig) and I can modify the cart on those 2 pages.
When I'm suppose to increment a product+1 with the button I'm redirected to A SINGLE ROUTE.
If the user increment the product on the homepage I want to him to be redirected to the homepage, and if he increment the product on the cart page I want to him to be redirected to the cart page, how im suppose to do this, I'm little bit lost.
There is a way to redirect to the previous page ?

There is the code :

class CartService {

protected $session;
protected $productRepository;

public function __construct(SessionInterface $session, ProductRepository $productRepository){
    $this->session = $session;
    $this->productRepository = $productRepository;
}

public function add(int $id){
    $cart = $this->session->get('cart', []);

    if(isset($cart[$id])){
        $cart[$id]++;
    } else {
        $cart[$id] = 1;
    }

    $this->session->set('cart', $cart);
}

public function remove(int $id) {
    $cart = $this->session->get('cart', []);

    if(isset($cart[$id])){
        if($cart[$id] > 1){
            $cart[$id]--;
        } else {
            unset($cart[$id]);
        }
    }

    $this->session->set('cart', $cart);
}

public function delete(int $id){
    $cart = $this->session->get('cart', []);

    if(isset($cart[$id])){
        unset($cart[$id]);
    }

    $this->session->set('cart', $cart);
}

public function getFullCart() : array{
    $cart = $this->session->get('cart', []);
    
    $cartWithData = [];

    foreach($cart as $id => $quantity){
        $cartWithData[] = [
            'product' => $this->productRepository->find($id),
            'quantity' => $quantity
        ];
    }

    return $cartWithData;
}

public function getTotal(): float{
    $total = 0;

    foreach($this->getFullCart() as $item){
        $total += $item['product']->getPrice() * $item['quantity'];
    }

    return $total;
}

}

THE CONTROLLER of cartpage:

class CartController extends AbstractController{

/**
 * @Route ("/cart", name = "cart")
 */
public function cart(CartService $cartservice){

    return $this->render(
        'users/cart.html.twig',
        [
            'items' => $cartservice->getFullCart(),
            'total' => $cartservice->getTotal()
        ]
    );
}

/**
 * @Route ("/cart/add/{id}", name = "add_cart")
 */
public function add($id, CartService $cartservice, Request $request){
    $cartservice->add($id);

    return $this->redirectToRoute('homepage');
}


/**
 * @Route ("/cart/remove/{id}", name="remove_cart")
 */
public function remove($id, CartService $cartservice){
    $cartservice->remove($id);

    return $this->redirectToRoute('homepage');
}


/**
 * @Route ("/cart/delete/{id}", name="delete_cart")
 */
public function delete($id, CartService $cartservice){
    $cartservice->delete($id);

    return $this->redirectToRoute('homepage');
}

}

And I also display a part of the cart on my homepage, I display the price / name / quantity of the card, the controller of my homepage "HomeController.php":

/**
 * @Route("/", name="homepage")
*/
public function home(ProductRepository $productRepository, CategoryRepository $categoryRepository, CartService $cartService) : Response{
    $productRepository = $this->getDoctrine()->getRepository(Product::class);
    $products = $productRepository->findAll();
    $categories = $categoryRepository->findAll();
    return $this->render(
        'users/home.html.twig',
        [
            'products' => $products,
            'categories' => $categories,
            'total' => $cartService->getTotal(),
            'items' => $cartService->getFullCart()
        ]
    );
}

I tried this on the function add in CartController.php

    /**
 * @Route ("/cart/add/{id}", name = "add_cart")
 */
public function add($id, CartService $cartservice, Request $request){
    $cartservice->add($id);

    $uri = $request->attributes->get("_route");
    return $this->redirectToRoute($uri);
}

but it doesnt work, it say to me "Some mandatory parameters are missing ("id") to generate a URL for route "add_cart"." and the product increment x30. I think the function loop on the route cart/add/{id}.


Solution

  • UPDATE :

    I just need to get the referer like this :

        /**
     * @Route ("/cart/add/{id}", name = "add_cart")
     */
    public function add($id, CartService $cartservice, Request $request){
        $cartservice->add($id);
    
        $route = $request->headers->get('referer');
    
        return $this->redirect($route);
    }
    

    and i get redirect to the previous page