How to add grid items in Magento 2

Posted at: September 21, 2018 4:04 PM

Create Allnews Interface

Rsgitech\News\Api\Data\AllnewsInterface.php

Create interface for fields


<?php
namespace Rsgitech\News\Api\Data;

interface AllnewsInterface
{
	const NEWS_ID = 'news_id';
	const TITLE  = 'title';
	const DESCRIPTION = 'description';
	const STATUS = 'status';
	const CREATED_AT = 'created_at';
	const UPDATED_AT = 'updated_at';

	public function getId();

	public function getTitle();

	public function getDescription();

	public function getStatus();

	public function getCreatedAt();

	public function getUpdatedAt();

	public function setId($id);

	public function setTitle($title);

	public function setDescription($description);

	public function setStatus($status);

	public function setCreatedAt($created_at);

	public function setUpdatedAt($updated_at);
}
?>

Implement Interface in Allnews Model

Rsgitech\News\Model\Allnews.php


<?php
namespace Rsgitech\News\Model;

use Rsgitech\News\Api\Data\AllnewsInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\AbstractModel;

class Allnews extends AbstractModel implements AllnewsInterface, IdentityInterface
{
	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')];
	}

	public function getId()
	{
		return parent::getData(self::NEWS_ID);
	}

	public function getTitle()
	{
		return $this->getData(self::TITLE);
	}

	public function getDescription()
	{
		return $this->getData(self::DESCRIPTION);
	}

	public function getStatus()
	{
		return $this->getData(self::STATUS);
	}

	public function getCreatedAt()
	{
		return $this->getData(self::CREATED_AT);
	}

	public function getUpdatedAt()
	{
		return $this->getData(self::UPDATED_AT);
	}

	public function setId($id)
	{
		return $this->setData(self::NEWS_ID, $id);
	}

	public function setTitle($title)
	{
		return $this->setData(self::TITLE, $title);
	}

	public function setDescription($description)
	{
		return $this->setData(self::DESCRIPTION, $description);
	}

	public function setStatus($status)
	{
		return $this->setData(self::STATUS, $status);
	}

	public function setCreatedAt($created_at)
	{
		return $this->setData(self::CREATED_AT, $created_at);
	}

	public function setUpdatedAt($updated_at)
	{
		return $this->setData(self::UPDATED_AT, $updated_at);
	}
}
?>

Create AllnewsRepositoryInterface

Rsgitech\News\Api\AllnewsRepositoryInterface.php

Create AllnewsRepositoryInterface for save, delete, getById, deleteById


<?php
namespace Rsgitech\News\Api;

interface AllnewsRepositoryInterface
{
	public function save(\Rsgitech\News\Api\Data\AllnewsInterface $news);

    public function getById($newsId);

    public function delete(\Rsgitech\News\Api\Data\AllnewsInterface $news);

    public function deleteById($newsId);
}
?>

Create class AllnewsRepository

Rsgitech\News\Model\AllnewsRepository.php

Create class AllnewsRepository and implements interface AllnewsRepositoryInterface


<?php

namespace Rsgitech\News\Model;

use Rsgitech\News\Api\Data;
use Rsgitech\News\Api\AllnewsRepositoryInterface;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Reflection\DataObjectProcessor;
use Rsgitech\News\Model\ResourceModel\Allnews as ResourceAllnews;
use Rsgitech\News\Model\ResourceModel\Allnews\CollectionFactory as AllnewsCollectionFactory;
use Magento\Store\Model\StoreManagerInterface;

class AllnewsRepository implements AllnewsRepositoryInterface
{
    protected $resource;

    protected $allnewsFactory;

    protected $dataObjectHelper;

    protected $dataObjectProcessor;

    protected $dataAllnewsFactory;

    private $storeManager;

    public function __construct(
        ResourceAllnews $resource,
        AllnewsFactory $allnewsFactory,
        Data\AllnewsInterfaceFactory $dataAllnewsFactory,
        DataObjectHelper $dataObjectHelper,
		DataObjectProcessor $dataObjectProcessor,
        StoreManagerInterface $storeManager
    ) {
        $this->resource = $resource;
		$this->allnewsFactory = $allnewsFactory;
        $this->dataObjectHelper = $dataObjectHelper;
        $this->dataAllnewsFactory = $dataAllnewsFactory;
		$this->dataObjectProcessor = $dataObjectProcessor;
        $this->storeManager = $storeManager;
    }

