Magento – How to Set filter collection in custom model by product id magento 2

collection;gridmagento-2.1model

I want to filter collection in my custom model by product id to load the filter data value in admin grid.

My Model:-
Vender\Modulename\Model\Outofstock

namespace Vender\Modulename\Model;

class Outofstock extends \Magento\Framework\Model\AbstractModel
{
    protected function _construct()
    {
        $this->_init('Vender\Modulename\Model\ResourceModel\Outofstock');
    }
}

Resource Model:-

namespace Vender\Modulename\Model\ResourceModel;

class Outofstock extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    protected function _construct()
    {
        $this->_init('custom_table', 'id');
    }
}

Collection:-

namespace Vender\Modulename\Model\ResourceModel\Outofstock;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    protected $_idFieldName = 'id';

    protected function _construct()
    {
        $this->_init(
            'Vender\Modulename\Model\Outofstock',
            'Vender\Modulename\Model\ResourceModel\Outofstock'
        );
    }
}

I have already created a field with product_id and value 14

Please suggest me.If any other way is available to filter the collection before load in admin grid.

Can any one help me on this problem ? Any references or suggestions are highly appreciated.

Best Answer

You can try the below sample code.

If you define grid collection thought layout than you can use updater to add default filter.

<argument name="dataSource" xsi:type="object">
    Namespace\Modulename\Model\Resource\News\Collection
    <updater>Namespace\Modulename\Model\Resource\News\Collection\Updater</updater>
</argument>

and

<?php
namespace Namespace\Modulename\Model\Resource\News\Collection;

class CollectionUpdater implements \Magento\Framework\View\Layout\Argument\UpdaterInterface
{

    public function update($argument)
    {
        $argument->addFieldToFilter('you_field', 'value');

        return $argument;
    }
}