Hi, everybody! I had a chance to get my hands on the latest magento2 and do a learning project. I decided to create custom module which has admin listing from two tables. In many cases we need to display listing from two tables by using mysql Joins. So, following is the simplest and easiest explanation to do the same.
So, by the end of this series of blog posts you will be able to do the following, with ease:
- Creating a module that is installable via Composer
- Create controllers and understand how the rewrite system works
- How blocks, layouts and template work
- Create models and interact with the database
- Setup an admin interface to create, edit and delete items from the database.
- Setup an admin listing which have joins from two tables
create following files
Ekvi/adminjoins/composer.json
{
“name”: “ekvi/adminjoins”,
“description”: “Module for admin listing by using two tables”,
“require”: {
“php”: “~5.5.0|~5.6.0|~7.0.0”
},
“type”: “magento2-module”,
“version”: “1.0.0”,
“license”: [
“proprietary”
],
“autoload”: {
“files”: [
“registration.php”
],
“psr-4”: {
“Ekvi\\Adminjoins\\”: “”
}
},
“authors”: [
{
“name”: “Ekvi”,
“email”: “info@ekvitech.com”,
“homepage”: “https://ekvitech.com”,
“role”: “Developer”
}
],
“support”: {
“email”: “info@ekvitech.com”
}
}
Ekvi/adminjoins/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
‘Ekvi_Adminjoins’,
__DIR__
);
?>
Ekvi/adminjoins/etc/module.xml
This registers our module, we have no dependencies so we haven’t listed any…
<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd”>
<module name=”Ekvi_Adminjoins” setup_version=”1.0.0″>
</module>
</config>
Ekvi/adminjoins/etc/config.xml
<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:module:Magento_Store:etc/config.xsd”>
<default>
<adminjoins>
<general>
<enabled>1</enabled>
<page_title>Admin Joins</page_title>
<identifier>joins</identifier>
<meta_keywords>ekvi, magento, admin joins, listing, ekvitech</meta_keywords>
<meta_description>Admin Joins Tutorial</meta_description>
<page_heading>Tutorial</page_heading>
<page_subheading>Tutorial</page_subheading>
</general>
<manage_links>
<header_enable>1</header_enable>
<header_text>Tutorial</header_text>
<footer_enable>1</footer_enable>
<footer_text>Tutorial</footer_text>
</manage_links>
<seo>
<url_suffix>.html</url_suffix>
</seo>
</adminjoins>
</default>
</config>
Ekvi/adminjoins/etc/frontend/routes.xml
Frontend router configuration file. id is the identifier which needs to be unique and frontname is going to be the first part of url
<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd”>
<router id=”standard”>
<route id=”adminjoins” frontName=”adminjoins”>
<module name=”Ekvi_Adminjoins” />
</route>
</router>
</config>
Ekvi/adminjoins/Controller/Index/Index.php
This is the controller for our frontend. All the dependencies are mentioned in __construct. Context gives you access to things like: the object manager, the URL model, and more.
<?php
namespace Ekvi\Adminjoins\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context as Context;
class Index extends \Magento\Framework\App\Action\Action
{
public function __construct(
Context $context
) {
parent::__construct($context);
}
public function execute()
{
$this->_view->loadLayout();
$this->_view->getLayout()->initMessages();
$this->_view->renderLayout();
}
}
?>
Ekvi/adminjoins/Setup/InstallSchema.php
This will create tables in database. When you first install your module and run bin/magento setup:upgrade our Setup script will be ran, and a record inserted into a table called setup_module also the two tables ekvi_employee and ekvi_employee_salary will be created.
<?php
namespace Ekvi\Adminjoins\Setup;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class InstallSchema implements InstallSchemaInterface
{
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
SchemaSetupInterface $setup, ModuleContextInterface $context
) {
/**
* Prepare database before module installation
*/
$setup->startSetup();
/**
****** Create table ‘ekvi_employee’ ******
*/
$table = $setup->getConnection()->newTable(
$setup->getTable(‘ekvi_employee’)
)->addColumn(
‘id’,
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[‘identity’ => true, ‘nullable’ => false,’primary’ => true],
‘Employee Id’
)->addColumn(
‘name’,
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
‘200’,
[‘nullable’ => false],
‘Employee Name’
)->addColumn(
’emailid’,
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
‘200’,
[‘nullable’ => false],
‘Employee Emailid’
)->addColumn(
‘salary_id’,
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
‘2’,
[‘nullable’ => false],
‘Current Salary’
);
$setup->getConnection()->createTable($table);
/**
****** Create table ‘ekvi_employee_salary’ ******
*/
$table = $setup->getConnection()->newTable(
$setup->getTable(‘ekvi_employee_salary’)
)->addColumn(
‘salary_id’,
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[‘identity’ => true, ‘nullable’ => false, ‘primary’ => true],
‘Salary ID’
)->addColumn(
‘salary’,
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
‘200’,
[‘nullable’ => false],
‘Salary Group’
);
$setup->getConnection()->createTable($table);
$setup->endSetup();
}
}
?>
Now lets create the Model and ResourceModel which will allow us to intract with our tables in database
Ekvi/adminjoins/Model/Employee.php
<?php
namespace Ekvi\Adminjoins\Model;
use Magento\Framework\Model\AbstractModel;
class Employee extends AbstractModel
{
/**
* Define resource model
*/
protected function _construct()
{
$this->_init(‘Ekvi\Adminjoins\Model\ResourceModel\Employee’);
}
}
?>
Ekvi/adminjoins/Model/ResourceModel/Employee.php
mention your table name and primary key in constructor
<?php
namespace Ekvi\Adminjoins\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Employee extends AbstractDb
{
/**
* Define main table
*/
protected function _construct()
{
$this->_init(‘ekvi_employee’, ‘id’);
}
}
?>
Ekvi/adminjoins/Model/ResourceModel/Employee/Collection.php
This will return the collection from the main table. _initSelect is the function which will create join with table ekvi_employee_salary.
<?php
namespace Ekvi\Adminjoins\Model\ResourceModel\Employee;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected $_idFieldName = ‘id’;
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,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
\Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
) {
$this->_init(
‘Ekvi\Adminjoins\Model\Employee’,
‘Ekvi\Adminjoins\Model\ResourceModel\Employee’
);
parent::__construct(
$entityFactory, $logger, $fetchStrategy, $eventManager, $connection,
$resource
);
$this->storeManager = $storeManager;
}
protected function _initSelect()
{
parent::_initSelect();
$this->getSelect()->joinLeft(
[‘secondTable’ => $this->getTable(‘ekvi_employee_salary’)],
‘main_table.salary_id = secondTable.salary_id’,
[‘secondTable.salary_id as salaryId’,’salary’]
);
}
}
?>
Ekvi/adminjoins/Model/ResourceModel/Employee/Grid/Collection.php
This is usually mentioned as a virtualtype and physically not created, But here we need to create this file as we need join with other table for this model.
and will pass some elements from di.xml (will create further)
<?php
namespace Ekvi\Adminjoins\Model\ResourceModel\Employee\Grid;
use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Search\AggregationInterface;
use Ekvi\Adminjoins\Model\ResourceModel\Employee\Collection as EmployeeCollection;
/**
* Class Collection
* Collection for displaying grid of shops
*/
class Collection extends EmployeeCollection implements SearchResultInterface
{
/**
* Resource initialization
* @return $this
*/
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,
\Magento\Store\Model\StoreManagerInterface $storeManager,
$mainTable,
$eventPrefix,
$eventObject,
$resourceModel,
$model = ‘Magento\Framework\View\Element\UiComponent\DataProvider\Document’,
$connection = null,
\Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
) {
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$storeManager,
$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 Model for table ekvi_employee_salary
Ekvi/adminjoins/Model/Salary.php
<?php
namespace Ekvi\Adminjoins\Model;
use Magento\Framework\Model\AbstractModel;
class Salary extends AbstractModel
{
/**
* Define resource model
*/
protected function _construct()
{
$this->_init(‘Ekvi\Adminjoins\Model\ResourceModel\Salary’);
}
}
?>
Ekvi/adminjoins/Model/ResourceModel/Salary.php
<?php
namespace Ekvi\Adminjoins\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Salary extends AbstractDb
{
/**
* Define main table
*/
protected function _construct()
{
$this->_init(‘ekvi_employee_salary’, ‘salary_id’);
}
}
?>
Ekvi/adminjoins/Model/ResourceModel/Salary/Collection.php
<?php
namespace Ekvi\Adminjoins\Model\ResourceModel\Salary;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected $_idFieldName = ‘salary_id’;
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,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
\Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
) {
$this->_init(
‘Ekvi\Adminjoins\Model\Salary’,
‘Ekvi\Adminjoins\Model\ResourceModel\Salary’
);
parent::__construct(
$entityFactory, $logger, $fetchStrategy, $eventManager, $connection,
$resource
);
$this->storeManager = $storeManager;
}
}
?>
Now Next step is Creation of Block
Ekvi/adminjoins/Block/Listing.php
_prepareLayout will create page title, description and metakeywords, These are already mentioned in our config.xml(created above) and we get these values with the help of Helper/Data.php (will create in next step)
<?php
namespace Ekvi\Adminjoins\Block;
class Listing extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Ekvi\Adminjoins\Helper\Data $moduleHelper,
array $data = []
) {
parent::__construct($context, $data);
$this->_moduleHelper = $moduleHelper;
}
protected function _prepareLayout()
{
$this->pageConfig->getTitle()->set($this->_moduleHelper->getAdminjoinsTitle());
$this->pageConfig->setDescription(
$this->escapeHtml($this->stripTags($this->_moduleHelper->getDescription()))
);
$this->pageConfig->setKeywords($this->_moduleHelper->getMetaKeywords());
return parent::_prepareLayout();
}
}
?>
Ekvi/adminjoins/Helper/Data.php
Here comes our Helper file.
<?php
namespace Ekvi\Adminjoins\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\ScopeInterface;
class Data extends AbstractHelper
{
const XML_ADMINJOINS_PAGE_TITLE = ‘adminjoins/general/page_title’;
const XML_ADMINJOINS_PAGE_METADESCRIPTION = ‘adminjoins/general/meta_description’;
const XML_ADMINJOINS_PAGE_METAKEYWORD = ‘adminjoins/general/meta_keywords’;
protected $_scopeConfig;
public function __construct(
Context $context,
\Magento\Backend\Model\UrlInterface $backendUrl,
ScopeConfigInterface $scopeConfig
) {
parent::__construct($context);
$this->_backendUrl = $backendUrl;
$this->_scopeConfig = $scopeConfig;
}
public function getAdminjoinsTitle()
{
return $this->scopeConfig->getValue(
self::XML_ADMINJOINS_PAGE_TITLE, ScopeInterface::SCOPE_STORE
);
}
public function getDescription()
{
return $this->scopeConfig->getValue(
self::XML_ADMINJOINS_PAGE_METADESCRIPTION, ScopeInterface::SCOPE_STORE
);
}
public function getMetaKeywords()
{
return $this->scopeConfig->getValue(
self::XML_ADMINJOINS_PAGE_METAKEYWORD, ScopeInterface::SCOPE_STORE
);
}
}
?>
Ekvi/adminjoins/view/frontend/layout/adminjoins_index_index.xml
Here we specify which block and template we want to use and where to display.
<?xml version=”1.0″ encoding=”UTF-8″?>
<page xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” layout=”1column”
xsi:noNamespaceSchemaLocation=”urn:magento:framework:View/Layout/etc/page_configuration.xsd”>
<body>
<referenceContainer name=”content”>
<block class=”Ekvi\Adminjoins\Block\Listing” name=”listing”
template=”listing.phtml”>
</block>
</referenceContainer>
</body>
</page>
Ekvi/adminjoins/view/frontend/templates/listing.phtml
This is the template file for frontend.
<h1 style=”color: #f1703d;”> Welcome to Magento 2</h1>
<?php echo “This is my frontend template”;?>
Now let us move to the Admin Interface. we will use the concept of Ui components. This is actually very interesting concept being used in Magento 2
Ekvi/adminjoins/etc/adminhtml/routes.xml
first we need to register route for admin
<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:App/etc/routes.xsd”>
<router id=”admin”>
<route id=”adminjoins” frontName=”adminjoins”>
<module name=”Ekvi_Adminjoins” before=”Magento_Backend”/>
</route>
</router>
</config>
Ekvi/adminjoins/etc/adminhtml/menu.xml
define where whould our tab appear, we have created it under Content.
<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:module:Magento_Backend:etc/menu.xsd”>
<menu>
<add id=”Ekvi_Adminjoins::content” title=”Ekvi” module=”Ekvi_Adminjoins” sortOrder=”401″ parent=”Magento_Backend::content” resource=”Ekvi_Adminjoins::content”/>
<add id=”Ekvi_Adminjoins::manage_list” title=”Employee List” module=”Ekvi_Adminjoins” sortOrder=”401″ parent=”Ekvi_Adminjoins::content” resource=”Ekvi_Adminjoins::content” action=”adminjoins/employee/index”/>
</menu>
</config>
Ekvi/adminjoins/etc/adminhtml/acl.xml
<?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=”Magento_Backend::content”>
<resource id=”Ekvi_Adminjoins::content” title=”Admin Joins” sortOrder=”10″ >
<resource id=”Ekvi_Adminjoins::manage_list” title=”Manage Listing” sortOrder=”40″>
</resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>
Ekvi/adminjoins/etc/di.xml
Here we are using Employee Model
<?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=”Ekvi\Adminjoins\Api\Data\EmployeeInterface” type=”Ekvi\Adminjoins\Model\Employee” />
<virtualType name=”AdminjoinsGirdFilterPool” type=”Magento\Framework\View\Element\UiComponent\DataProvider\FilterPool”>
<arguments>
<argument name=”appliers” xsi:type=”array”>
<item name=”regular” xsi:type=”object”>Magento\Framework\View\Element\UiComponent\DataProvider\RegularFilter</item>
<item name=”fulltext” xsi:type=”object”>Magento\Framework\View\Element\UiComponent\DataProvider\FulltextFilter</item>
</argument>
</arguments>
</virtualType>
<virtualType name=”EmployeeGridDataProvider” type=”Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider”>
<arguments>
<argument name=”collection” xsi:type=”object” shared=”false”>Ekvi\Adminjoins\Model\ResourceModel\Employee\Collection</argument>
<argument name=”filterPool” xsi:type=”object” shared=”false”>AdminjoinsGirdFilterPool</argument>
</arguments>
</virtualType>
<type name=”Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory”>
<arguments>
<argument name=”collections” xsi:type=”array”>
<item name=”adminjoins_employee_listing_data_source” xsi:type=”string”>Ekvi\Adminjoins\Model\ResourceModel\Employee\Grid\Collection</item>
</argument>
</arguments>
</type>
<type name=”Ekvi\Adminjoins\Model\ResourceModel\Employee\Grid\Collection”>
<arguments>
<argument name=”mainTable” xsi:type=”string”>ekvi_employee</argument>
<argument name=”eventPrefix” xsi:type=”string”>ekvi_adminjoins_grid_collection</argument>
<argument name=”eventObject” xsi:type=”string”>ekvi_grid_collection</argument>
<argument name=”resourceModel” xsi:type=”string”>Ekvi\Adminjoins\Model\ResourceModel\Employee</argument>
</arguments>
</type>
</config>
Ekvi/adminjoins/view/adminhtml/layout/adminjoins_employee_edit.xml
<?xml version=”1.0″?>
<page xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” layout=”admin-2columns-left” xsi:noNamespaceSchemaLocation=”urn:magento:framework:View/Layout/etc/page_configuration.xsd”>
<update handle=”editor”/>
<body>
<referenceContainer name=”content”>
<block class=”Ekvi\Adminjoins\Block\Adminhtml\Employee\Edit” name=”adminjoins_employee_edit”/>
</referenceContainer>
</body>
</page>
Ekvi/adminjoins/view/adminhtml/layout/adminjoins_employee_index.xml
<?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=”adminjoins_employee_listing”/>
</referenceContainer>
</body>
</page>
Ekvi/adminjoins/view/adminhtml/ui_component/adminjoins_employee_listing.xml
This represents the listing in admin interface.
<?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”>adminjoins_employee_listing.adminjoins_employee_listing_data_source</item>
<item name=”deps” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing_data_source</item>
</item>
<item name=”spinner” xsi:type=”string”>adminjoins_employee_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 New Employee</item>
<item name=”class” xsi:type=”string”>primary</item>
<item name=”url” xsi:type=”string”>*/*/new</item>
</item>
</item>
</argument>
<dataSource name=”adminjoins_employee_listing_data_source”>
<argument name=”dataProvider” xsi:type=”configurableObject”>
<argument name=”class” xsi:type=”string”>EmployeeGridDataProvider</argument>
<argument name=”name” xsi:type=”string”>adminjoins_employee_listing_data_source</argument>
<argument name=”primaryFieldName” xsi:type=”string”>id</argument>
<argument name=”requestFieldName” xsi:type=”string”>id</argument>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”update_url” xsi:type=”url” path=”mui/index/render”/>
</item>
</argument>
</argument>
<argument name=”data” xsi:type=”array”>
<item name=”js_config” xsi:type=”array”>
<item name=”component” xsi:type=”string”>Magento_Ui/js/grid/provider</item>
</item>
</argument>
</dataSource>
<container name=”listing_top”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”template” xsi:type=”string”>ui/grid/toolbar</item>
</item>
</argument>
<bookmark name=”bookmarks”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”component” xsi:type=”string”>Magento_Ui/js/grid/controls/bookmarks/bookmarks</item>
<item name=”displayArea” xsi:type=”string”>dataGridActions</item>
<item name=”storageConfig” xsi:type=”array”>
<item name=”saveUrl” xsi:type=”url” path=”mui/bookmark/save”/>
<item name=”deleteUrl” xsi:type=”url” path=”mui/bookmark/delete”/>
<item name=”namespace” xsi:type=”string”>adminjoins_employee_listing</item>
</item>
</item>
</argument>
</bookmark>
<container name=”columns_controls”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”columnsData” xsi:type=”array”>
<item name=”provider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.adminjoins_employee_columns</item>
</item>
<item name=”component” xsi:type=”string”>Magento_Ui/js/grid/controls/columns</item>
<item name=”displayArea” xsi:type=”string”>dataGridActions</item>
</item>
</argument>
</container>
<filters name=”listing_filters”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”columnsProvider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.adminjoins_employee_columns</item>
<item name=”storageConfig” xsi:type=”array”>
<item name=”provider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.listing_top.bookmarks</item>
<item name=”namespace” xsi:type=”string”>current.filters</item>
</item>
<item name=”templates” xsi:type=”array”>
<item name=”filters” xsi:type=”array”>
<item name=”select” xsi:type=”array”>
<item name=”component” xsi:type=”string”>Magento_Ui/js/form/element/ui-select</item>
<item name=”template” xsi:type=”string”>ui/grid/filters/elements/ui-select</item>
</item>
</item>
</item>
<item name=”childDefaults” xsi:type=”array”>
<item name=”provider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.listing_top.listing_filters</item>
<item name=”imports” xsi:type=”array”>
<item name=”visible” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.adminjoins_employee_columns.${ $.index }:visible</item>
</item>
</item>
</item>
</argument>
</filters>
<massaction name=”listing_massaction”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”selectProvider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.adminjoins_employee_columns.ids</item>
<item name=”indexField” xsi:type=”string”>id</item>
</item>
</argument>
<action name=”delete”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”type” xsi:type=”string”>delete</item>
<item name=”label” xsi:type=”string” translate=”true”>Delete</item>
<item name=”url” xsi:type=”url” path=”adminjoins/employee/massDelete”/>
<item name=”confirm” xsi:type=”array”>
<item name=”title” xsi:type=”string” translate=”true”>Delete items</item>
<item name=”message” xsi:type=”string” translate=”true”>Are you sure you wan’t to delete selected items?</item>
</item>
</item>
</argument>
</action>
</massaction>
<paging name=”listing_paging”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”storageConfig” xsi:type=”array”>
<item name=”provider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.listing_top.bookmarks</item>
<item name=”namespace” xsi:type=”string”>current.paging</item>
</item>
<item name=”selectProvider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.adminjoins_employee_columns.ids</item>
<item name=”displayArea” xsi:type=”string”>bottom</item>
<item name=”options” xsi:type=”array”>
<item name=”20″ xsi:type=”array”>
<item name=”value” xsi:type=”number”>20</item>
<item name=”label” xsi:type=”string” translate=”true”>20</item>
</item>
<item name=”30″ xsi:type=”array”>
<item name=”value” xsi:type=”number”>30</item>
<item name=”label” xsi:type=”string” translate=”true”>30</item>
</item>
<item name=”50″ xsi:type=”array”>
<item name=”value” xsi:type=”number”>50</item>
<item name=”label” xsi:type=”string” translate=”true”>50</item>
</item>
<item name=”100″ xsi:type=”array”>
<item name=”value” xsi:type=”number”>100</item>
<item name=”label” xsi:type=”string” translate=”true”>100</item>
</item>
<item name=”200″ xsi:type=”array”>
<item name=”value” xsi:type=”number”>200</item>
<item name=”label” xsi:type=”string” translate=”true”>200</item>
</item>
</item>
</item>
</argument>
</paging>
</container>
<columns name=”adminjoins_employee_columns”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”storageConfig” xsi:type=”array”>
<item name=”provider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.listing_top.bookmarks</item>
<item name=”namespace” xsi:type=”string”>current</item>
</item>
<item name=”childDefaults” xsi:type=”array”>
<item name=”fieldAction” xsi:type=”array”>
<item name=”provider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.adminjoins_employee_columns.actions</item>
<item name=”target” xsi:type=”string”>applyAction</item>
<item name=”params” xsi:type=”array”>
<item name=”0″ xsi:type=”string”>edit</item>
<item name=”1″ xsi:type=”string”>${ $.$data.rowIndex }</item>
</item>
</item>
<item name=”controlVisibility” xsi:type=”boolean”>true</item>
<item name=”storageConfig” xsi:type=”array”>
<item name=”provider” xsi:type=”string”>adminjoins_employee_listing.adminjoins_employee_listing.listing_top.bookmarks</item>
<item name=”root” xsi:type=”string”>columns.${ $.index }</item>
<item name=”namespace” xsi:type=”string”>current.${ $.storageConfig.root}</item>
</item>
</item>
</item>
</argument>
<selectionsColumn name=”ids”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”resizeEnabled” xsi:type=”boolean”>false</item>
<item name=”resizeDefaultWidth” xsi:type=”string”>55</item>
<item name=”indexField” xsi:type=”string”>id</item>
</item>
</argument>
</selectionsColumn>
<column name=”id”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”filter” xsi:type=”string”>textRange</item>
<item name=”sorting” xsi:type=”string”>asc</item>
<item name=”label” xsi:type=”string” translate=”true”>ID</item>
</item>
</argument>
</column>
<column name=”name”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”filter” xsi:type=”string”>text</item>
<item name=”editor” xsi:type=”array”>
<item name=”editorType” xsi:type=”string”>text</item>
<item name=”validation” xsi:type=”array”>
<item name=”required-entry” xsi:type=”boolean”>true</item>
</item>
</item>
<item name=”label” xsi:type=”string” translate=”true”>Employee Name</item>
</item>
</argument>
</column>
<column name=”emailid”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”filter” xsi:type=”string”>text</item>
<item name=”editor” xsi:type=”array”>
<item name=”editorType” xsi:type=”string”>text</item>
<item name=”validation” xsi:type=”array”>
<item name=”required-entry” xsi:type=”boolean”>true</item>
</item>
</item>
<item name=”label” xsi:type=”string” translate=”true”>Email Id</item>
</item>
</argument>
</column>
<column name=”salary”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”filter” xsi:type=”string”>text</item>
<item name=”editor” xsi:type=”array”>
<item name=”editorType” xsi:type=”string”>text</item>
<item name=”validation” xsi:type=”array”>
<item name=”required-entry” xsi:type=”boolean”>true</item>
</item>
</item>
<item name=”label” xsi:type=”string” translate=”true”>Salary Group</item>
</item>
</argument>
</column>
<actionsColumn name=”actions” class=”Ekvi\Adminjoins\Ui\Component\Listing\Column\EmployeeActions”>
<argument name=”data” xsi:type=”array”>
<item name=”config” xsi:type=”array”>
<item name=”resizeEnabled” xsi:type=”boolean”>false</item>
<item name=”resizeDefaultWidth” xsi:type=”string”>107</item>
<item name=”indexField” xsi:type=”string”>id</item>
</item>
</argument>
</actionsColumn>
</columns>
</listing>
Ekvi/adminjoins/Ui/Component/Listing/Column/EmployeeActions.php
<?php
namespace Ekvi\Adminjoins\Ui\Component\Listing\Column;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Framework\UrlInterface;
class EmployeeActions extends Column
{
/** Url path */
const ADMINJOINS_URL_PATH_EDIT = ‘adminjoins/employee/edit’;
const ADMINJOINS_URL_PATH_DELETE = ‘adminjoins/employee/delete’;
/** @var UrlInterface */
protected $urlBuilder;
/**
* @var string
*/
private $editUrl;
/**
* @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::ADMINJOINS_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[‘id’])) {
$item[$name][‘edit’] = [
‘href’ => $this->urlBuilder->getUrl($this->editUrl, [‘id’ => $item[‘id’]]),
‘label’ => __(‘Edit’)
];
$item[$name][‘delete’] = [
‘href’ => $this->urlBuilder->getUrl(self::ADMINJOINS_URL_PATH_DELETE, [‘id’ => $item[‘id’]]),
‘label’ => __(‘Delete’),
‘confirm’ => [
‘title’ => __(‘Delete “${ $.$data.title }”‘),
‘message’ => __(‘Are you sure you wan\’t to delete a “${ $.$data.title }” record?’)
]
];
}
}
}
return $dataSource;
}
}
?>
Lets create admin Block
Ekvi/adminjoins/Block/Adminhtml/Employee/Edit.php
<?php
namespace Ekvi\Adminjoins\Block\Adminhtml\Employee;
class Edit extends \Magento\Backend\Block\Widget\Form\Container
{
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry = null;
/**
* @param \Magento\Backend\Block\Widget\Context $context
* @param \Magento\Framework\Registry $registry
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Widget\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
) {
$this->_coreRegistry = $registry;
parent::__construct($context, $data);
}
/**
* Initialize adminjoins employee edit block
*
* @return void
*/
protected function _construct()
{
$this->_objectId = ‘id’;
$this->_blockGroup = ‘Ekvi_Adminjoins’;
$this->_controller = ‘adminhtml_employee’;
parent::_construct();
if ($this->_isAllowedAction(‘Ekvi_Adminjoins::save’)) {
$this->buttonList->update(‘save’, ‘label’, __(‘Save Employee’));
$this->buttonList->add(
‘saveandcontinue’,
[
‘label’ => __(‘Save and Continue Edit’),
‘class’ => ‘save’,
‘data_attribute’ => [
‘mage-init’ => [
‘button’ => [‘event’ => ‘saveAndContinueEdit’, ‘target’ => ‘#edit_form’],
],
]
],
-100
);
} else {
$this->buttonList->remove(‘save’);
}
if ($this->_isAllowedAction(‘Ekvi_Adminjoins::employee_delete’)) {
$this->buttonList->update(‘delete’, ‘label’, __(‘Delete Employee’));
} else {
$this->buttonList->remove(‘delete’);
}
}
/**
* Retrieve text for header element depending on loaded employee
*
* @return \Magento\Framework\Phrase
*/
public function getHeaderText()
{
if ($this->_coreRegistry->registry(‘adminjoins_employee’)->getId()) {
return __(“Edit Employee ‘%1′”, $this->escapeHtml($this->_coreRegistry->registry(‘adminjoins_employee’)->getTitle()));
} else {
return __(‘New Employee’);
}
}
/**
* Check permission for passed action
*
* @param string $resourceId
* @return bool
*/
protected function _isAllowedAction($resourceId)
{
return $this->_authorization->isAllowed($resourceId);
}
/**
* Getter of url for “Save and Continue” button
* tab_id will be replaced by desired by JS later
*
* @return string
*/
protected function _getSaveAndContinueUrl()
{
return $this->getUrl(‘adminjoins/*/save’, [‘_current’ => true, ‘back’ => ‘edit’, ‘active_tab’ => ”]);
}
}
?>
Ekvi/adminjoins/Block/Adminhtml/Employee/Edit/Form.php
This will create form for Add New Employee.
<?php
namespace Ekvi\Adminjoins\Block\Adminhtml\Employee\Edit;
use Ekvi\Adminjoins\Model\EmployeeFactory;
use Ekvi\Adminjoins\Model\SalaryFactory;
use Magento\Cms\Model\Wysiwyg\Config;
/**
* Adminhtml employee edit form
*/
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
/**
* @var \Magento\Store\Model\System\Store
*/
protected $_systemStore;
protected $_modelSection;
protected $_wysiwygConfig;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Data\FormFactory $formFactory
* @param \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig
* @param \Magento\Store\Model\System\Store $systemStore
* @param array $data
*/
protected $_countryFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
SalaryFactory $modelSalary,
Config $wysiwygConfig,
EmployeeFactory $modelEmployee,
array $data = []
) {
$this->_systemStore = $systemStore;
$this->_modelSalary = $modelSalary;
$this->_modelEmployee = $modelEmployee;
$this->_wysiwygConfig = $wysiwygConfig;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* Init form
*
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->setId(’employee_form’);
$this->setTitle(__(‘Employee Information’));
}
/**
* Prepare form
*
* @return $this
*/
protected function _prepareForm()
{
/** @var \Ekvi\Adminjoins\Model\Employee $model */
$model = $this->_coreRegistry->registry(‘adminjoins_employee’);
/*Salary data*/
$salaryData=$this->_modelSalary->create()->getCollection()->getData();
$options=array();
foreach($salaryData as $val){
$options [$val[‘salary_id’]]= $val[‘salary’];
}
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[‘data’ => [‘id’ => ‘edit_form’, ‘action’ => $this->getData(‘action’), ‘method’ => ‘post’]]
);
$form->setHtmlIdPrefix(‘post_’);
$fieldset = $form->addFieldset(
‘base_fieldset’,
[‘legend’ => __(‘General Information’), ‘class’ => ‘fieldset-wide’]
);
if ($model->getId()) {
$fieldset->addField(‘id’, ‘hidden’, [‘name’ => ‘id’]);
}
$fieldset->addField(
‘name’,
‘text’,
[‘name’ => ‘name’, ‘label’ => __(‘Employee Name’), ‘title’ => __(‘Employee Name’), ‘required’ => true]
);
$fieldset->addField(
’emailid’,
‘text’,
[‘name’ => ’emailid’, ‘label’ => __(‘Employee Email’), ‘title’ => __(‘Employee Email’), ‘required’ => true,’class’ =>’validate-email’,
‘note’ => ‘Please enter a valid email address. For example johndoe@domain.com.’]
);
$fieldset->addField(
‘salary_id’,
‘select’,
[
‘name’ => ‘salary_id’,
‘label’ => __(‘Salary’),
‘title’ => __(‘Salary’),
‘required’ => true,
‘options’ => $options
]
);
$data=$model->getData();
$form->setValues($data);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
?>
Ekvi/adminjoins/Controller/Adminhtml/Employee/Index.php
<?php
namespace Ekvi\Adminjoins\Controller\Adminhtml\Employee;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class Index extends \Magento\Backend\App\Action
{
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @param Context $context
* @param PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
PageFactory $resultPageFactory
) {
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
/**
* Index action
*
* @return \Magento\Backend\Model\View\Result\Page
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->setActiveMenu(‘Magento_Backend::content_elements’);
$resultPage->getConfig()->getTitle()->prepend(__(‘Employees’));
return $resultPage;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed(‘Ekvi_Adminjoins::employee’);
}
}
?>
Ekvi/adminjoins/Controller/Adminhtml/Employee/Save.php
To save new employee in database
<?php
namespace Ekvi\Adminjoins\Controller\Adminhtml\Employee;
use Magento\Backend\App\Action;
use Magento\TestFramework\ErrorLog\Logger;
class Save extends \Magento\Backend\App\Action
{
/**
* @param Action\Context $context
*/
public function __construct(Action\Context $context)
{
parent::__construct($context);
}
/**
* {@inheritdoc}
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(‘Ekvi_Adminjoins::save’);
}
/**
* Save action
*
* @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) {
/** @var \Ekvi\Adminjoins\Model\Employee $model */
$model = $this->_objectManager->create(‘Ekvi\Adminjoins\Model\Employee’);
$id = $this->getRequest()->getParam(‘id’);
if ($id) {
$model->load($id);
}
$model->setData($data);
$this->_eventManager->dispatch(
‘adminjoins_employee_prepare_save’,
[’employee’ => $model, ‘request’ => $this->getRequest()]
);
try {
$model->save();
$this->messageManager->addSuccess(__(‘You saved this employee.’));
$this->_objectManager->get(‘Magento\Backend\Model\Session’)->setFormData(false);
if ($this->getRequest()->getParam(‘back’)) {
return $resultRedirect->setPath(‘*/*/edit’, [‘id’ => $model->getId(), ‘_current’ => true]);
}
return $resultRedirect->setPath(‘*/*/’);
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\RuntimeException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addException($e, __(‘Something went wrong while saving the employee.’));
}
$this->_getSession()->setFormData($data);
return $resultRedirect->setPath(‘*/*/edit’, [‘id’ => $this->getRequest()->getParam(‘id’)]);
}
return $resultRedirect->setPath(‘*/*/’);
}
}
?>
Ekvi/adminjoins/Controller/Adminhtml/Employee/NewAction.php
<?php
namespace Ekvi\Adminjoins\Controller\Adminhtml\Employee;
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);
}
/**
* {@inheritdoc}
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(‘Ekvi_Adminjoins::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’);
}
}
?>
Ekvi/adminjoins/Controller/Adminhtml/Employee/Edit.php
<?php
namespace Ekvi\Adminjoins\Controller\Adminhtml\Employee;
use Magento\Backend\App\Action;
class Edit extends \Magento\Backend\App\Action
{
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry = null;
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
/**
* @param Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
* @param \Magento\Framework\Registry $registry
*/
public function __construct(
Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Framework\Registry $registry
) {
$this->resultPageFactory = $resultPageFactory;
$this->_coreRegistry = $registry;
parent::__construct($context);
}
/**
* {@inheritdoc}
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(‘Ekvi_Adminjoins::save’);
}
/**
* Init actions
*
* @return \Magento\Backend\Model\View\Result\Page
*/
protected function _initAction()
{
// load layout, set active menu and breadcrumbs
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->setActiveMenu(‘Magento_Backend::content_elements’);
return $resultPage;
}
/**
* Edit Adminjoins employee
*
* @return \Magento\Backend\Model\View\Result\Page|\Magento\Backend\Model\View\Result\Redirect
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function execute()
{
$id = $this->getRequest()->getParam(‘id’);
$model = $this->_objectManager->create(‘Ekvi\Adminjoins\Model\Employee’);
if ($id) {
$model->load($id);
if (!$model->getId()) {
$this->messageManager->addError(__(‘This employee no longer exists.’));
/** \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath(‘*/*/’);
}
}
$data = $this->_objectManager->get(‘Magento\Backend\Model\Session’)->getFormData(true);
if (!empty($data)) {
$model->setData($data);
}
$this->_coreRegistry->register(‘adminjoins_employee’, $model);
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->_initAction();
$resultPage->addBreadcrumb(
$id ? __(‘Edit Employee’) : __(‘New Employee’),
$id ? __(‘Edit Employee’) : __(‘New Employee’)
);
$resultPage->getConfig()->getTitle()->prepend(__(‘Employee’));
$resultPage->getConfig()->getTitle()
->prepend($model->getId() ? $model->getTitle() : __(‘New Employee’));
return $resultPage;
}
}
?>
Ekvi/adminjoins/Controller/Adminhtml/Employee/Delete.php
This is used for single delete
<?php
namespace Ekvi\Adminjoins\Controller\Adminhtml\Employee;
use Magento\Backend\App\Action;
use Magento\TestFramework\ErrorLog\Logger;
class Delete extends \Magento\Backend\App\Action
{
/**
* {@inheritdoc}
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(‘Ekvi_Adminjoins::delete’);
}
/**
* Delete action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$id = $this->getRequest()->getParam(‘id’);
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if ($id) {
try {
$model = $this->_objectManager->create(‘Ekvi\Adminjoins\Model\Employee’);
$model->load($id);
$model->delete();
$this->messageManager->addSuccess(__(‘The employee has been deleted.’));
return $resultRedirect->setPath(‘*/*/’);
} catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
return $resultRedirect->setPath(‘*/*/edit’, [‘id’ => $id]);
}
}
$this->messageManager->addError(__(‘We can\’t find a employee to delete.’));
return $resultRedirect->setPath(‘*/*/’);
}
}
?>
Ekvi/adminjoins/Controller/Adminhtml/Employee/MassDelete.php
<?php
namespace Ekvi\Adminjoins\Controller\Adminhtml\Employee;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use Ekvi\Adminjoins\Model\ResourceModel\Employee\CollectionFactory;
use Magento\Framework\Controller\ResultFactory;
/**
* Class MassDisable
*/
class MassDelete extends \Magento\Backend\App\Action
{
/**
* @var Filter
*/
protected $filter;
/**
* @var CollectionFactory
*/
protected $collectionFactory;
/**
* @param Context $context
* @param Filter $filter
* @param CollectionFactory $collectionFactory
*/
public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory)
{
$this->filter = $filter;
$this->collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Execute action
*
* @return \Magento\Backend\Model\View\Result\Redirect
* @throws \Magento\Framework\Exception\LocalizedException|\Exception
*/
public function execute()
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$collectionSize = $collection->getSize();
foreach ($collection as $item) {
$item->delete();
}
$this->messageManager->addSuccess(__(‘A total of %1 record(s) have been deleted.’, $collectionSize));
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath(‘*/*/’);
}
}
?>
We have created all the required files, Now we just need setup:upgrade and cache:flush command to install our module, and then you can view the two tables created in database.