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

Is there any way to add products to cart from a controller?

我知道有一种方法可以通过 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() {
            }
    });

但是如果我想直接从控制器做同样的事情而不需要 rendering/loading 任何 tpl 或 js 文件。

有什么方法可以做到吗?

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

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

    $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();