Magento 2 : Add Block Grid’s Column Custom Filter

Creating a grid in Magento 2 can be a powerful tool for managing data and providing a user-friendly interface for administrators. One key aspect of any grid is the ability to filter data based on specific criteria. In Magento 2, one way to filter grid data is by using the “%%” operator.

The “%%” operator is a wildcard that matches any number of characters in a given column value. For example, if you have a grid displaying a list of customers and you want to filter by last name, you can use the “%%” operator to search for all last names containing a specific string of characters. This can be especially useful when dealing with large datasets or when searching for partial matches.

To use the “%%” operator in a Magento 2 grid, you first need to define the column you want to filter. This is typically done in the _prepareColumns() method of your grid block class. Within this method, you can use the addColumn() method to define each column and its properties. To enable filtering on a specific column, you can set the filter_condition_callback property to a callback function that defines the filtering logic.

Here’s an example of how to use the “%%” operator to filter a customer grid by last name:

$this->addColumn(
    'lastname',
    [
        'header' => __('Last Name'),
        'index' => 'lastname',
        'filter_condition_callback' => [$this, '_filterLastName']
    ]
);

...

protected function _filterLastName($collection, $column)
{
    if (!$value = $column->getFilter()->getValue()) {
        return $this;
    }

    $this->getCollection()->addFieldToFilter('lastname', ['like' => '%' . $value . '%']);

    return $this;
}

In this example, we define a lastname column and set the filter_condition_callback property to the _filterLastName() method. This method takes two arguments: the collection to filter and the column being filtered. We first check if a filter value has been set, and if not, we return the collection unchanged. If a filter value is set, we use the addFieldToFilter() method to add a “like” condition to the collection, using the “%%” operator to match any last name containing the filter value.

Using the “%%” operator in a Magento 2 grid can make filtering data more flexible and powerful. By defining custom filter callbacks, you can customize the behavior of your grids to meet the specific needs of your application. With this technique, you can create powerful, user-friendly interfaces for managing your data.

Leave a Comment

Your email address will not be published. Required fields are marked *