Magento 2: Display Certain Rows from Custom Table in Admin Grid

customgridmagento2table

I have a custom table(id,product_id,company_code) that is displayed on the backend as a grid.

To create the grid, I followed this link.

This displays all the records from the table. I need to show only those records that have company_code = 1.

I am very new to Magento and not sure about the terminology.

Best Answer

If you want to limit the collection that shows within the grid when using the UI component, you need to look at the DataProvider class. There are methods in there which allow you to add "filters" that are always present (e.g. limiting rows to only those within a specific store).

For example, I have a custom module that keeps a history of changes made within this module on a per-item basis. So customers can have multiple "items" and a history is recorded when they act upon the item (e.g. update data). To show this history within the admin, I can't just show all the history in the grid, I need to filter it to the relevant history associated to an item ID.

So in my ui_component xml document I look at the dataProvider node to see which class is providing the data:

<!-- define the date source (must be the same than in argument/item/provider and argument/js_config/deps -->
    <dataSource name="contacts_contact_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <!-- unique name for the grid -->
            <argument name="class" xsi:type="string">ContactsGridDataProvider</argument>
            <!-- name of the data source same as in argument/js_config/provider -->

In this case, the class is "ContactsGridDataProvider". Whatever class that points to should extend the class \Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider. In that class you could override the prepareUpdateUrl method and add any filter(s) you wish.

For example, my data provider overrides that function to add a filter for the "item id" the user is currently looking at:

class ScopedDataProvider extends \Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider
{
    public function prepareUpdateUrl()
    {
        parent::prepareUpdateUrl();

        if ($this->request->getParam('id')) {
            $itemId = $this->request->getParam('id');
        } else {
            $itemId = $this->request->getParam('item_id');
        }

        if ($itemId) {
            $this->addFilter(
                $this->filterBuilder->setField('item_id')
                    ->setValue($itemId)
                    ->setConditionType('eq')
                    ->create()
            );
        }
    }
}

Adding this filter was enough to limit the scope of the grid to only those items related to the item currently being viewed. This seems like what you want to do with limiting the "ids" to only be shown if company_code = 1.

Hope that helps you out.

Related Topic