6

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..

2
  • Have you try with, $post = $this->getRequest()->getPostValue(); $postObject = new \Magento\Framework\DataObject(); $postObject->setData($post); Commented Jan 4, 2017 at 9:54
  • @Rakesh That will create DataObject, So now I have Object which I want to convert into magento2 collection .. Commented Jan 4, 2017 at 9:58

1 Answer 1

11

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;
8
  • but still its not giving all the methods available with core magento collection for example getSelect() is not available. Commented Jan 4, 2017 at 10:18
  • Of course not, this is the equivalent to Varien_Data_Collection which also does not have a getSelect() method. These are the basic collection classes, not the database specific collection classes, and the way you are using them, the database specific methods do not make sense. Commented Jan 4, 2017 at 10:20
  • filters are not working with Data Collection, I have gone to the method addFieldToFilter its returning nothing just throwing error ..any help ? Commented Jan 4, 2017 at 15:20
  • This seems to be a different question. Magento (1 and 2) can not filter a "loaded" collection Commented Jan 4, 2017 at 15:41
  • 1
    When I print print_r($collection->getData()); data. It gives me an error. Commented Apr 18, 2018 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.