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

109 views Asked by At

I know that there is a way to add products to cart by calling cart controller through ajax request. Like:-

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

But if I want to do the same thing from a contoller directly without rendering/loading any tpl or js file.

Is there any way to perform the same?

1

There are 1 answers

0
Wolfack On BEST ANSWER

I finally found a way to perform the same.

To add products to cart from a controller directly you have to use the following code.

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

You can also add a cart rule to the cart directly just by using the id of that cart rule.

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