How to convert the Data object into Magento2 Collection ?

In Mage1 we could do as below..


$collection = new Varien_Data_Collection();                
foreach ($items as $item) {
    $varienObject = new Varien_Object();
return $collection;

but how do in Mage2 ??

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

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

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();
return $collection;
| improve this answer | |
  • but still its not giving all the methods available with core magento collection for example getSelect() is not available. – Mohammad Mujassam Jan 4 '17 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. – Fabian Schmengler Jan 4 '17 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 ? – Mohammad Mujassam Jan 4 '17 at 15:20
  • This seems to be a different question. Magento (1 and 2) can not filter a "loaded" collection – Fabian Schmengler Jan 4 '17 at 15:41
  • Magento2... this method is available with collection but throwing error – Mohammad Mujassam Jan 4 '17 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.