Magento – Magento2: Convert DataObject/Array into magento2 Collection

collection;magento-2.1magento2object

How to convert the Data object into Magento2 Collection ?

In Mage1 we could do as below..

Mage1:

$collection = new Varien_Data_Collection();                
foreach ($items as $item) {
    $varienObject = new Varien_Object();
    $varienObject->setData($item);
    $collection->addItem($varienObject);
}
return $collection;

but how do in Mage2 ??

I know How set the DataObject But problem with Making the collection..

Best Answer

The collection class is Magento\Framework\Data\Collection, but you need to instantiate it using the autogenerated factory Magento\Framework\Data\CollectionFactory. Obtain it using the object manager or - preferred - by adding it as constructor parameter to the class where you use it (dependency injection)

Then your code becomes:

$collection = $this->collectionFactory->create();
foreach ($items as $item) {
    $varienObject = new \Magento\Framework\DataObject();
    $varienObject->setData($item);
    $collection->addItem($varienObject);
}
return $collection;
Related Topic