问题
I'm using CakePHP 3.2 for writing a shopping cart application.
I'm using cookie to add items to the cart.
Now I want to update and delete value from cart. so that if user clicks on the same product add to cart
with a different quantity
value the existing record will be deleted and new will be added to cart.
This is my addToCart()
method.
public function addToCart()
{
$this->loadModel('Products');
if ($this->request->is('post')) {
$p_id = $this->request->data('product_id');
$p_quantity = $this->request->data('qnty');
$product = $this->Products->get($p_id);
$product->quantity = $p_quantity;
if (!$product) {
throw new NotFoundException(__('Invalid Product'));
}
$cart = $this->Cookie->read('Cart') ? $this->Cookie->read('Cart') : [];
$itemInCart = false;
$itemUpdated = false;
if ($cart != null) {
foreach($cart as $cart_item):
if ($cart_item['id'] == $p_id) {
if ($cart_item['quantity'] != $p_quantity) {
$this->Cookie->delete('Cart.'.$cart_item); // line 148
$cart[] = $product;
$this->Cookie->write('Cart', $cart);
$itemsCount = count($this->Cookie->read('Cart'));
$this->Flash->success('Product updated in cart');
return $this->redirect($this->referer);
}
$itemInCart = true;
}
endforeach;
}
if (!$itemInCart) {
$cart[] = $product;
$this->Cookie->write('Cart', $cart);
$itemsCount = count($this->Cookie->read('Cart'));
if ($itemUpdated) {
$this->Flash->success(__('Product updated in cart'));
} else {
$this->Flash->success(__('Product added to cart'));
}
return $this->redirect($this->referer());
} else {
$this->Flash->success(__('Product is already in cart'));
return $this->redirect($this->referer());
}
}
}
But this is giving error as
Notice (8): Array to string conversion [APP/Controller/OrdersController.php, line 148]
How could I update the quantity value in the cart.
回答1:
Try the following:
public function addToCart()
{
$this->loadModel('Products');
if ($this->request->is('post')) {
$p_id = $this->request->data('product_id');
$p_quantity = $this->request->data('qnty');
$product = $this->Products->get($p_id);
if (!$product) {
throw new NotFoundException(__('Invalid Product'));
}
$product->quantity = $p_quantity;
$cart = $this->Cookie->read('Cart') ? $this->Cookie->read('Cart') : [];
$itemInCart = false;
$new_cart = [];
if ($cart != null) {
foreach($cart as $cart_item):
if ($cart_item['id'] == $p_id) {
if($p_quantity == 0){
//Removed the item from cart and set itemInCart to true
$itemInCart = true;
}else{
//update the quantity of item
$new_cart[] = $product;
$itemInCart = true;
}
}else{
$new_cart[] = $cart_item;
}
endforeach;
}
if ($itemInCart) {
$this->Cookie->write('Cart', $new_cart);
$this->Flash->success(__('Product updated in cart'));
} else {
$cart[] = $product;
$this->Cookie->write('Cart', $cart);
$this->Flash->success(__('Product added to cart'));
}
return $this->redirect($this->referer);
}
}
来源:https://stackoverflow.com/questions/38348282/cakephp-3-delete-and-update-array-from-cookie