To add default filter to grid in Magento2?
If you define grid collection thought layout than you can use updater to add default filter.
<argument name="dataSource" xsi:type="object">
Tutorial\SimpleNews\Model\Resource\News\Collection
<updater>Tutorial\SimpleNews\Model\Resource\News\Collection\Updater</updater>
</argument>
and
<?php
namespace Tutorial\SimpleNews\Model\Resource\News\Collection;
class CollectionUpdater implements \Magento\Framework\View\Layout\Argument\UpdaterInterface
{
/**
* Update grid collection according to chosen order
*
* @param \Tutorial\SimpleNews\Model\Resource\News\Collection $argument
* @return \Tutorial\SimpleNews\Model\Resource\News\Collection
*/
public function update($argument)
{
$argument->addFieldToFilter('you_field', 'value');
return $argument;
}
}
or Extend Grid block
class Grid extends \Magento\Backend\Block\Widget\Grid
{
protected function _prepareCollection()
{
if ($this->getCollection()) {
foreach ($this->getDefaultFilter() as $field => $value) {
$this->getCollection()->addFieldToFilter($field, $value);
}
}
return parent::_prepareCollection();
}
}
you need to add this inside the arguments tag:
<argument name="default_filter" xsi:type="array">
<item name="field_name_here" xsi:type="string">value here</item>
</argument>
if your arguments are contained in this block
<block class="Magento\Backend\Block\Widget\Grid" name="some.name.here" as="grid">
you need to create your own class that extends Magento\Backend\Block\Widget\Grid
like this:
<?php
namespace Namespace\Module\Block\Adminhtml\Whatever;
class Grid extends \Magento\Backend\Block\Widget\Grid
{
public function _construct()
{
parent::_construct();
if ($this->hasData('default_filter')) {
$this->setDefaultFilter($this->getData('default_filter'));
}
}
}
and modify the block tag above to
<block class="Namespace\Module\Block\Adminhtml\Whatever\Grid" name="some.name.here" as="grid">
if you already use a custom grid and not the default Magento\Backend\Block\Widget\Grid
you don't need to create the class.
You just need to copy the _construct
method from above in your class.