0

I want to get the current product category ids by Knockout JS.

Please help.

4

1 Answer 1

2

You can get all category ids of current product with Knockout in your custom module using following way:

/app/code/Vendor/Module/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\Product" name="index.kojs" template="Vendor_Module::catids.phtml"/>
        </referenceContainer>
    </body>
</page>

/app/code/Vendor/Module/Block/Product.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{

    /**
     * @var array|\Magento\Checkout\Block\Checkout\LayoutProcessorInterface[]
     */
    protected $layoutProcessors;

    /**
     * @var \Magento\Catalog\Model\ProductCategoryList
     */
    protected $productCategoryList;

    /**
     * [__construct description]
     * @param \Magento\Framework\View\Element\Template\Context $context             [description]
     * @param \Magento\Framework\Registry                      $registry            [description]
     * @param \Magento\Catalog\Model\ProductCategoryList       $productCategoryList [description]
     * @param array                                            $layoutProcessors    [description]
     * @param array                                            $data                [description]
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Catalog\Model\ProductCategoryList $productCategoryList,
        array $layoutProcessors = [],
        array $data = []
    ) {
        $this->jsLayout = isset($data['jsLayout']) && is_array($data['jsLayout']) ? $data['jsLayout'] : [];
        $this->_registry = $registry;
        $this->layoutProcessors = $layoutProcessors;
        $this->productCategoryList = $productCategoryList;
        parent::__construct($context, $data);
    }

    public function getJsLayout()
    {
        foreach ($this->layoutProcessors as $processor) {
            $this->jsLayout = $processor->process($this->jsLayout);
        }
        return \Zend_Json::encode($this->jsLayout);
    }

    public function getCatIds()
    {
        $productId = $this->_registry->registry('current_product')->getId();
        $categoryIds = $this->productCategoryList->getCategoryIds($productId);
        return json_encode($categoryIds);
    }
}

/app/code/Vendor/Module/view/frontend/templates/catids.phtml

<?php
/**
 * Copyright © Maagento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<div id="kocat" data-bind="scope:'kocat'">
    <!-- ko template: getTemplate() --><!-- /ko -->
    <script type="text/x-magento-init">
        {
            "#kocat": {
                "Magento_Ui/js/core/app": {
                    "components": {
                        "kocat": {
                            "component": "Vendor_Module/js/view/kocat",
                            "defaultCollection":<?= $block->getCatIds(); ?>
                         }
                    }
                }
            }
        }
    </script>
</div>

/app/code/Vendor/Module/view/frontend/web/js/view/kocat.js

define([
    'jquery',
    'ko',
    'uiComponent',
    'mage/url',
    'mage/storage',
    'mage/validation'
], function ($,ko, Component, urlBuilder,storage) {
    'use strict';
    return Component.extend({
        /*Initialization*/
        initialize: function () {
           self = this;
           self._super();
           console.log(self.defaultCollection);
        },
    });
});

Check in console, you will get all category ids of current product on product page.

I hope it will helpful for you.

5

Your Answer

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

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