0

I am trying to retrive product id from item id.

i created first js function in sidebar.js:

define([
'jquery',
'Magento_Customer/js/model/authentication-popup',
'Magento_Customer/js/customer-data',
'Magento_Ui/js/modal/alert',
'Magento_Ui/js/modal/confirm',
'underscore',
'jquery/ui',
'mage/decorate',
'mage/collapsible',
'mage/cookies'
], function ($, authenticationPopup, customerData, alert, confirm, _) {
'use strict';

$.widget('mage.sidebar', {
    options: {
        isRecursive: true,
        minicart: {
            maxItemsVisible: 3
        }
    },
    scrollHeight: 0,
    shoppingCartUrl: window.checkout.shoppingCartUrl,

    /**
     * Create sidebar.
     * @private
     */
    _create: function () {
        this._initContent();
    },

    /**
     * Update sidebar block.
     */
    update: function () {
        $(this.options.targetElement).trigger('contentUpdated');
        this._calcHeight();
        this._isOverflowed();
    },

    /**
     * @private
     */
    _initContent: function () {
        var self = this,
            events = {};

        this.element.decorate('list', this.options.isRecursive);

        /**
         * @param {jQuery.Event} event
         */
        events['click ' + this.options.button.close] = function (event) {
            event.stopPropagation();
            $(self.options.targetElement).dropdownDialog('close');
        };
        events['click ' + this.options.button.checkout] = $.proxy(function () {
            var cart = customerData.get('cart'),
                customer = customerData.get('customer'),
                element = $(this.options.button.checkout);

            if (!customer().firstname && cart().isGuestCheckoutAllowed === false) {
                // set URL for redirect on successful login/registration. It's postprocessed on backend.
                $.cookie('login_redirect', this.options.url.checkout);

                if (this.options.url.isRedirectRequired) {
                    element.prop('disabled', true);
                    location.href = this.options.url.loginUrl;
                } else {
                    authenticationPopup.showModal();
                }

                return false;
            }
            element.prop('disabled', true);
            location.href = this.options.url.checkout;
        }, this);

        /**
         * @param {jQuery.Event} event
         */
        events['click ' + this.options.button.remove] =  function (event) {

            event.stopPropagation();

            confirm({

                content: self.options.confirmMessage,
                actions: {
                    /** @inheritdoc */
                    confirm: function () {

        self._removeItemCategory($(event.currentTarget));
                       self._removeItem($(event.currentTarget));                                                        
                       // location.reload();

                    },


                    /** @inheritdoc */
                    always: function (e) {
                        e.stopImmediatePropagation();
                    }
                }
            });
        };

        /**
         * @param {jQuery.Event} event
         */
        events['keyup ' + this.options.item.qty] = function (event) {
            self._showItemButton($(event.target));
        };

        /**
         * @param {jQuery.Event} event
         */
        events['change ' + this.options.item.qty] = function (event) {
            self._showItemButton($(event.target));
        };

        /**
         * @param {jQuery.Event} event
         */
        events['click ' + this.options.item.button] = function (event) {
            event.stopPropagation();
            self._updateItemQty($(event.currentTarget));
        };

        /**
         * @param {jQuery.Event} event
         */
        events['focusout ' + this.options.item.qty] = function (event) {
            self._validateQty($(event.currentTarget));
        };

        this._on(this.element, events);
        this._calcHeight();
        this._isOverflowed();
    },

    /**
     * Add 'overflowed' class to minicart items wrapper element
     *
     * @private
     */
    _isOverflowed: function () {
        var list = $(this.options.minicart.list),
            cssOverflowClass = 'overflowed';

        if (this.scrollHeight > list.innerHeight()) {
            list.parent().addClass(cssOverflowClass);
        } else {
            list.parent().removeClass(cssOverflowClass);
        }
    },

    /**
     * @param {HTMLElement} elem
     * @private
     */
    _showItemButton: function (elem) {
        var itemId = elem.data('cart-item'),
            itemQty = elem.data('item-qty');

        if (this._isValidQty(itemQty, elem.val())) {
            $('#update-cart-item-' + itemId).show('fade', 300);
        } else if (elem.val() == 0) { //eslint-disable-line eqeqeq
            this._hideItemButton(elem);
        } else {
            this._hideItemButton(elem);
        }
    },

    /**
     * @param {*} origin - origin qty. 'data-item-qty' attribute.
     * @param {*} changed - new qty.
     * @returns {Boolean}
     * @private
     */
    _isValidQty: function (origin, changed) {
        return origin != changed && //eslint-disable-line eqeqeq
            changed.length > 0 &&
            changed - 0 == changed && //eslint-disable-line eqeqeq
            changed - 0 > 0;
    },

    /**
     * @param {Object} elem
     * @private
     */
    _validateQty: function (elem) {
        var itemQty = elem.data('item-qty');

        if (!this._isValidQty(itemQty, elem.val())) {
            elem.val(itemQty);
        }
    },

    /**
     * @param {HTMLElement} elem
     * @private
     */
    _hideItemButton: function (elem) {
        var itemId = elem.data('cart-item');

        $('#update-cart-item-' + itemId).hide('fade', 300);
    },

    /**
     * @param {HTMLElement} elem
     * @private
     */
    _updateItemQty: function (elem) {
        var itemId = elem.data('cart-item');

        this._ajax(this.options.url.update, {
            'item_id': itemId,
            'item_qty': $('#cart-item-' + itemId + '-qty').val()
        }, elem, this._updateItemQtyAfter);
    },

    /**
     * Update content after update qty
     *
     * @param {HTMLElement} elem
     */
    _updateItemQtyAfter: function (elem) {
        var productData = this._getProductById(Number(elem.data('cart-item')));

        if (!_.isUndefined(productData)) {
            $(document).trigger('ajax:updateCartItemQty');

            if (window.location.href === this.shoppingCartUrl) {
                window.location.reload(false);
            }
        }
        this._hideItemButton(elem);
    },

    /**
     * @param {HTMLElement} elem
     * @private
     */
    _removeItem: function (elem) {
        console.log(this.options.url.remove);
        var itemId = elem.data('cart-item');

        this._ajax(this.options.url.remove, {
            'item_id': itemId
        }, elem, this._removeItemAfter);
    },

    /**
     * @param {HTMLElement} elem
     * @private
     */
    _removeItemCategory: function (elem) {

       // var itemId = elem.data('cart-item');
        var skuId = elem.data('cart-item');

        var customUrl = window.customUrl;
        console.log(customUrl); 

        this._ajaxnew(customUrl, {
            'sku': skuId
        }, elem);

        //$('.subCategoryCountInCart').css("display", "none");
    },

    /**
     * Update content after item remove
     *
     * @param {Object} elem
     * @private
     */
    _removeItemAfter: function (elem) {
        var productData = this._getProductById(Number(elem.data('cart-item')));

        if (!_.isUndefined(productData)) {
            $(document).trigger('ajax:removeFromCart', {
                productIds: [productData['product_id']]
            });
        }
    },

    /**
     * Retrieves product data by Id.
     *
     * @param {Number} productId - product Id
     * @returns {Object|undefined}
     * @private
     */
    _getProductById: function (productId) {
        return _.find(customerData.get('cart')().items, function (item) {
            return productId === Number(item['item_id']);
        });
    },

    /**
     * @param {String} url - ajax url
     * @param {Object} data - post data for ajax call
     * @param {Object} elem - element that initiated the event
     * @param {Function} callback - callback method to execute after AJAX success
     */
    _ajax: function (url, data, elem, callback) {
        $.extend(data, {
            'form_key': $.mage.cookies.get('form_key')
        });

        $.ajax({
            url: url,
            data: data,
            type: 'post',
            dataType: 'json',
            context: this,
            //showLoader: true,

            /** @inheritdoc */
            beforeSend: function () {
                elem.attr('disabled', 'disabled');
            },

            /** @inheritdoc */
            complete: function () {
                elem.attr('disabled', null);
            }

        })

            .done(function (response) {
                var msg;

                if (response.success) {
                    callback.call(this, elem, response);
                } else {
                    msg = response['error_message'];

                    if (msg) {
                        alert({
                            content: msg
                        });
                    }
                }
            })
            .fail(function (error) {
                console.log(JSON.stringify(error));
            });
    },


    _ajaxnew: function (url, data, elem) {
        console.log(elem);
                   //var itemQty = elem.data('item-qty');
                    //console.log(itemQty);
                    //console.log($('#cart-item-' + elem + '-qty').val())
        $.extend(data, {
            'form_key': $.mage.cookies.get('form_key')
        });

        $.ajax({
            url: url,
            data: data,
            type: 'post',
            dataType: 'json',
            context: this,
           // showLoader: true,

            /** @inheritdoc */
            beforeSend: function () {
                elem.attr('disabled', 'disabled');
            },

            /** @inheritdoc */
            complete: function () {
                elem.attr('disabled', null);
            }

        })

            .done(function (response) {

                if(response.cat_id){

                   var bagcount =  parseInt($("#"+ response.cat_id + " strong").text());
                   var updatedBagcount = bagcount - response.qty;
                   if(updatedBagcount <= 0){
                       $("span#"+ response.cat_id).hide();
                   } else {
                       $("#"+ response.cat_id + " strong").html(updatedBagcount);
                   }
                }
            })
            .fail(function (error) {
                console.log(JSON.stringify(error));
            });
    },


    /**
     * Calculate height of minicart list
     *
     * @private
     */
    _calcHeight: function () {
        var self = this,
            height = 0,
            counter = this.options.minicart.maxItemsVisible,
            target = $(this.options.minicart.list),
            outerHeight;

        self.scrollHeight = 0;
        target.children().each(function () {

            if ($(this).find('.options').length > 0) {
                $(this).collapsible();
            }
            outerHeight = $(this).outerHeight();

            if (counter-- > 0) {
                height += outerHeight;
            }
            self.scrollHeight += outerHeight;
        });

        target.parent().height(height);
    }


});

return $.mage.sidebar;
  });

