I need to filter Magento 2 custom grid model collection by URL parameter. I have used this below code.
protected function _initSelect() {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$request = $objectManager->get('Magento\Framework\App\Request\Http');
$seller_id = $request->getParam('seller_id');
$this->addFilterToMap('increment_id', 'main_table.increment_id');
$this->addFilterToMap('status', 'main_table.status');
$this->addFilterToMap('seller_id', 'main_table.seller_id');
$this->addFieldToFilter('seller_id', ['eq' => $seller_id]);
$this->getSelect()->joinLeft(
['secondTable' => $this->getTable('sales_order_grid')], //2nd table name by which you want to join mail table
'main_table.order_id = secondTable.entity_id', // common column which available in both table
'*' // '*' define that you want all column of 2nd table. if you want some particular column then you can define as ['column1','column2']
)->group('main_table.order_id');
//$this->addFieldToFilter('main_table.seller_id', ['eq' => '39']);
parent::_initSelect();
// var_dump($this->getSelect()->__toString());
// exit;
return $this;
}
When I log this seller_id it is showing by when I pass in filter not working. it is working when I pass a static value. I'm not sure how to filter a collection by param in the model.
1 Answer 1
parent::_initSelect(); should be called on start of _initSelect.
Code might look like:
protected function _initSelect()
{
parent::_initSelect();
$tableDescription = $this->getConnection()->describeTable($this->getMainTable());
foreach ($tableDescription as $columnInfo) {
$this->addFilterToMap($columnInfo['COLUMN_NAME'], 'main_table.' . $columnInfo['COLUMN_NAME']);
}
$this->getSelect()->joinLeft(
['secondTable' => $this->getTable('sales_order_grid')], //2nd table name by which you want to join mail table
'main_table.order_id = secondTable.entity_id', // common column which available in both table
'*' // '*' define that you want all column of 2nd table. if you want some particular column then you can define as ['column1','column2']
);
$this->getSelect()->group('main_table.order_id');
// Add your fiter after join
return $this;
}
answered May 13, 2021 at 4:23
Explore related questions
See similar questions with these tags.
default