top of page
Writer's pictureVishesh Dwivedi

Add working filter for custom additional column in UI component grid Magento 2

Recently I was working on a module and came across a situation where I need to display customer name in the admin UI grid on the basis of customer id. So for that I have used _renderFiltersBefore() method and implemented my logic there.


So, as of now, customer name is showing in my grid.


But the error occurs when we try to filter the grid by customer name.


Actually when we use filters in UI component, it filters the collection using addFieldToFilter() method and return the desired result but addFieldToFilter() doesn't work with the joined collections, and that's the reson we are getting system exception.


So, here comes the role of addFilterToMap() method. If we look at this method -


/**
 * Add filter to Map
 *
 * @param string $filter
 * @param string $alias
 * @param string $group default 'fields'
 * @return $this
 */
public function addFilterToMap($filter, $alias, $group = 'fields')
{
    if ($this->_map === null) {
        $this->_map = [$group => []];
    } elseif (empty($this->_map[$group])) {
       $this->_map[$group] = [];
    }
    $this->_map[$group][$filter] = $alias;

    return $this;
}

It adds the additional fields to the _map array, and you must have use this array in your collection class like this -


$this->_map['fields']['entity_id'] = 'main_table.entity_id';

Basically, addFilterToMap() method maps the additional fields to the collection. The _map array contains all the collection data groupwise, so all the collection fields are stored in this array and addFilterToMap method also maps the joined table fields to this array. Now addFieldToFilter() will work for the joined field also.


So, I just call this method in my grid collection class like below and my UI filters started working as magic.

public function _construct()
{
    parent::_construct();
    $this->addFilterToMap(
        'customer_name', 'customerGridFlat.name'
    );
}

Here I am using _construct() method as this method initializes in the constructor, you can use any method according to your need (customerGridFlat is an alias used for customer_grid_flat table in join condition.)


Thank you. Happy Filtering ;) .

928 views0 comments

Recent Posts

See All

Comments


bottom of page