after thai in controller:

public function execute()
{
    $itemid = (int)$this->getRequest()->getParam('item_id');

    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $productData = $_objectManager->get('Magento\Quote\Model\Quote\Item')->load($itemid);
    $productId = $productData['product_id'];
    $qty = $productData['qty'];
    print_r($productId); 
    $product = $_objectManager->get('Magento\Catalog\Model\Product')->load($productId);
        $categoriesId = $product->getCategoryIds();
        print_r($categoriesId); 
        foreach($categoriesId as $categoryId){
           $cat = $_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);


        } 

Through this call, some time i am getting product id sometime not. can anyone please help me how to get product id through item id , everytime, and what i am doing wrong?

7
  • Does item_id sending all the time to your custom controller? Commented Nov 29, 2019 at 9:08
  • yes.. item id i am getting all the time.
    – sam
    Commented Nov 29, 2019 at 9:10
  • You can send item_sku instead of item id to controller and load product by sku. Commented Nov 29, 2019 at 9:13
  • i did, but still same thing happen
    – sam
    Commented Nov 29, 2019 at 11:42
  • Can you pls share your whole sidebar.js code to find another solution? Commented Nov 29, 2019 at 11:49

2 Answers 2

0

You can get SKU from item, then can load produdct by SKU and then can get the product details