    public function save(\Rsgitech\News\Api\Data\AllnewsInterface $news)
    {
        if ($news->getStoreId() === null) {
            $storeId = $this->storeManager->getStore()->getId();
            $news->setStoreId($storeId);
        }
        try {
            $this->resource->save($news);
        } catch (\Exception $exception) {
            throw new CouldNotSaveException(
                __('Could not save the news: %1', $exception->getMessage()),
                $exception
            );
        }
        return $news;
    }

    public function getById($newsId)
    {
		$news = $this->allnewsFactory->create();
        $news->load($newsId);
        if (!$news->getId()) {
            throw new NoSuchEntityException(__('News with id "%1" does not exist.', $newsId));
        }
        return $news;
    }
	
    public function delete(\Rsgitech\News\Api\Data\AllnewsInterface $news)
    {
        try {
            $this->resource->delete($news);
        } catch (\Exception $exception) {
            throw new CouldNotDeleteException(__(
                'Could not delete the news: %1',
                $exception->getMessage()
            ));
        }
        return true;
    }

    public function deleteById($newsId)
    {
        return $this->delete($this->getById($newsId));
    }
}
?>

Resource model Allnews

Rsgitech\News\Model\ResourceModel\Allnews.php

Here set created at and updated at date before save


<?php
namespace Rsgitech\News\Model\ResourceModel;

use Magento\Framework\Model\AbstractModel;

class Allnews extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
	protected $_date;
	
	public function __construct(
        \Magento\Framework\Model\ResourceModel\Db\Context $context,
		\Magento\Framework\Stdlib\DateTime\DateTime $date
    ) {
        parent::__construct($context);
		$this->_date = $date;
    }
	
	/**
     * Define main table
     */
	protected function _construct()
	{
		$this->_init('rsgitech_news', 'news_id');
	}
	
	protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
    {
        $object->setUpdatedAt($this->_date->date());
        if ($object->isObjectNew()) {
            $object->setCreatedAt($this->_date->date());
        }
        return parent::_beforeSave($object);
    }
}
?>

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">
	<preference for="Rsgitech\News\Api\Data\AllnewsInterface" type="Rsgitech\News\Model\Allnews" />
	<preference for="Rsgitech\News\Api\AllnewsRepositoryInterface" type="Rsgitech\News\Model\AllnewsRepository" />
	<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>
	<type name="Magento\Framework\Model\Entity\RepositoryFactory">
        <arguments>
            <argument name="entities" xsi:type="array">
                <item name="Rsgitech\News\Api\Data\AllnewsInterface" xsi:type="string">Rsgitech\News\Api\AllnewsRepositoryInterface</item>
            </argument>
        </arguments>
    </type>
</config>

Create file acl.xml

Rsgitech\News\etc\acl.xml

Create ACL file for user authorization


<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
	<acl>
		<resources>
			<resource id="Magento_Backend::admin">
				<resource id="Rsgitech_News::rsgitech" title="Rsgitech" sortOrder="51">
					<resource id="Rsgitech_News::news_allnews" title="All News" sortOrder="10">
						<resource id="Rsgitech_News::save" title="Save News" translate="title" sortOrder="10" />
						<resource id="Rsgitech_News::news_delete" title="Delete News" translate="title" sortOrder="20" />
					</resource>
				</resource>
				<resource id="Magento_Backend::stores">
					<resource id="Magento_Backend::stores_settings">
						<resource id="Magento_Config::config">
							<resource id="Rsgitech_News::news_config" title="Rsgitech News" translate="title"/>
						</resource>
					</resource>
				</resource>
			</resource>
		</resources>
	</acl>
</config>

Create block Allnews

Rsgitech\News\Block\Adminhtml\Allnews.php


<?php
namespace Rsgitech\News\Block\Adminhtml;

