Magento 2 – How to Create Grid Using UI Component for Custom EAV Model

admineavgridmagento-2.1magento2

I have created a new entity type and custom EAV model. Now i am trying to create grid for it using ui component. How we can use the eav data collection instead of flat table for grid?

Best Answer

I've been able to do this within the admin section. You need to have your ResourceModel collection extend from the \Magento\Eav\Model\Entity\Collection\AbstractCollection class. Within your Grid Data provider, load the collection and use addAttributeToSelect('*'):

class Grid extends \Magento\Ui\DataProvider\AbstractDataProvider
{    

public function __construct(
    ....
    \[Namespace]\[Module]\Model\ResourceModel\[Obj]\CollectionFactory $collectionFactory,
    ....
) {
    ....
    $collection = $collectionFactory->create();
    $collection->addAttributeToSelect('*');
    $this->collection = $collection;
    ...
}}

which will load up the attribute values, then you need to specify the columns in the grid in your [Namespace][Module]/view/[loc]/ui_component/[ui_component_grid_name].xml layout:

<listing ...>
...
<columns ...>
    ...
    <column name="[attribute_code]">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                ...
                <item name="label" xsi:type="string" translate="true">[Attribute Label]</item>
                ...
            </item>
        </argument>
    </column>
    ...
</columns>