Virtualtype admin grid filter data collection in Magento 2
Instead of using a virtual type, you need to create a class which extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
and has a _beforeLoad
method where the test_id
filter is applied.
Example:
use Magento\Framework\App\RequestInterface;
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 Psr\Log\LoggerInterface as Logger;
class Collection extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{
protected $request;
public function __construct(
EntityFactory $entityFactory,
Logger $logger,
FetchStrategy $fetchStrategy,
EventManager $eventManager,
$mainTable = 'module_test',
$resourceModel = 'Namespace\Module\Model\ResourceModel\Test\Collection',
RequestInterface $request
) {
$this->request = $request;
parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $mainTable, $resourceModel);
}
public function _beforeLoad()
{
// show only items with passed in parameter
if ($testId = $this->request->getParam('test_id')) {
$this->addFieldToFilter('test_id', $testId);
}
return parent::_beforeLoad();
}
}
if you have this in your ui component :
<item name="update_url" path="mui/index/render" xsi:type="url"/>
then add this code below above code:
<item name="filter_url_params" xsi:type="array">
<item name="test_id" xsi:type="boolean">1</item>
</item>