class Allnews extends \Magento\Backend\Block\Widget\Grid\Container
{
    protected function _construct()
    {
        $this->_controller = 'adminhtml_allnews';
        $this->_blockGroup = 'Rsgitech_News';
        $this->_headerText = __('Manage News');

        parent::_construct();

        if ($this->_isAllowedAction('Rsgitech_News::save')) {
            $this->buttonList->update('add', 'label', __('Add News'));
        } else {
            $this->buttonList->remove('add');
        }
    }

    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }
}
?>

Create Grid Block

Rsgitech\News\Block\Adminhtml\Allnews\Grid.php


<?php
namespace Rsgitech\News\Block\Adminhtml\Allnews;

class Grid extends \Magento\Backend\Block\Widget\Grid
{
 
}
?>

Create GenericButton Block

Rsgitech\News\Block\Adminhtml\Allnews\Edit\GenericButton.php


<?php
namespace Rsgitech\News\Block\Adminhtml\Allnews\Edit;

use Magento\Backend\Block\Widget\Context;
use Rsgitech\News\Api\AllnewsRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class GenericButton
{
    protected $context;
   
    protected $allnewsRepository;
    
    public function __construct(
        Context $context,
        AllnewsRepositoryInterface $allnewsRepository
    ) {
        $this->context = $context;
        $this->allnewsRepository = $allnewsRepository;
    }

    public function getNewsId()
    {
        try {
            return $this->allnewsRepository->getById(
                $this->context->getRequest()->getParam('news_id')
            )->getId();
        } catch (NoSuchEntityException $e) {
        }
        return null;
    }

    public function getUrl($route = '', $params = [])
    {
        return $this->context->getUrlBuilder()->getUrl($route, $params);
    }
}
?>

Create BackButton Block

Rsgitech\News\Block\Adminhtml\Allnews\Edit\BackButton.php


<?php

namespace Rsgitech\News\Block\Adminhtml\Allnews\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

/**
 * Class BackButton
 */
class BackButton extends GenericButton implements ButtonProviderInterface
{
    /**
     * @return array
     */
    public function getButtonData()
    {
        return [
            'label' => __('Back'),
            'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()),
            'class' => 'back',
            'sort_order' => 10
        ];
    }

    /**
     * Get URL for back (reset) button
     *
     * @return string
     */
    public function getBackUrl()
    {
        return $this->getUrl('*/*/');
    }
}
?>

Create DeleteButton Block

Rsgitech\News\Block\Adminhtml\Allnews\Edit\DeleteButton.php


<?php

namespace Rsgitech\News\Block\Adminhtml\Allnews\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

/**
 * Class DeleteButton
 */
class DeleteButton extends GenericButton implements ButtonProviderInterface
{
    /**
     * @return array
     */
    public function getButtonData()
    {
        $data = [];
        if ($this->getNewsId()) {
            $data = [
                'label' => __('Delete News'),
                'class' => 'delete',
                'on_click' => 'deleteConfirm(\'' . __(
                    'Are you sure you want to do this?'
                ) . '\', \'' . $this->getDeleteUrl() . '\')',
                'sort_order' => 20,
            ];
        }
        return $data;
    }

    /**
     * @return string
     */
    public function getDeleteUrl()
    {
        return $this->getUrl('*/*/delete', ['news_id' => $this->getNewsId()]);
    }
}
?>

Create ResetButton Block

Rsgitech\News\Block\Adminhtml\Allnews\Edit\ResetButton.php


<?php

namespace Rsgitech\News\Block\Adminhtml\Allnews\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

/**
 * Class ResetButton
 */
class ResetButton implements ButtonProviderInterface
{
    /**
     * @return array
     */
    public function getButtonData()
    {
        return [
            'label' => __('Reset'),
            'class' => 'reset',
            'on_click' => 'location.reload();',
            'sort_order' => 30
        ];
    }
}
?>

Create SaveAndContinueButton Block

Rsgitech\News\Block\Adminhtml\Allnews\Edit\SaveAndContinueButton.php


<?php

namespace Rsgitech\News\Block\Adminhtml\Allnews\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

/**
 * Class SaveAndContinueButton
 */
class SaveAndContinueButton extends GenericButton implements ButtonProviderInterface
{
    /**
     * @return array
     */
    public function getButtonData()
    {
        return [
            'label' => __('Save and Continue Edit'),
            'class' => 'save',
            'data_attribute' => [
                'mage-init' => [
                    'button' => ['event' => 'saveAndContinueEdit'],
                ],
            ],
            'sort_order' => 80,
        ];
    }
}
?>

