Refresh session in symfony2 for shopping cart
I have the following code:
public function addAction(Request $request){
//Get submited data
// Get Value from session
$sessionVal = $this->get('session')->get('aBasket');
// Append value to retrieved array.
$aBasket = $request->request->all();
if(count($sessionVal) > 0) {
foreach ($sessionVal as $key=>$value) {
if($aBasket['product_id'] == $sessionVal[$key]['product_id'])
{
$sessionVal[$key]['product_quantity'] = $sessionVal[$key]['product_quantity'] + $aBasket['product_quantity'];
$this->get('session')->set('aBasket', $sessionVal);
}
else
{
$sessionVal[] = $aBasket;
$this->get('session')->set('aBasket', $sessionVal);
}
}
}
else
{
$sessionVal[] = $aBasket;
$this->get('session')->set('aBasket', $sessionVal);
}
// Set value back to session
return $this->redirect($this->generateUrl('shop_desktop_homepage'));
}
The idea is to increase the number of the existing product if the id doesn't match, then add them. Now the quantity has been correctly added, but the product has also been added. Take a decision? Help me please...
source to share
You can simplify your code, I think your session array will look something like this:
array(
'11' =>array('id'=>'11','title'=>'some product','product_quantity'=>2),
'12' =>array('id'=>'12','title'=>'some product','product_quantity'=>1),
'13' =>array('id'=>'13','title'=>'some product','product_quantity'=>3),
);
the key in your basket array will be the product id, so it won't be possible to duplicate the product in the array now below the code. I removed the loop foreach
, instead I only used the if check if the if(isset($sessionVal[$aBasket['product_id']]))
product already exists in the basket array, putting the product id instead of the key, for example if(isset($sessionVal['11']))
if it exists, then increment the quantity by one, if not, then insert the product into the basket array
public function addAction( Request $request ) {
$sessionVal = $this->get( 'session' )->get( 'aBasket' );
$aBasket = $request->request->all();
if(isset($sessionVal[$aBasket['product_id']])){
$sessionVal[$aBasket['product_id']]['product_quantity'] += 1;
}else{
$sessionVal[$aBasket['product_id']]= array(
'id'=>$aBasket['product_id'],
'product_quantity' => 1,
'other_info' => '...'
);
}
$this->get( 'session' )->set( 'aBasket', $sessionVal );
return $this->redirect( $this->generateUrl( 'shop_desktop_homepage' ) );
}
source to share