Issue
Friends, I appreciate if anyone can analyze.
I add items to the shopping cart according to the code below.
public function add()
{
$order = $this->Orders->newEntity();
if ($this->request->is('post')) {
$order = $this->Orders->patchEntity($order, $this->request->getData());
$order->product = $this->Orders->Products->get($order->product_id, ['contain' => ['Users']]);
$session = $this->request->getSession();
$cart = $session->read('cart');
$cart[] = $order;
if (isset($cart[$order->product_id])) {
//product is already in the cart
} else {
$cart[$order->product_id] = $order;
}
$product = $this->Orders->Products->find('list', ['limit' => 200]);
$users = $this->Products->Users->find('list', ['limit' => 200]);
$this->set(compact('order', 'products', 'users'));
}
}
I can add products to the normal cart, but I can't prevent the same product from being added multiple times. It needs to be only once.
Thanks for any comment!
Solution
Instead of this
if (isset($cart[$order->product_id])) {
//product is already in the cart
} else {
$cart[$order->product_id] = $order;
}
It should be something like this (as I don't have your full code)
// counter is to check if the product_id already exists
$counter = 0;
foreach($cart as $cartOne){
if($cartOne['product_id'] == $order->product_id){
$cartOne['quantity'] += 1;
$counter++;
break;
}
}
if($counter == 0){
$cart[$order->product_id] = $order;
}
$counter = 0;
Full Code Here:
public function add(){
$order = $this->Orders->newEntity();
if ($this->request->is('post')) {
$order = $this->Orders->patchEntity($order, $this->request->getData());
$order->product = $this->Orders->Products->get($order->product_id, ['contain' => ['Users']]);
$session = $this->request->getSession();
$cart = $session->read('cart');
$cart[] = $order;
// counter is to check if the product_id already exists
$counter = 0;
foreach($cart as $cartOne){
if($cartOne['product_id'] == $order->product_id){
$cartOne['quantity'] += 1;
$counter++;
break;
}
}
if($counter == 0){
$cart[$order->product_id] = $order;
}
$counter = 0;
$product = $this->Orders->Products->find('list', ['limit' => 200]);
$users = $this->Products->Users->find('list', ['limit' => 200]);
$this->set(compact('order', 'products', 'users'));
}
}
Answered By - Chilarai
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.