0
votes

I have a php code with custom module. How can I add the product to the cart from code. I have id_number (product id) and id_customer (customer id)

<?php

$product id = 1167;

// how to proceed to add information to cart

need to update this product(id_number) to my cart (loggedin user)

1

1 Answers

0
votes

I use this snippet in my module to add product to the cart, but you can use it in an controller overrided :

public function add2cart(){
        $id = 1167;
        $qty = 1;

        if($id!=''){


            $this->createCart();
            $this->context->cart->updateQty($qte, $id, null, '');
            $this->context->cart->save();
            $this->context->cookie->__set('id_cart', $this->context->cart->id);         


            echo 'Product added to cart!';
            exit;


        }

    }



    private function createCart()
    {
        if (is_null($this->context->cart)) {

            $this->context->cart = 
            new Cart($this->context->cookie->id_cart);
        }

        if (is_null($this->context->cart->id_lang)) {
            $this->context->cart->id_lang = $this->context->cookie->id_lang;
        }

        if (is_null($this->context->cart->id_currency)) {
            $this->context->cart->id_currency = $this->context->cookie->id_currency;
        }

        if (is_null($this->context->cart->id_customer)) {
            $this->context->cart->id_customer = $this->context->cookie->id_customer;
        }

        if (is_null($this->context->cart->id_guest)) {

            if (empty($this->context->cookie->id_guest)){
                $this->context->cookie->__set(
                'id_guest', 
                Guest::getFromCustomer($this->context->cookie->id_customer)
                );
            }
            $this->context->cart->id_guest = $this->context->cookie->id_guest;
        }

        if (is_null($this->context->cart->id)) {

            $this->context->cart->add();

            $this->context->cookie->__set('id_cart', $this->context->cart->id);
        }
    }

And in my initContent function, i call the function add2cart() :

$this->add2cart();