Search code examples
javascriptphpjqueryopencartopencart-3

How to add product in to cart by sku or by model in Opencart 3.0


I want to add products into the cart by SKU or MODEL instead of Product id. here is the code of how it adds in the category.twig file

<button type="button" onclick="cart.add('{{ product.product_id }}', '{{ product.minimum }}');"><i class="fa fa-shopping-cart"></i> <span class="hidden-xs hidden-sm hidden-md">{{ button_cart }}</span></button>

And here is js

// Cart add remove functions
var cart = {
    'add': function(product_id, quantity) {
        $.ajax({
            url: 'index.php?route=checkout/cart/add',
            type: 'post',
            data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
            dataType: 'json',
            beforeSend: function() {
                $('#cart > button').button('loading');
            },
            complete: function() {
                $('#cart > button').button('reset');
            },
            success: function(json) {
                $('.alert-dismissible, .text-danger').remove();

                if (json['redirect']) {
                    location = json['redirect'];
                }

                if (json['success']) {
                    $('#content').parent().before('<div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');

                    // Need to set timeout otherwise it wont update the total
                    setTimeout(function () {
                        $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
                    }, 100);

                    $('html, body').animate({ scrollTop: 0 }, 'slow');

                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    },
}

in above code opencart uses product_id to add product into cart but instead i want to add it by sku or model


Solution

  • In common.js new method derived from add (basically product_id changed to sku and addBySku is called)

        'addBySku': function(sku, quantity) {
            $.ajax({
                url: 'index.php?route=checkout/cart/addBySku',
                type: 'post',
                data: 'sku=' + sku + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
                //nothing else changed from 'add' method
    

    In catalog/controller/checkout/cart.php derived from add method. Just get product_id by sku, put it into post and keep everything else unchanged.

        public function addBySku() {
            $this->load->language('checkout/cart');
            $this->load->model('catalog/product');
    
            $json = array();
    
            if (isset($this->request->post['sku'])) {
                $product_id = (int)$this->model_catalog_product->productIDBySku($this->request->post['sku']);   
            } else {
                $product_id = 0;
            }
            $this->request->post['product_id'] = $product_id;
    
    
            //nothing else changed from 'add' method
    
    
    

    In catalog/model/catalog/product.php. Add this method which retrieves sku by product_id

        public function productIDBySku($sku) {
            $query = $this->db->query("select product_id from " . DB_PREFIX . "product where sku = '" . $this->db->escape($sku) . "'");
            return $query->row['product_id'];
        }
    

    Hope that helps. I didn't test it though. Don't forget to call correct method and pass sku

    <!--<button type="button" onclick="cart.add('{{ product.product_id }}',-->
    <button type="button" onclick="cart.addBySku('{{ product.sku }}',