In this blog, we are going to learn how we can create a class grid in the form of an interface component with the value of the “children_count” column in the admin section.

You can check us out Previous blog where we have mentioned what error we may encounter when applying lapset_lask class collection column.
In the previous blog, we created a category grid without the children_count column.

In this blog, we will also introduce lapset_lask category in the grid.

To do this, you need to complete the following steps:

1. Obtain all categories using the following code:

$collection = $this->categoryFactory->create()
            ->getCollection()
            ->addAttributeToSelect('*');

Here the query is as follows:

SELECT `e`.* FROM `catalog_category_entity` AS `e`

If you run this query on the database, the result is as follows:

2. Now reset the columns in the collection and set the desired columns. Here I have reset all the columns and set entity_id and children_count to values childrenCount columns.

$collection->getSelect()
            ->reset(Zend_Db_Select::COLUMNS)
            ->columns(['entity_id', 'e.children_count as childrenCount']);

Now the query is as follows:

SELECT `e`.`entity_id`, `e`.`children_count` AS `childrenCount` FROM `catalog_category_entity` AS `e`

If you run this query on the database, the result is as follows:

SQLResult4

3. Because I need to display the names of the categories in the grid, I have added the following statement to the collection of the survey.

$collection->addAttributeToSelect('*')
            ->addFieldToFilter('name', ["neq"=>null])
            ->addFieldToFilter('is_active', 1);

Now the query is as follows:

SELECT `e`.`entity_id`, `e`.`children_count` AS `childrenCount`, IF(at_name.value_id > 0, at_name.value, at_name_default.value) AS `name`, IF(at_is_active.value_id > 0, at_is_active.value, at_is_active_default.value) AS `is_active` FROM `catalog_category_entity` AS `e` LEFT JOIN `catalog_category_entity_varchar` AS `at_name_default` ON (`at_name_default`.`entity_id` = `e`.`entity_id`) AND (`at_name_default`.`attribute_id` = '45') AND `at_name_default`.`store_id` = 0 LEFT JOIN `catalog_category_entity_varchar` AS `at_name` ON (`at_name`.`entity_id` = `e`.`entity_id`) AND (`at_name`.`attribute_id` = '45') AND (`at_name`.`store_id` = 1) LEFT JOIN `catalog_category_entity_int` AS `at_is_active_default` ON (`at_is_active_default`.`entity_id` = `e`.`entity_id`) AND (`at_is_active_default`.`attribute_id` = '46') AND `at_is_active_default`.`store_id` = 0 LEFT JOIN `catalog_category_entity_int` AS `at_is_active` ON (`at_is_active`.`entity_id` = `e`.`entity_id`) AND (`at_is_active`.`attribute_id` = '46') AND (`at_is_active`.`store_id` = 1) WHERE (IF(at_name.value_id > 0, at_name.value, at_name_default.value) != '') AND (IF(at_is_active.value_id > 0, at_is_active.value, at_is_active_default.value) = '1')

If you run this query on the database, the result is as follows:

SQLResult5

4. Now check the entire code in the CategoryGrid.php file inside the application / code / vendor / CustomModule / Block / Adminhtml / rule / edit / tab / directory.

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Vendor_CustomModule
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace VendorCustomModuleBlockAdminhtmlRuleEditTab;

use MagentoCustomerControllerRegistryConstants;

/**
 * class for the category grid tab in the rule form.
 */
class CategoryGrid extends MagentoBackendBlockWidgetGridExtended
{
    /**
     * @var MagentoCatalogModelCategoryFactory
     */
    protected $categoryFactory;

    /**
     * @var VendorCustomModuleModelResourceModelRuleCategoryCollectionFactory
     */
    protected $ruleCategoryCollection;

