【发布时间】:2016-07-13 09:53:18
【问题描述】:
我正在使用 CakePHP 3.2 编写购物车应用程序。
我正在使用 cookie 将商品添加到购物车。
现在我想更新和删除购物车中的值。这样,如果用户点击具有不同 quantity 值的同一产品 add to cart,则现有记录将被删除,新记录将被添加到购物车。
这是我的addToCart() 方法。
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());
}
}
}
但这会导致错误
Notice (8): Array to string conversion [APP/Controller/OrdersController.php, line 148]
如何更新购物车中的数量值。
【问题讨论】:
-
第 148 行是什么?
-
举个例子:我已经有了product_id(1)和quantity(3)。现在您使用相同的 product_id 调用了 addToCart() 函数,现在您想要覆盖数量或(旧数量 + 当前数量)。告诉我
-
@claudios 我已经在代码中标记了第 148 行。
-
@MathsRkBala 我想覆盖现有数量。
-
@anujsharma9196 请使用我的代码并告诉我。谢谢:-)
标签: cakephp cookies cakephp-3.2