Magento 2: How to Add Attributes to Custom EAV Model Collection

admindata-providergridmagento2

Using Magento 2.1.3: I want to display custom EAV attributes in a admin grid, but can't figure out how to properly add them to the data provider collection. I would assume this would work, but it's throwing an undefined method error on addAttributeToSelect:

namespace Vendor\Namespace\Ui\Component\Listing\DataProviders\Namespace\Obj;

class Grid extends \Magento\Ui\DataProvider\AbstractDataProvider
{    
public function __construct(
    $name,
    $primaryFieldName,
    $requestFieldName,
    \Vendor\Namespace\Model\ResourceModel\Obj\CollectionFactory $collectionFactory,
    array $meta = [],
    array $data = []
) {
    parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
    $this->collection = $collectionFactory->create();
    $this->collection->addAttributeToSelect('*');
    $this->collection->load();
}
}

My \Vendor\Namespace\Model\ResourceModel\Obj\Collection class extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection

I have also now tried loading the product model, then getting the collection, and still no luck, however loading a obj directly contains the attributes:

....
_construct(
    ....
    \Vendor\Namespace\Model\ObjFactory $objFactory,
     ....
) {
   $obj = $objFactory->create()->load([id]);
   var_dump($obj->getData()); // has attributes
   $objCollection = $obj->getCollection();
   foreach ($objCollection as $cObj) {
        var_dump($cObj->getData()); // no attributes
   }
}

Best Answer

The resource model you're extending does not have an addAttributeToSelect method and is not intended to be used for EAV entities.

Your collection should extend \Magento\Eav\Model\Entity\Collection\AbstractCollection instead.