有没有办法从控制器添加产品到购物车?

时间:2015-06-25 12:42:02

标签: php ajax prestashop prestashop-1.6 prestashop-1.5

我知道有一种方法可以通过ajax请求调用购物车控制器来将产品添加到购物车。喜欢: -

 $.ajax({
            type: "POST",
            url: baseUri + '?rand=' + new Date().getTime(),
            data: 'controller=cart&add=1&ajax=true&qty=' + $('#quantity_wanted').val() + '&id_product=' + id_product + '&token=' + static_token + ( (parseInt(idCombination) && idCombination != null) ? '&ipa=' + parseInt(idCombination): ''),
            beforeSend: function() {
            },
            success: function() {
            }
    });

但是如果我想直接从控制器做同样的事情而不渲染/加载任何tpl或js文件。

有没有办法执行相同的操作?

1 个答案:

答案 0 :(得分:0)

我终于找到了一种方法来执行相同的操作。

要直接从控制器向购物车添加产品,您必须使用以下代码。

    $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);
    foreach ($products_to_add as $pro)
    {
        $updateQuantity = $cart->updateQty((int)$pro['quantity'], (int)$pro['id_product'], (int)$pro['id_product_attribute'], (int)$pro['id_customization'], 'up', (int)$pro['id_address_delivery'], null, false);          
        $cart->update();
    }

您也可以直接使用该购物车规则的ID将购物车规则添加到购物车。

$cart->addCartRule((int)$data['discount_code']);
$cart->update();