Create admin grid listing in Magento 2
Create Model File Allnews.php
Rsgitech\News\Model\Allnews.php
<?php
namespace Rsgitech\News\Model;
use Magento\Framework\Model\AbstractModel;
class Allnews extends AbstractModel
{
const STATUS_ENABLED = 1;
const STATUS_DISABLED = 0;
const CACHE_TAG = 'rsgitech_news';
//Unique identifier for use within caching
protected $_cacheTag = self::CACHE_TAG;
protected function _construct()
{
$this->_init('Rsgitech\News\Model\ResourceModel\Allnews');
}
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
public function getDefaultValues()
{
$values = [];
return $values;
}
public function getAvailableStatuses()
{
return [self::STATUS_ENABLED => __('Enabled'), self::STATUS_DISABLED => __('Disabled')];
}
}
?>
Create Resource Model
Rsgitech\News\Model\ResourceModel\Allnews.php
Define table in resource model
<?php
namespace Rsgitech\News\Model\ResourceModel;
use Magento\Framework\Model\AbstractModel;
class Allnews extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
public function __construct(
\Magento\Framework\Model\ResourceModel\Db\Context $context
) {
parent::__construct($context);
}
/**
* Define main table
*/
protected function _construct()
{
$this->_init('rsgitech_news', 'news_id');
}
}
?>
Create Collection
Rsgitech\News\Model\ResourceModel\Allnews\Collection.php
Define model and resource model
<?php
namespace Rsgitech\News\Model\ResourceModel\Allnews;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected $_idFieldName = 'news_id';
protected $_eventPrefix = 'news_allnews_collection';
protected $_eventObject = 'allnews_collection';
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init('Rsgitech\News\Model\Allnews', 'Rsgitech\News\Model\ResourceModel\Allnews');
}
}
?>
Create Grid Collection
Rsgitech\News\Model\ResourceModel\Allnews\Grid\Collection.php
<?php
namespace Rsgitech\News\Model\ResourceModel\Allnews\Grid;
use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Api\Search\AggregationInterface;
use Rsgitech\News\Model\ResourceModel\Allnews\Collection as AllnewsCollection;
/**
* Class Collection
* Collection for displaying grid
*/
class Collection extends AllnewsCollection implements SearchResultInterface
{
/**
* @var AggregationInterface
*/
protected $aggregations;
/**
* @param \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory
* @param \Psr\Log\LoggerInterface $logger
* @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
* @param \Magento\Framework\Event\ManagerInterface $eventManager
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\EntityManager\MetadataPool $metadataPool
* @param mixed|null $mainTable
* @param string $eventPrefix
* @param mixed $eventObject
* @param mixed $resourceModel
* @param string $model
* @param null $connection
* @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb|null $resource
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
\Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
\Magento\Framework\Event\ManagerInterface $eventManager,
$mainTable,
$eventPrefix,
$eventObject,
$resourceModel,
$model = \Magento\Framework\View\Element\UiComponent\DataProvider\Document::class,
\Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
\Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
) {
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$connection,
$resource
);
$this->_eventPrefix = $eventPrefix;
$this->_eventObject = $eventObject;
$this->_init($model, $resourceModel);
$this->setMainTable($mainTable);
}
/**
* @return AggregationInterface
*/
public function getAggregations()
{
return $this->aggregations;
}
/**
* @param AggregationInterface $aggregations
* @return $this
*/
public function setAggregations($aggregations)
{
$this->aggregations = $aggregations;
}
/**
* Get search criteria.
*
* @return \Magento\Framework\Api\SearchCriteriaInterface|null
*/
public function getSearchCriteria()
{
return null;
}
/**
* Set search criteria.
*
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return $this
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function setSearchCriteria(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria = null)
{
return $this;
}
/**
* Get total count.
*
* @return int
*/
public function getTotalCount()
{
return $this->getSize();
}
/**
* Set total count.
*
* @param int $totalCount
* @return $this
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function setTotalCount($totalCount)
{
return $this;
}
/**
* Set items list.
*
* @param \Magento\Framework\Api\ExtensibleDataInterface[] $items
* @return $this
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function setItems(array $items = null)
{
return $this;
}
}
?>
Create file status.php
Rsgitech\News\Model\Allnews\Source\Status.php
It is dropdown of status like as enabled and disabled
<?php
namespace Rsgitech\News\Model\Allnews\Source;
use Magento\Framework\Data\OptionSourceInterface;
class Status implements OptionSourceInterface
{
protected $allNews;
public function __construct(\Rsgitech\News\Model\Allnews $allNews)
{
$this->allNews = $allNews;
}
public function toOptionArray()
{
$availableOptions = $this->allNews->getAvailableStatuses();
$options = [];
foreach ($availableOptions as $key => $value) {
$options[] = [
'label' => $value,
'value' => $key,
];
}
return $options;
}
}
?>
Create Action Column of Grid Items
Rsgitech\News\Ui\Component\Listing\Column\AllnewsActions.php
You can create action of grid items like edit, delete, view etc.
<?php
namespace Rsgitech\News\Ui\Component\Listing\Column;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Escaper;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
/**
* Class AllnewsActions
*/
class AllnewsActions extends Column
{
/** Url path */
const CMS_URL_PATH_EDIT = 'news/allnews/edit';
const CMS_URL_PATH_DELETE = 'news/allnews/delete';
/**
* @var \Magento\Framework\UrlInterface
*/
protected $urlBuilder;
/**
* @var string
*/
private $editUrl;
/**
* @var Escaper
*/
private $escaper;
/**
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param UrlInterface $urlBuilder
* @param array $components
* @param array $data
* @param string $editUrl
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
UrlInterface $urlBuilder,
array $components = [],
array $data = [],
$editUrl = self::CMS_URL_PATH_EDIT
) {
$this->urlBuilder = $urlBuilder;
$this->editUrl = $editUrl;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
/**
* Prepare Data Source
*
* @param array $dataSource
* @return array
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
$name = $this->getData('name');
if (isset($item['news_id'])) {
$item[$name]['edit'] = [
'href' => $this->urlBuilder->getUrl($this->editUrl, ['news_id' => $item['news_id']]),
'label' => __('Edit')
];
$title = $this->getEscaper()->escapeHtml($item['title']);
$item[$name]['delete'] = [
'href' => $this->urlBuilder->getUrl(self::CMS_URL_PATH_DELETE, ['news_id' => $item['news_id']]),
'label' => __('Delete'),
'confirm' => [
'title' => __('Delete %1', $title),
'message' => __('Are you sure you want to delete a %1 record?', $title)
]
];
}
}
}
return $dataSource;
}
/**
* Get instance of escaper
* @return Escaper
* @deprecated 101.0.7
*/
private function getEscaper()
{
if (!$this->escaper) {
$this->escaper = ObjectManager::getInstance()->get(Escaper::class);
}
return $this->escaper;
}
}
?>
Create file di.xml
Rsgitech\News\etc\di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<virtualType name="AllnewsGridDataProvider" type="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider">
<arguments>
<argument name="collection" xsi:type="object" shared="false">Rsgitech\News\Model\ResourceModel\Allnews\Collection</argument>
</arguments>
</virtualType>
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="news_allnews_listing_data_source" xsi:type="string">Rsgitech\News\Model\ResourceModel\Allnews\Grid\Collection</item>
</argument>
</arguments>
</type>
<type name="Rsgitech\News\Model\ResourceModel\Allnews\Grid\Collection">
<arguments>
<argument name="mainTable" xsi:type="string">rsgitech_news</argument>
<argument name="eventPrefix" xsi:type="string">rsgitech_news_grid_collection</argument>
<argument name="eventObject" xsi:type="string">rsgitech_news_collection</argument>
<argument name="resourceModel" xsi:type="string">Rsgitech\Rsgitech\Model\ResourceModel\Allnews</argument>
</arguments>
</type>
</config>
Controller Action Index.php
Rsgitech\News\Controller\Adminhtml\AllNews\Index.php
Change controller file like this
<?php
namespace Rsgitech\News\Controller\Adminhtml\AllNews;
class Index extends \Magento\Backend\App\Action
{
protected $resultPageFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->prepend(__('All News'));
return $resultPage;
}
}
?>
Create view file of ui component
Rsgitech\News\view\adminhtml\ui_component\news_allnews_listing.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">news_allnews_listing.news_allnews_listing_data_source</item>
<item name="deps" xsi:type="string">news_allnews_listing.news_allnews_listing_data_source</item>
</item>
<item name="spinner" xsi:type="string">allnews_columns</item>
<item name="buttons" xsi:type="array">
<item name="add" xsi:type="array">
<item name="name" xsi:type="string">add</item>
<item name="label" xsi:type="string" translate="true">Add News</item>
<item name="class" xsi:type="string">primary</item>
<item name="url" xsi:type="string">*/*/new</item>
</item>
</item>
</argument>
<dataSource name="news_allnews_listing_data_source">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">AllnewsGridDataProvider</argument>
<argument name="name" xsi:type="string">news_allnews_listing_data_source</argument>
<argument name="primaryFieldName" xsi:type="string">news_id</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
<item name="update_url" xsi:type="url" path="mui/index/render"/>
<item name="storageConfig" xsi:type="array">
<item name="indexField" xsi:type="string">news_id</item>
</item>
</item>
</argument>
</argument>
</dataSource>
<listingToolbar name="listing_top">
<settings>
<sticky type="xs:boolean">false</sticky>
</settings>
<bookmark name="bookmarks"/>
<columnsControls name="columns_controls" />
<filterSearch name="fulltext"/>
<filters name="listing_filters">
<argument name="data" xsi:type="array">
<item name="observers" xsi:type="array">
<item name="column" xsi:type="string">column</item>
</item>
</argument>
<settings>
<templates>
<filters>
<select>
<param name="template" xsi:type="string">ui/grid/filters/elements/ui-select</param>
<param name="component" xsi:type="string">Magento_Ui/js/form/element/ui-select</param>
</select>
</filters>
</templates>
</settings>
</filters>
<massaction name="listing_massaction">
<action name="delete">
<settings>
<confirm>
<message translate="true">Are you sure you want to delete selected items?</message>
<title translate="true">Delete items</title>
</confirm>
<url path="news/allnews/massDelete"/>
<type>delete</type>
<label translate="true">Delete</label>
</settings>
</action>
</massaction>
<paging name="listing_paging"/>
</listingToolbar>
<columns name="allnews_columns">
<settings>
<editorConfig>
<param name="clientConfig" xsi:type="array">
<item name="saveUrl" xsi:type="url" path="news/allnews/inlineEdit"/>
<item name="validateBeforeSave" xsi:type="boolean">false</item>
</param>
<param name="indexField" xsi:type="string">news_id</param>
<param name="enabled" xsi:type="boolean">true</param>
<param name="selectProvider" xsi:type="string">news_allnews_listing.news_allnews_listing.allnews_columns.ids</param>
</editorConfig>
<childDefaults>
<param name="fieldAction" xsi:type="array">
<item name="provider" xsi:type="string">news_allnews_listing.news_allnews_listing.allnews_columns_editor</item>
<item name="target" xsi:type="string">startEdit</item>
<item name="params" xsi:type="array">
<item name="0" xsi:type="string">${ $.$data.rowIndex }</item>
<item name="1" xsi:type="boolean">true</item>
</item>
</param>
</childDefaults>
</settings>
<selectionsColumn name="ids">
<settings>
<indexField>news_id</indexField>
<resizeEnabled>false</resizeEnabled>
<resizeDefaultWidth>55</resizeDefaultWidth>
</settings>
</selectionsColumn>
<column name="news_id">
<settings>
<filter>textRange</filter>
<label translate="true">ID</label>
<sorting>asc</sorting>
</settings>
</column>
<column name="title">
<settings>
<filter>text</filter>
<editor>
<validation>
<rule name="required-entry" xsi:type="boolean">true</rule>
</validation>
<editorType>text</editorType>
</editor>
<label translate="true">Title</label>
</settings>
</column>
<column name="status" component="Magento_Ui/js/grid/columns/select">
<settings>
<options class="Rsgitech\News\Model\Allnews\Source\Status"/>
<filter>select</filter>
<editor>
<editorType>select</editorType>
</editor>
<dataType>select</dataType>
<label translate="true">Status</label>
</settings>
</column>
<column name="created_at" class="Magento\Ui\Component\Listing\Columns\Date" component="Magento_Ui/js/grid/columns/date">
<settings>
<filter>dateRange</filter>
<dataType>date</dataType>
<label translate="true">Created</label>
</settings>
</column>
<column name="updated_at" class="Magento\Ui\Component\Listing\Columns\Date" component="Magento_Ui/js/grid/columns/date">
<settings>
<filter>dateRange</filter>
<dataType>date</dataType>
<label translate="true">Modified</label>
</settings>
</column>
<actionsColumn name="actions" class="Rsgitech\News\Ui\Component\Listing\Column\AllnewsActions">
<settings>
<indexField>news_id</indexField>
<resizeEnabled>false</resizeEnabled>
<resizeDefaultWidth>107</resizeDefaultWidth>
</settings>
</actionsColumn>
</columns>
</listing>
Layout
Rsgitech\News\view\adminhtml\layout\news_allnews_index.xml
Load uiComponent news_allnews_listing in news_allnews_index.xml file
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="styles"/>
<body>
<referenceContainer name="content">
<uiComponent name="news_allnews_listing"/>
</referenceContainer>
</body>
</page>
Then run below commands
php bin/magento setup:upgrade
php bin/magetno setup:static-content:deploy
php bin/magento cache:flush
0 comments:
Post a Comment
Thanks