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 increment the quantity of an existing product, if id not corespond then add them. Now the quantity is correct added, but and the product is also added.Exist a solution?? Help me please...
You can simplify your code to, i guess your session array would look something like
key in your cart array will be product id so there will be no chance of duplicate product in array now in below code i have removed
foreach
loop instead i have used just an if checkif(isset($sessionVal[$aBasket['product_id']]))
whether product already exist in cart array by putting product id in place of key e.gif(isset($sessionVal['11']))
if exist then increment quantity by one, if not exist then insert product in cart array