PrestaCraft on Facebook

Please like our page on Facebook to get notifications about new tutorials :)


PrestaCraft

PrestaCraft on Facebook

Please like our page on Facebook to get notifications about new tutorials :)


PrestaCraft

Recently I’ve struggled with creating customer cart programatically. I’ve found that PrestaShop has already such code in CartController.php. So whenever you need to create cart in your module (in front controller, hook etc.) you can use this little snippet:

if (!$this->context->cart->id) {
    if (Context::getContext()->cookie->id_guest) {
        $guest = new Guest(Context::getContext()->cookie->id_guest);
        $this->context->cart->mobile_theme = $guest->mobile_theme;
    }
    $this->context->cart->add();
    if ($this->context->cart->id) {
        $this->context->cookie->id_cart = (int)$this->context->cart->id;
    }
}

The cart is going to be created if it doesn’t exist. If you’d like to add some product(s), you can to it like this:

if ((int)$this->context->cart->id > 0) {
    $cart = new Cart((int)$this->context->cart->id);
    $cart->updateQty($quantity, $id_product, $id_product_attribute); // Insert here quantity, product ID and optionally its ID product attribute (or null). You can duplicate this line for another product.
    $cart->update();
}

And that’s all. Thanks!

Leave a comment

Your email address will not be published.

Be the first to post a comment!

Leave a comment

Your email address will not be published.