Create SaveButton Block

Rsgitech\News\Block\Adminhtml\Allnews\Edit\SaveButton.php


<?php

namespace Rsgitech\News\Block\Adminhtml\Allnews\Edit;

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

/**
 * Class SaveButton
 */
class SaveButton extends GenericButton implements ButtonProviderInterface
{
    /**
     * @return array
     */
    public function getButtonData()
    {
        return [
            'label' => __('Save News'),
            'class' => 'save primary',
            'data_attribute' => [
                'mage-init' => ['button' => ['event' => 'save']],
                'form-role' => 'save',
            ],
            'sort_order' => 90,
        ];
    }
}
?>

Create Controller Action NewAction

Rsgitech\News\Controller\Adminhtml\Allnews\NewAction.php

Create new grid item


<?php
namespace Rsgitech\News\Controller\Adminhtml\Allnews;

class NewAction extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Backend\Model\View\Result\Forward
     */
    protected $resultForwardFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
    ) {
        $this->resultForwardFactory = $resultForwardFactory;
        parent::__construct($context);
    }
	
	/**
     * Authorization level
     *
     * @see _isAllowed()
     */
	protected function _isAllowed()
	{
		return $this->_authorization->isAllowed('Rsgitech_News::save');
	}

    /**
     * Forward to edit
     *
     * @return \Magento\Backend\Model\View\Result\Forward
     */
    public function execute()
    {
        /** @var \Magento\Backend\Model\View\Result\Forward $resultForward */
        $resultForward = $this->resultForwardFactory->create();
        return $resultForward->forward('edit');
    }
}
?>

Create Controller Action Save

Rsgitech\News\Controller\Adminhtml\Allnews\Save.php


<?php

namespace Rsgitech\News\Controller\Adminhtml\Allnews;

use Magento\Backend\App\Action;
use Rsgitech\News\Model\Allnews;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Exception\LocalizedException;

class Save extends \Magento\Backend\App\Action
{
    /**
     * @var DataPersistorInterface
     */
    protected $dataPersistor;

    /**
     * @var \Rsgitech\News\Model\AllnewsFactory
     */
    private $allnewsFactory;

    /**
     * @var \Rsgitech\News\Api\AllnewsRepositoryInterface
     */
    private $allnewsRepository;

    /**
     * @param Action\Context $context
     * @param DataPersistorInterface $dataPersistor
     * @param \Rsgitech\News\Model\AllnewsFactory $allnewsFactory
     * @param \Rsgitech\News\Api\AllnewsRepositoryInterface $allnewsRepository
     */
    public function __construct(
        Action\Context $context,
        DataPersistorInterface $dataPersistor,
        \Rsgitech\News\Model\AllnewsFactory $allnewsFactory = null,
        \Rsgitech\News\Api\AllnewsRepositoryInterface $allnewsRepository = null
    ) {
        $this->dataPersistor = $dataPersistor;
        $this->allnewsFactory = $allnewsFactory
            ?: \Magento\Framework\App\ObjectManager::getInstance()->get(\Rsgitech\News\Model\AllnewsFactory::class);
        $this->allnewsRepository = $allnewsRepository
            ?: \Magento\Framework\App\ObjectManager::getInstance()->get(\Rsgitech\News\Api\AllnewsRepositoryInterface::class);
        parent::__construct($context);
    }
	
	/**
     * Authorization level
     *
     * @see _isAllowed()
     */
	protected function _isAllowed()
	{
		return $this->_authorization->isAllowed('Rsgitech_News::save');
	}

    /**
     * Save action
     *
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($data) {
            if (isset($data['status']) && $data['status'] === 'true') {
                $data['status'] = Allnews::STATUS_ENABLED;
            }
            if (empty($data['news_id'])) {
                $data['news_id'] = null;
            }

            /** @var \Rsgitech\News\Model\Allnews $model */
            $model = $this->allnewsFactory->create();

