Select Page

Add custom column filter in customer grid collection in Magento 2

Khushboo Sahu
Published: May 15, 2022

<?php

namespace Vendor\Module\Model\ResourceModel\CustomerGrid;

 

use Magento\Customer\Model\ResourceModel\Customer;

use Magento\Customer\Ui\Component\DataProvider\Document;

use Magento\Framework\App\ObjectManager;

use Magento\Framework\Data\Collection\Db\FetchStrategyInterface as FetchStrategy;

use Magento\Framework\Data\Collection\EntityFactoryInterface as EntityFactory;

use Magento\Framework\Event\ManagerInterface as EventManager;

use Magento\Framework\Locale\ResolverInterface;

use Magento\Framework\Stdlib\DateTime\TimezoneInterface;

use Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult;

use Psr\Log\LoggerInterface as Logger;

 

/**

* Customer Grid Collection Class

*/

class Collection extends \Magento\Customer\Model\ResourceModel\Grid\Collection

{

 

    /**

     * @param EntityFactory $entityFactory

     * @param Logger $logger

     * @param FetchStrategy $fetchStrategy

     * @param EventManager $eventManager

     * @param ResolverInterface $localeResolver

     * @param \Magento\Backend\Model\Auth\Session $adminSession

     * @param string $mainTable

     * @param string $resourceModel

     * @param TimezoneInterface|null $timeZone

     */

    public function __construct(

        EntityFactory $entityFactory,

        Logger $logger,

        FetchStrategy $fetchStrategy,

        EventManager $eventManager,

        ResolverInterface $localeResolver,

        \Magento\Backend\Model\Auth\Session $adminSession,

        $mainTable = ‘customer_grid_flat’,

        $resourceModel = Customer::class,

        TimezoneInterface $timeZone = null

    ) {

        $this->adminSession = $adminSession;

        parent::__construct(

            $entityFactory,

            $logger,

            $fetchStrategy,

            $eventManager,

            $localeResolver,

            $mainTable,

            $resourceModel,

            $timeZone

        );

    }

 

    /**

     * @inheritdoc

     */

    protected function _initSelect()

    {

        parent::_initSelect();

 

        if (!is_null($this->adminSession->getUser())) {

            $roleName = $this->adminSession->getUser()->getRole()->getRoleName();

            $userId = $this->adminSession->getUser()->getId();

            if ($userId && $roleName != “Administrator”) {

                //added filter for user_id custom column

                $this->getSelect()->where(“main_table.user_id=$userId”);

            }

        }

        

        return $this;

    }

}

Source: webkul.com