How to customize admin grid collection in magento 2:

This post will helpful when use more than one table join in magento 2 admin grid collection. Consider we have created one Module with admin grid collection (resourceModel , Model). In a grid you need add one filter field that too available in some other table not a module table. So we have to join both the tables (we can more than one tables with alias ). When we use the join use alias from your magento collection script. It will help to fetch the exact value from the respective table (to avoid the confusion when both the table column name is same)
Ex: Here i have to filter my magento collection by mobile_type column field. Which is available in other than module table. In a collection also we can do the customization or else we can do custom filter with in Grid.php itself. From Collection.php (it will read it from Model.php finally) will return the actual module collection to Grid.php
For the testing purpose in Grid.php itself i had included my filter .
To filter by defualt while render the grid itself in magenot 2 admin:

Script : 1

File path: Jute\Ecommerce\Block\Adminhtml\Grid.php
Note: main_table is my table alias.
 protected function _prepareCollection()  {
 /** @var \Jute\Ecommerce\Model\ResourceModel\Collection $collection */
 $collection = $this->_myCollectionFactory->create()->setStoreViewId(null);
 //Add your filter here
 $collection->addFieldToFilter('main_table.mobile_type', array('eq' => array(1,2)));
 $this->setCollection($collection);
 return parent::_prepareCollection();
 }

Leave a Reply