How can I create custom collection to show data in grid in back-end. Example, I want to show a list of log files or show cron job tasks, The did not come from Database, just an array I collect.

Please help me.


You can create a custom collection class and instead of extending it to the usual Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection you can extend it to Magento\Framework\Data\Collection and use the addItem method to add your array values as collection items.

First the we need a collection class app/code/<Vendor>/<Module-Name>/Model/ResourceModel/Logs/Collection.php

namespace <Vendor>\<Module-Name>\Model\ResourceModel\Logs;

use Magento\Framework\Data\Collection as DataCollection;

class Collection extends DataCollection

}//end class

Now for the Grid file app/code/<Vendor>/<Module-Name>/Block/Adminhtml/Logs/Grid.php


 namespace <Vendor>\<Module-Name>\Block\Adminhtml\Logs;

 use Magento\Backend\Block\Widget\Grid\Extended;
 use Magento\Backend\Block\Template\Context;
 use Magento\Backend\Helper\Data;
 use <Vendor>\<Module-Name>\Model\ResourceModel\Logs\Collection; 

 class Grid extends Extended

     * @var Collection
    protected $_collection;

    * Constructor
    * @param Context $context
    * @param Data $backendHelper
    * @param Collection $collection
    * @param array $data
    public function __construct(
        Context $context,
        Data $backendHelper,
        Collection $collection,
        array $data = []
    ) {
        $this->_collection = $collection;
        parent::__construct($context, $backendHelper, $data);
    }//end __construct()

    * @return void
    protected function _construct()

    protected function _prepareCollection()
        $logData = [
                'id' => 1,
                'value' => "Some Value"
                'id' => 2,
                'value' => "Some Another Value"
        $collection = $this->_collection;
        foreach ($logData as $data) {
            $DataObject = new \Magento\Framework\DataObject($data);
        return parent::_prepareCollection();
    }//end _prepareCollection()

    protected function _prepareColumns()
       //Your columns
       return parent::_prepareColumns();
    }//end _prepareColumns()
}//end class
|improve this answer|||||
  • Thanks, Could you give me an example how I can extend and build it inside a module ? – Daniel Dinh May 30 '16 at 10:54
  • Ya sure let me modify my answer – Atish Goswami May 30 '16 at 10:58
  • See if this is more helpful – Atish Goswami May 30 '16 at 11:22

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.