dion
dion

Reputation: 35

How to store a many values in Symfony session inside same array with for many request?

I working on bookstore project, I have a list of books with button Add to Cart , click on that should save the ID of book in session by some name. But problem for me is how can save many this ID inside session so I can later access them inside foreach?

/**
 * @Route("/cart/{bookId}", name="AppBundle_Book_addingToCartAction")
 */
public function addingToCartAction(Request $request, int $bookId)
{
    // getting session 
    $sessionCart = $request->getSession();

    // when user click on button Add to Cart , i send ID of book here(and others book IDs),
    // so i need to save that ID inside a session(i was thinking making of some array
    // with all this values), so how can I do this,i trying like this:
    $sessionCart->set('BookIDs', array('Book'.$bookId => $bookId));

    return $this->render('AppBundle:Books:shopingCart.html.twig', array(
        'id' => $bookId,
    ));
}

Upvotes: 0

Views: 862

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94682

The simplest solution would be this I think.

1) create a key in the session object for your cart, then you can segregate it from other things in the session.

2) get and set the contents of that in the same way you would any other array.

3) Just keep the bookId in there unless you have some need for anything else.

/**
 * @Route("/cart/{bookId}", name="AppBundle_Book_addingToCartAction")
 */
public function addingToCartAction(Request $request, int $bookId)
{
    // getting session 
    $sessionCart = $request->getSession();

    $cart = $sessionCart->get('cart');

    $cart[] = $bookId;

    $sessionCart->set('cart', $cart);

    return $this->render('AppBundle:Books:shopingCart.html.twig', array('id' => $bookId));
}

Upvotes: 1

actarus
actarus

Reputation: 46

you should get the array from the session variable. And add the new book Id in this array. Otherwise you will override this variable.

$arrayOfBook = $sessionCart->get('BookIDs');
if ($arrayOfBook == null){
  arrayOfBook = [];
}
arrayOfBook[] = $bookId;
$sessionCart->set('BookIDs', arrayOfBook);

Upvotes: 0

Related Questions