            $id = $this->getRequest()->getParam('news_id');
            if ($id) {
                try {
                    $model = $this->allnewsRepository->getById($id);
                } catch (LocalizedException $e) {
                    $this->messageManager->addErrorMessage(__('This news no longer exists.'));
                    return $resultRedirect->setPath('*/*/');
                }
            }

            $model->setData($data);

            $this->_eventManager->dispatch(
                'news_allnews_prepare_save',
                ['allnews' => $model, 'request' => $this->getRequest()]
            );

            try {
                $this->allnewsRepository->save($model);
                $this->messageManager->addSuccessMessage(__('You saved the news.'));
                $this->dataPersistor->clear('news_allnews');
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['news_id' => $model->getId(), '_current' => true]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addExceptionMessage($e->getPrevious() ?:$e);
            } catch (\Exception $e) {
                $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the news.'));
            }

            $this->dataPersistor->set('news_allnews', $data);
            return $resultRedirect->setPath('*/*/edit', ['news_id' => $this->getRequest()->getParam('news_id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }
}
?>

Create ui component form

Rsgitech\News\view\adminhtml\ui_component\news_allnews_form.xml


<?xml version="1.0" encoding="UTF-8"?>

<form 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_form.allnews_form_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">News Information</item>
        <item name="template" xsi:type="string">templates/form/collapsible</item>
    </argument>
    <settings>
        <buttons>
            <button name="save_and_continue" class="Rsgitech\News\Block\Adminhtml\Allnews\Edit\SaveAndContinueButton"/>
            <button name="save" class="Rsgitech\News\Block\Adminhtml\Allnews\Edit\SaveButton"/>
            <button name="reset" class="Rsgitech\News\Block\Adminhtml\Allnews\Edit\ResetButton"/>
            <button name="delete" class="Rsgitech\News\Block\Adminhtml\Allnews\Edit\DeleteButton"/>
            <button name="back" class="Rsgitech\News\Block\Adminhtml\Allnews\Edit\BackButton"/>
        </buttons>
        <namespace>news_allnews_form</namespace>
        <dataScope>data</dataScope>
        <deps>
            <dep>news_allnews_form.allnews_form_data_source</dep>
        </deps>
    </settings>
    <dataSource name="allnews_form_data_source">
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
            </item>
        </argument>
        <settings>
            <submitUrl path="news/allnews/save"/>
        </settings>
        <dataProvider class="Rsgitech\News\Model\Allnews\DataProvider" name="allnews_form_data_source">
            <settings>
                <requestFieldName>news_id</requestFieldName>
                <primaryFieldName>news_id</primaryFieldName>
            </settings>
        </dataProvider>
    </dataSource>
    <fieldset name="general">
        <settings>
            <label/>
        </settings>
        <field name="news_id" formElement="input">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">allnews</item>
                </item>
            </argument>
            <settings>
                <dataType>text</dataType>
                <visible>false</visible>
                <dataScope>news_id</dataScope>
            </settings>
        </field>
        <field name="status" sortOrder="10" formElement="checkbox">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">allnews</item>
                    <item name="default" xsi:type="number">1</item>
                </item>
            </argument>
            <settings>
                <dataType>boolean</dataType>
                <label translate="true">Enable News</label>
                <dataScope>status</dataScope>
            </settings>
            <formElements>
                <checkbox>
                    <settings>
                        <valueMap>
                            <map name="false" xsi:type="number">0</map>
                            <map name="true" xsi:type="number">1</map>
                        </valueMap>
                        <prefer>toggle</prefer>
                    </settings>
                </checkbox>
            </formElements>
        </field>
        <field name="title" sortOrder="20" formElement="input">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">allnews</item>
                </item>
            </argument>
            <settings>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">true</rule>
                </validation>
                <dataType>text</dataType>
                <label translate="true">News Title</label>
                <dataScope>title</dataScope>
            </settings>
        </field>
    </fieldset>
    <fieldset name="content" sortOrder="10">
        <settings>
            <collapsible>true</collapsible>
            <label translate="true">Content</label>
        </settings>
        <field name="description" formElement="wysiwyg">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">allnews</item>
                </item>
            </argument>
            <settings>
                <additionalClasses>
                    <class name="admin__field-wide">true</class>
                </additionalClasses>
                <label/>
                <dataScope>description</dataScope>
            </settings>
            <formElements>
                <wysiwyg>
                    <settings>
                        <wysiwyg>true</wysiwyg>
                    </settings>
                </wysiwyg>
            </formElements>
        </field>
    </fieldset>
</form>

Create Layout

Rsgitech\News\view\adminhtml\layout\news_allnews_edit.xml

Load uiComponent news_allnews_form in news_allnews_edit.xml file


<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="editor"/>
    <body>
        <referenceContainer name="content">
            <uiComponent name="news_allnews_form"/>
        </referenceContainer>
    </body>
</page>

Then run below commands


php bin/magento setup:upgrade
php bin/magetno setup:static-content:deploy
php bin/magento cache:flush

Complete!!

Download source code: Download

This lesson also available on YouTube
Grid Items Add Grid Item Magento 2 Admin Grid

Please leave comments

11 Comments


hartej singh 4 years ago
DataProvider.php file is missing sir please check. Thanks for this useful tutorial.
Reply
    shivani 2 years ago
    below code is available for DataProvider . . . . . <?php namespace Rsgitech\News\Model\Allnews; use Rsgitech\News\Model\ResourceModel\Allnews\CollectionFactory; use Magento\Framework\App\Request\DataPersistorInterface; /** * Class DataProvider */ class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider { /** * @var \Rsgitech News\Model\ResourceModel\Allnews\Collection */ protected $collection; /** * @var DataPersistorInterface */ protected $dataPersistor; /** * @var array */ protected $loadedData; /** * @param string $name * @param string $primaryFieldName * @param string $requestFieldName * @param CollectionFactory $allnewsCollectionFactory * @param DataPersistorInterface $dataPersistor * @param array $meta * @param array $data */ public function __construct( $name, $primaryFieldName, $requestFieldName, CollectionFactory $allnewsCollectionFactory, DataPersistorInterface $dataPersistor, array $meta = [], array $data = [] ) { $this->collection = $allnewsCollectionFactory->create(); $this->dataPersistor = $dataPersistor; parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data); $this->meta = $this->prepareMeta($this->meta); } /** * Prepares Meta * * @param array $meta * @return array */ public function prepareMeta(array $meta) { return $meta; } /** * Get data * * @return array */ public function getData() { if (isset($this->loadedData)) { return $this->loadedData; } $items = $this->collection->getItems(); /** @var $news \Rsgitech\News\Model\Allnews */ foreach ($items as $news) { $this->loadedData[$news->getId()] = $news->getData(); } $data = $this->dataPersistor->get('news_allnews'); if (!empty($data)) { $news= $this->collection->getNewEmptyItem(); $news->setData($data); $this->loadedData[$news->getId()] = $news->getData(); $this->dataPersistor->clear ('news_allnews'); } return $this->loadedData; } }
    Reply
Sakshi 5 years ago
Hi, I followed your tutorials and tried making my own custom module. Delete and massDelete actions are working alright but Add and Edit actions give internal server error. Let me know if I am missing something.
Reply
    Sikander 1 year ago
    you found anything of this?
    Reply
Drew 5 years ago
Getting 404 on Add News Button Click?
Reply
    Sikander 1 year ago
    Hey Drew, any luck with the error?
    Reply
      Drew 1 year ago
      Yes, figured it out a long time ago. I can't even remember what was causing the error. I've done a lot of Magento 2 development since my post.. thanks for reaching out.
      Reply
        Sikander 1 year ago
        Okay, I am actually learning this. could you mind guiding, what should i look into to resolve this one?
        Reply
          Drew 1 year ago
          Did you download all the code from https://www.truecodex.com/download/magext/ I'd need to reinstall this test extension and test. I don't necessarily follow exactly this when building similar extensions now. if I have time this weekend, I'll try to figure it out.
          Reply
            Sikander 1 year ago
            which approach do you follow exactly now?
            Reply
              Drew 1 year ago
              Did you download the code from that link? Did you try enabling the extension to see if it works? This is still a good approach for admin extensions if you are just starting to learn Magento 2 Dev. There's many different ways to create these backend modules, but you still need to create majority of these files, it can be very repetitive. I tend to create a example build , so I don't have to create all these files over and over again.
              Reply