Skip to main content

Magento 2: Category list for custom magento system configuration section ( Backend )

In system.xml file field for multi select of category is like:

NOTE: Use Select for Single item and multiselect for multiple in - <field id="bannerlist" translate="label" type="multiselect"

<group id="bannerblock_setting" translate="label" type="text" delault="1" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Setting</label>
    <field id="bannerlist" translate="label" type="multiselect" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
        <label>Select Category</label>
        <!-- <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>-->
        <source_model>Ipragmatech\Bannerblock\Model\Config\Source\Categorylist</source_model>
    </field>
</group>
 
 
////////////////////////////////////////////////////////////////////////////
Create a file Categorylist.php in Companyname\Modulename\Model\Config\Source 


namespace Companyname\Modulename\Model\Config\Source;

use Magento\Framework\Option\ArrayInterface;

class Categorylist implements ArrayInterface
{
    protected $_categoryHelper;

    public function __construct(\Magento\Catalog\Helper\Category $catalogCategory)
    {
        $this->_categoryHelper = $catalogCategory;
    }

    /*
     * Return categories helper
     */

    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
    }

    /*  
     * Option getter
     * @return array
     */
    public function toOptionArray()
    {


        $arr = $this->toArray();
        $ret = [];

        foreach ($arr as $key => $value)
        {

            $ret[] = [
                'value' => $key,
                'label' => $value
            ];
        }

        return $ret;
    }

    /*
     * Get options in "key-value" format
     * @return array
     */
    public function toArray()
    {

        $categories = $this->getStoreCategories(true,false,true);

        $catagoryList = array();
        foreach ($categories as $category){

            $catagoryList[$category->getEntityId()] = __($category->getName());
        }

        return $catagoryList;
    }

}
 
 
- It will show only parent categories
 /////////////////////////////////////////////////////////////////////////////
For all categories and subcategories

<?php

namespace VendorName\ModuleName\Model\Config\Source;

use Magento\Framework\Option\ArrayInterface;

class Categorylist implements ArrayInterface
{
    protected $_categoryFactory;
    protected $_categoryCollectionFactory;

    public function __construct(
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
    )
    {
        $this->_categoryFactory = $categoryFactory;
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
    }

    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
    {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');

        // select only active categories
        if ($isActive) {
            $collection->addIsActiveFilter();
        }

        // select categories of certain level
        if ($level) {
            $collection->addLevelFilter($level);
        }

        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }

        // select certain number of categories
        if ($pageSize) {
            $collection->setPageSize($pageSize);
        }

        return $collection;
    }

    public function toOptionArray()
    {
        $arr = $this->_toArray();
        $ret = [];

        foreach ($arr as $key => $value)
        {
            $ret[] = [
                'value' => $key,
                'label' => $value
            ];
        }

        return $ret;
    }

    private function _toArray()
    {
        $categories = $this->getCategoryCollection(true, false, false, false);

        $catagoryList = array();
        foreach ($categories as $category)
        {
            $catagoryList[$category->getEntityId()] = __($this->_getParentName($category->getPath()) . $category->getName());
        }

        return $catagoryList;
    }

    private function _getParentName($path = '')
    {
        $parentName = '';
        $rootCats = array(1,2);

        $catTree = explode("/", $path);
        // Deleting category itself
        array_pop($catTree);

        if($catTree && (count($catTree) > count($rootCats)))
        {
            foreach ($catTree as $catId)
            {
                if(!in_array($catId, $rootCats))
                {
                    $category = $this->_categoryFactory->create()->load($catId);
                    $categoryName = $category->getName();
                    $parentName .= $categoryName . ' -> ';
                }
            }
        }

        return $parentName;
    }
}
 
 
- It will show all subcategories also
 
 

Comments

Popular posts from this blog

Magento 2: Get Products by category ID

<?php $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        // $appState = $objectManager->get('\Magento\Framework\App\State'); // $appState->setAreaCode('frontend'); $categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory'); $categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category'); $categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository'); $store = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore(); $categoryId = 47; // YOUR CATEGORY ID $category = $categoryFactory->create()->load($categoryId); $categoryProducts = $category->getProductCollection()                              ->addAttributeToSelect('*');       ...