Reputation: 442
I am implementing cart module in Yii, I am able to save everything in session array but each time same product is added the quantity get increment but again got set to 1.
here is my function code snippet
public function actionAddToCart($id) {
$found = 0;
$cart = array();
$cart_item = $this->loadModel($id)->name;
$cart_price = $this->loadModel($id)->price;
$newItem = Yii::app()->session['cart'];
foreach ($newItem as $item) {
if($id == $item['id']) {
echo "quantity" . $item['quantity'];
$item['quantity'] += 1;
$found = 1;
$newItem[$id] = array('name'=>$cart_item,'price'=>$cart_price, 'quantity'=>$item['quantity'], 'id'=>$id ) ;
echo "Element Found=" . $found . 'Now quantity is '.$item['quantity'];
}
}
if($found != 1) {
$newItem[$id] = array('name'=>$cart_item,'price'=>$cart_price, 'quantity'=>1, 'id'=>$id ) ;
Yii::app()->session['cart'] = $newItem ;
echo "New added" ;
}
//array_push($cart, Yii::app()->session['cart'][$id] ) ; //array('name'=>$cart_item,'price'=>$cart_price)) ;
echo json_encode(array("items"=>$newItem));
Yii::app()->end();
}
Seeking help thanks in advance.
Upvotes: 0
Views: 460
Reputation: 274
You are not accessing the global variable $found
.
Here is the modified code:
public function actionAddToCart($id) {
$found = 0;
$cart = array();
$cart_item = $this->loadModel($id)->name;
$cart_price = $this->loadModel($id)->price;
$newItem = Yii::app()->session['cart'];
foreach ($newItem as $item) {
if($id == $item['id']) {
echo "quantity" . $item['quantity'];
$item['quantity'] += 1;
$GLOBALS['found'] = 1;
$newItem[$id] = array('name'=>$cart_item,'price'=>$cart_price, 'quantity'=>$item['quantity'], 'id'=>$id ) ;
echo "Element Found=" . $found . 'Now quantity is '.$item['quantity'];
}
}
if($found == 0) {
$newItem[$id] = array('name'=>$cart_item,'price'=>$cart_price, 'quantity'=>1, 'id'=>$id ) ;
Yii::app()->session['cart'] = $newItem ;
echo "New added" ;
}
//array_push($cart, Yii::app()->session['cart'][$id] ) ; //array('name'=>$cart_item,'price'=>$cart_price)) ;
echo json_encode(array("items"=>$newItem));
Yii::app()->end();
}
Upvotes: 0
Reputation: 2488
You are not updating the SESSION CART where there is found ,
Also Your code it just a bit mess( in the sense of optamization).
try this.
public function actionAddToCart($id) {
$newItem = Yii::app()->session['cart'];
if(isset($newItem[$id])){
$newItem[$id]['quantity']++;
echo "Element Found= 1 Now quantity is ".$newItem[$id]['quantity'];
}
else{
$cartItem= $this->loadModel($id)
$newItem[$id] = array('name'=>$cartItem->name,'price'=>$cartItem->price, 'quantity'=>1, 'id'=>$id ) ;
}
Yii::app()->session['cart'] = $newItem ;
//array_push($cart, Yii::app()->session['cart'][$id] ) ;
//array('name'=>$cart_item,'price'=>$cart_price)) ;
echo json_encode(array("items"=>$newItem));
Yii::app()->end();
}
Upvotes: 1