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
<?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
<?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()
{
parent::_construct();
$this->setId('logs_grid');
$this->setDefaultSort('log_id');
$this->setDefaultDir('DESC');
$this->setSaveParametersInSession(true);
$this->setVarNameFilter('logs_record');
}
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);
$collection->addItem(
DataObject($DataObject)
);
}
$this->setCollection($collection);
return parent::_prepareCollection();
}//end _prepareCollection()
protected function _prepareColumns()
{
//Your columns
return parent::_prepareColumns();
}//end _prepareColumns()
}//end class