    /**
     * Construct
     *
     * @param MagentoBackendBlockTemplateContext $context
     * @param MagentoBackendHelperData $backendHelper
     * @param MagentoCatalogModelCategoryFactory $categoryFactory
     * @param VendorCustomModuleModelResourceModelRuleCategoryCollectionFactory $ruleCategoryCollection
     * @param array $data
     */
    public function __construct(
        MagentoBackendBlockTemplateContext $context,
        MagentoBackendHelperData $backendHelper,
        MagentoCatalogModelCategoryFactory $categoryFactory,
        VendorCustomModuleModelResourceModelRuleCategoryCollectionFactory $ruleCategoryCollection,
        array $data = []
    ) {
        $this->categoryFactory = $categoryFactory;
        $this->ruleCategoryCollection = $ruleCategoryCollection;
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * @inheritdoc
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('loyalty_rule_categorygrid');
        $this->setDefaultSort('entity_id', 'asc');
        $this->setUseAjax(true);
    }

    /**
     * @param Column $column
     * @return $this
     */
    protected function _addColumnFilterToCollection($column)
    {
        // Set custom filter for in category flag
        if ($column->getId() == 'in_categories') {
            $categoryIds = $this->_getSelectedCategories();
            if (empty($categoryIds)) {
                $categoryIds = 0;
            }
            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter('entity_id', ['in' => $categoryIds]);
            } elseif (!empty($categoryIds)) {
                $this->getCollection()->addFieldToFilter('entity_id', ['nin' => $categoryIds]);
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }
        return $this;
    }

    /**
     * Apply various selection filters to prepare the category grid collection.
     *
     * @return $this
     */
    protected function _prepareCollection()
    {
        $collection = $this->categoryFactory->create()
            ->getCollection()
            ->addAttributeToSelect('*');
           
        $collection->getSelect()
            ->reset(Zend_Db_Select::COLUMNS)
            ->columns(['entity_id', 'e.children_count as childrenCount']);
            
        $collection->addAttributeToSelect('*')
            ->addFieldToFilter('name', ["neq"=>null])
            ->addFieldToFilter('is_active', 1);
            
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    /**
     * @inheritdoc
     */
    protected function _prepareColumns()
    {
        $this->addColumn(
            "entity_id",
            [
                "type"     => "number",
                "align"    => "center",
                "width"    => "30px",
                "index"    => "entity_id",
                "header"   => __("ID")
            ]
        );

        $this->addColumn(
            "name",
            [
                "index"    => "name",
                "align"    => "left",
                "header"   => __("Category Name")
            ]
        );

        $this->addColumn(
            "childrenCount",
            [
                "index"    => "childrenCount",
                "align"    => "left",
                "header"   => __("Children Count")
            ]
        );

        $this->addColumn(
            "in_categories",
            [
                "type"     => "checkbox",
                "name"     => "in_categories",
                "align"    => "center",
                "width"    => "100px",
                "index"    => "entity_id",
                "values"   => $this->_getSelectedCategories(),
                "header"   => __("Select"),
                "sortable" => false
            ]
        );

        $this->addColumn(
            "inv",
            [
                "type"     => "input",
                "class"    => "number_check loyalty_points",
                "width"    => "150px",
                "align"    => "center",
                "index"    => "inv",
                "filter"   => false,
                "header"   => __("Loyalty Points"),
                "sortable" => false,
                "renderer" => VendorCustomModuleBlockAdminhtmlPoints::class
            ]
        );
        
        return parent::_prepareColumns();
    }

    /**
     * @inheritdoc
     */
    public function getGridUrl()
    {
        return $this->getUrl("*/*/categoryGridData", ["_current"=>true]);
    }

    /**
     * @return array
     */
    protected function _getSelectedCategories()
    {
        $categoryIds = [];
        $ruleId      = $this->getRequest()->getParam("id");
        $pointsCollection = $this->ruleCategoryCollection->create()
            ->addFieldToFilter("loyalty_rule_id", $ruleId);
        
        foreach ($pointsCollection as $each) {
            $categoryIds[] = $each->getCategoryId();
        }
        return $categoryIds;
    }
}
classGridWithChildrenCount

I hope this helps. Thank you 🙂

Previous blog: Fix a class grid issue with the Children_count column in the custom UI component

Next blog: Create and edit data in the category grid in a custom UI component format in Magento 2

LEAVE A REPLY

Please enter your comment!
Please enter your name here