Str*_*dis 5 php cart prestashop
在Prestashop中,我创建了一个自定义表单,其中显示了包含所有产品的列表,用户可以填写相应的数量.通过提交表单,我清除购物车并用新值填充它,最后重定向到结帐页面.
一切都很好,但只有当购物车已经存在时.如果是空车(cart_id == null),我无法添加产品.我尝试了几种方法来创建$ cart但我没有设法这样做.
我没有任何例外,代码执行没有错误,只是在结束时,在结帐页面,购物车仍然是空的; 我再说一遍,只有当车已经空了.如果购物车中有产品,那么这个过程就是完美的!
我将不胜感激.
这是我的小型控制器,它从表单中获取产品和数量,并将它们添加到购物车中:
include('../../config/config.inc.php');
include('../../header.php');
// Filling the array of products
$products = array();
foreach ($_POST as $key => $value)
if (substr($key, 0, 9) === 'quantity_')
$products[substr($key, 9)] = $value;
// First of all, we remove all products
$prods = $cart->getProducts();
foreach ($prods as $prod)
$cart->deleteProduct($prod['id_product']);
// Adding the new products
foreach ($products as $product_id => $quantity)
if ($quantity > 0)
$cart->updateQty($quantity, $product_id);
// Redirecting to the checkout page.
header("Location: " . $_POST['redirect']);
exit();`
Run Code Online (Sandbox Code Playgroud)
先感谢您!
小智 9
我有同样的问题,Prestashop在以多种不同方式调用CartCore时没有正确创建新购物车 - 上下文或直接调用都没有成功.
在这里找到了来自其他人的宝石:
// get cart id if exists
if ($this->context->cookie->id_cart)
{
$cart = new Cart($this->context->cookie->id_cart);
}
// create new cart if needed
if (!isset($cart) OR !$cart->id)
{
$cart = new Cart();
$cart->id_customer = (int)($this->context->cookie->id_customer);
$cart->id_address_delivery = (int) (Address::getFirstCustomerAddressId($cart->id_customer));
$cart->id_address_invoice = $cart->id_address_delivery;
$cart->id_lang = (int)($this->context->cookie->id_lang);
$cart->id_currency = (int)($this->context->cookie->id_currency);
$cart->id_carrier = 1;
$cart->recyclable = 0;
$cart->gift = 0;
$cart->add();
$this->context->cookie->id_cart = (int)($cart->id);
$cart->update();
}
Run Code Online (Sandbox Code Playgroud)
这对我来说很有用.如您所见,它比仅仅要求上下文检索或创建新购物车更深入.心连心.
当您不在课堂上时,您可能需要包含此行
$context = Context::getContext();
Run Code Online (Sandbox Code Playgroud)
然后添加一个定义购物车属性的购物车变量(在您的情况下分配一个 id )
$cart = $context->cart; // gets the cart id or creates a new one
Run Code Online (Sandbox Code Playgroud)
现在应该可以正常工作
BR(如果对您有帮助,请不要忘记接受答案:))