Refer: How to load product by SKU in magento 2

Item ID is often different from product ID

4
  • i tried with this and getting the error like" Uncaught TypeError: Argument 1 passed to Magento\Catalog\Model\ProductRepository::getProductFromLocalCache() must be of the type string, null given,"
    – sam
    Commented Nov 29, 2019 at 11:43
  • it seems to be some issue with cache. so, please clear cache once and if possible, run setup:di:compile too
    – Manish Joy
    Commented Dec 2, 2019 at 7:25
  • yes, i tried with sku, but again same issue, some time , we get the sku value, some time not
    – sam
    Commented Dec 2, 2019 at 10:40
  • well, that' seems impossible, becuase a product/item will definetly have an SKU
    – Manish Joy
    Commented Dec 2, 2019 at 10:41
0

Try with below code to get category object from product sku

protected $_cart;
protected $_productRepository;
protected $_categoryRepository;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Checkout\Model\Cart $cart
    \Magento\Catalog\Model\ProductRepository $productRepository,
    \Magento\Catalog\Model\CategoryRepository $categoryRepository
) {
    $this->_cart = $cart;
    $this->_productRepository = $productRepository;
    $this->_categoryRepository = $categoryRepository;
    parent::__construct($context);
}

public function execute()
{
    $itemId = (int)$this->getRequest()->getParam('item_id');
    $quoteItem = $this->cart->getQuote()->getItemById($itemId);
    $product = $this->_productRepository->get($quoteItem->getProductSku());
    $categoriesId = $product->getCategoryIds();
    foreach($categoriesId as $categoryId){
        $cat = $this->_categoryRepository->get($categoryId);
    } 
}

Note: Do not use objectmanager directly, It is not a good practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.