:::: MENU ::::

Magento 2 create product programmatically

Today we discussed how in Magento 2 create product programmatically. This tutorial includes the process of creating a simple product, set image to product and set quantity to product. So lets start with creating a simple product. We can do this in two ways- one is creating product with factory method and other is creating product with object manager.

Create Product with Factory Method

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function createProduct()
    {
       
        $_product = $this->_productloader->create();
        $_product->setName('First Test Product');
        $_product->setTypeId('simple');
        $_product->setAttributeSetId(4);
        $_product->setSku('test-SKU');
        $_product->setWebsiteIds(array(1));
        $_product->setVisibility(4);
        $_product->setPrice(array(1));
        $_product->setImage('/simpeproduct/test.jpg');
        $_product->setSmallImage('/simpeproduct/test.jpg');
        $_product->setThumbnail('/simpeproduct/test.jpg');
        $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 1000 //qty
            )
        );

        $_product->save();
        echo $_product->getId();
    }

Update Product with factory method

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function updateProduct()
    {
       
        $_product = $this->_productloader->create()->load(2047);
        $_product->setName('First Test Product Updated');
        $_product->save();
    }

Create Product with Object manager

 <?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $_product = $objectManager->create('Magento\Catalog\Model\Product');
    $_product->setName('First Test Product');
    $_product->setTypeId('simple');
    $_product->setAttributeSetId(4);
    $_product->setSku('test-SKU');
    $_product->setWebsiteIds(array(1));
    $_product->setVisibility(4);
    $_product->setPrice(array(1));
    $_product->setImage('/simpeproduct/test.jpg');
    $_product->setSmallImage('/simpeproduct/test.jpg');
    $_product->setThumbnail('/simpeproduct/test.jpg');
    $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 1000 //qty
            )
        );

$_product->save();
echo $_product->getId();

Update Product with Object manager

Now our custom product is created. Now we will update product. So doing with following example just.

            $_product = $objectManager->create('Magento\Catalog\Model\Product')->load(2047);
    $_product->setName('First Test Product Updated');
    $_product->save(); ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: April 19, 2018


Magento 2 use custom query

Today we will discuss how in Magento 2 custom query works. Sometime magento 2 model is not enough to get data from database as per our requirements. So to fulfill this requirement we use custom query. In this example we will use select custom query, custom delete query, custom insert query and custom update query. So let’s start with example.

Get connection

First of all we will establish a connection to execute the query.

 $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\ResourceConnection');          
        $connection= $this->_resources->getConnection();

Insert Query

It is simple to use insert query just set the values for columns. Use the inset method.

$array=array(‘column1’=>'column1','column2'=>'column2');

$connection->insert($this->_resources->getTableName(test_table), $array);

Select Query

Selecting table data in custom query you can use following code.

$select = $connection->select()->from(['o' =>  $this->_resources->getTableName(test_table)]);
$result = $connection->fetchAll($select);

       foreach ($result as $data) {
           echo $data['id'];
            }

Update Query

Updating table data in custom query you can use following code.

$id = 1;
 $sql = "Update " . $this->_resources->getTableName('test_table') . " Set `title` ='test title' where `id` = ".$id;
     $connection->query($sql);

Delete Query

To delete table data in custom query you can use following code.

$id = 1;
$condition = $this->getConnection()->quoteInto('id = ?', $id);
            $this->getConnection()->delete($this->getTable('test_table'), $condition);

Join Table

To join table in custom query you can use following code.

        $select = $connection->select()->from(['o' =>  $this->_resources->getTableName('test_table')])->joinleft(
        ['test_table1' => $this->_resources->getTableName('test_table1')],
        'o.id = test_table1.id',
        ['column1','column2']
    );
Author: Qaisar Satti
Category: Magento 2
Last Modified: April 19, 2018


Magento 2 reset admin password

Today we discuss how in Magento 2 reset admin password. This topic include how to reset admin password with sql query, reset password through command line interface (cli). Sometime you forgot the admin password so today we discuss how to reset your admin password. There are two ways to do that. First go to database and reset your with sql query and second create new user from command line and then login and reset the password from admin panel.

Reset with Query

Change test123 to your required password.

UPDATE `admin_user` SET `password` = CONCAT(SHA2('xxxxxxxxtest123', 256), ':xxxxxxxx:1') WHERE `username`= 'admin'

Reset From Cli

Create new user and login to admin panel and change you old user password.

<path_to_magento> php bin/magento admin:user:create --admin-user="admin" --admin-password="123123q" --admin-email="[email protected]" --admin-firstname="Admin" --admin-lastname="Admin"
Author: Qaisar Satti
Category: Magento 2
Last Modified: April 4, 2018


Magento 2 Render WYSIWYG content

Today we discuss how in Magento 2 Render WYSIWYG content. This topic will cover how to render wysiwyg editor content.There are two ways to render the WYSIWYG content. First Zend_Filter_Interface and second Using the \Magento\Cms\Model\Template\FilterProvider.

Using Zend Interface

namespace QaisarSatti\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $contentProcessor;
public function __construct(
    \Zend_Filter_Interface $templateProcessor,
) {
 
    $this->contentProcessor = $contentProcessor;
}
public function processContent($content)
{
    return $this->contentProcessor->filter($content);
}
}

Now Add block reference in di.xml

<type name="QaisarSatti\HelloWorld\Block\HelloWorld">
    <arguments>
        <argument name="contentProcessor" xsi:type="object">Magento\Widget\Model\Template\Filter</argument>
    </arguments>
</type>

Now call method from phtml

<?php echo $block->processContent($content);?>

Using CMS Model

namespace QaisarSatti\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $contentProcessor;
public function __construct(
    \Magento\Cms\Model\Template\FilterProvider $contentProcessor,
) {
 
    $this->contentProcessor = $contentProcessor;
}
public function processContent($content)
{
    return $this->contentProcessor->getPageFilter()->filter($content);
}
}

Now call method from phtml

<?php echo $block->processContent($content);?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: April 4, 2018


Magento 2 add remove footer link

Today we talk about how in magento 2 add remove footer link. This tutorial will include how to add footer link, how to remove footer link and how to add custom link in footer. So first we listed all current link that are available in footer.

Footer Links

Here is all available footer link.

Title Name
Privacy and Cookie Policy privacy-policy-link
Search Terms search-term-popular-link
Contact Us contact-us-link
Advanced Search catalog-search-advanced-link
Orders and Returns sales-guest-form-link

Remove Footer link

Now we will remove a link from footer links. For example we want to remove Privacy and Cookie Policy link from footer. For that we will use his code privacy-policy-link. Just simple use remove block code.

<?xml version="1.0"?>
<!--/**
   * Simple Hello World Module
   *
   * @category    QaisarSatti
   * @package     QaisarSatti_HelloWorld
   * @author      Muhammad Qaisar Satti
   * @Email       [email protected]
   *
   */ -->
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="privacy-policy-link" remove="true"/>
        </body>
    </page>

Same example go for other links too.

Add Footer link

Now we will add the custom link in footer links. For example you want to add footer link title Hello World and there must be unique name helloworld.

<?xml version="1.0"?>
<!--/**
    * Simple Hello World Module
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
    */ -->
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="footer_links">
                <block class="Magento\Framework\View\Element\Html\Link\Current" name="helloworld">
                    <arguments>
                        <argument name="label" xsi:type="string">Hello World</argument>
                        <argument name="path" xsi:type="string">helloworld</argument>
                    </arguments>
                </block>
            </referenceBlock>
        </body>
    </page>
Author: Qaisar Satti
Category: Magento 2
Last Modified: March 8, 2018


Magento 2 create basic module frontend part 4

As we finished with the basic module structure and admin part we move to Magento 2 create basic module frontend .Now this tutorial will be cover the create frontend router, create layout file, create frontend controller, create frontend block, add custom pagination. Now we start with frontend.

Create frontend router

Create routes.xml in following directory

QaisarSatti\HelloWorld\etc\frontend\

<?xml version="1.0"?>
<!--
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */
-->
     <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
        <router id="standard">
            <route id="helloworld" frontName="helloworld">
                <module name="QaisarSatti_HelloWorld" />
            </route>
        </router>
    </config>

Create frontend controller

Create Index.php in following directory

QaisarSatti\HelloWorld\Controller\Index\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action

{

    public function execute()
    {  
       
        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }

}

Create layout file

Create helloworld_index_index.xml in following directory

QaisarSatti\HelloWorld\etc\frontend\

<?xml version="1.0"?>
<!--
/**
* Hello World
   *
   * @category    QaisarSatti
   * @package     QaisarSatti_HelloWorld
   * @author      Muhammad Qaisar Satti
   * @Email       [email protected]
   *
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="content">
                <block class="QaisarSatti\HelloWorld\Block\HelloWorld" name="HellosWorld" template="QaisarSatti_HelloWorld::HelloWorld.phtml"></block>
            </referenceContainer>
        </body>
    </page>

Create frontend block

Create HelloWorld.php in following directory

QaisarSatti\HelloWorld\Block\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */


namespace QaisarSatti\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{
      protected $_coreRegistry = null;
    protected $_collectionFactory;
    protected $_productsFactory;
    protected $_helloworldFactory;
   public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \QaisarSatti\HelloWorld\Model\ResourceModel\HelloWorld\CollectionFactory $helloworldFactory,
       array $data = []
   ) {
 
       $this->_coreRegistry = $registry;
       $this->_helloworldFactory = $helloworldFactory;
       parent::__construct($context, $data);
   }
   public function getHelloCollection()
        {
          $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
           //get values of current limit
          $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 5;

          $helloCollection = $this->_helloworldFactory->create();
          $helloCollection->setPageSize($pageSize);
          $helloCollection->setCurPage($page);
          return $helloCollection;
        }
   public function _prepareLayout()
   {
   
       parent::_prepareLayout();
       $this->pageConfig->getTitle()->set(__('Sample Post'));

       if ($this->getHelloCollection()) {
            $pager = $this->getLayout()->createBlock('Magento\Theme\Block\Html\Pager','qaisarsatti.blog.pager')->setAvailableLimit(array(5=>5,10=>10,15=>15,20=>20));
            $pager->setShowPerPage(true);
            $pager->setCollection($this->getHelloCollection());
            $this->setChild('pager', $pager);
            $this->getHelloCollection()->load();
        }
        return $this;
   }
   public function getPagerHtml(){
        return $this->getChildHtml('pager');
    }


}

Create frontend phtml

Create HelloWorld.phtml in following directory

QaisarSatti\HelloWorld\view\frontend\templates\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

$blogCollection = $block->getHelloCollection();
foreach ($blogCollection as $blog) {

    echo $blog->getTitle().'<br />';
    echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$blog->getContent().'<br />';
}

 if ($block->getPagerHtml()): ?>
<div class="order-products-toolbar toolbar bottom">
<?php echo $block->getPagerHtml(); ?>
</div>
<?php endif ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: February 9, 2018


Magento 2 create basic module admin form part 3

As we completed the admin grid part now we move to part Magento 2 create basic module admin form. In this tutorial include admin new ui component form , admin edit ui component form , form data provider,edit form delete button and add different button to form. Now move on creating the ui component form.

Add New Form controller

Now we create controller for adding the new record. This controller just forwarding to edit controller. Create controller for NewAction.php in following directory

QaisarSatti\HelloWorld\Controller\Adminhtml\Index\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Controller\Adminhtml\Index;

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('QaisarSatti_HelloWorld::helloworld1');
    }

    /**
     * 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');
    }
}

Edit Form

Edit form is based on three parts edit controller, edit layout, and edit ui component. So we go through one by one.

Edit Form controller

Now we create controller for adding the new record. This controller just forwarding to edit controller. Create controller for Edit.php in following directory

QaisarSatti\HelloWorld\Controller\Adminhtml\Index\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Controller\Adminhtml\Index;

class Edit extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */

    protected $resultPageFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Framework\Registry $coreRegistry
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Registry $coreRegistry,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context, $coreRegistry);
    }

    /**
     * Index action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */

    public function execute()
    {

        $resultPage = $this->resultPageFactory->create();
        $this->initPage($resultPage)->getConfig()->getTitle()->prepend(__('Manage Post'));
        return $resultPage;
    }
    protected function initPage($resultPage)
    {
         $resultPage->setActiveMenu('QaisarSatti_HelloWorld::helloworld1')
             ->addBreadcrumb(__('Manage Post'), __('Manage Post'))
             ->addBreadcrumb(__('Manage Post'), __('Manage Post'));

         return $resultPage;
    }

    /**
     * Check the permission to run it
     *
     * @return boolean
     */

    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('QaisarSatti_HelloWorld::helloworld1');
    }
}

Edit Form layout

Now we create layout file for edit. This helloworld_index_edit.xml file combine the ui component with edit controller. Create controller for helloworld_index_edit.xml in following directory

QaisarSatti\HelloWorld\view\adminhtml\layout\

<?xml version="1.0"?>
<!--
   /**
   * Hello World
   *
   * @category    QaisarSatti
   * @package     QaisarSatti_HelloWorld
   * @author      Muhammad Qaisar Satti
   * @Email       [email protected]
   *
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <uiComponent name="helloworld_edit"/>
        </referenceContainer>
     
    </body>
</page>

Data Provider for Edit Form

Now create the data provider for admin form. Create DataProvider.php in following directory

QaisarSatti\HelloWorld\Model\HelloWorld\

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace QaisarSatti\HelloWorld\Model\HelloWorld;

use QaisarSatti\HelloWorld\Model\ResourceModel\HelloWorld\CollectionFactory;
use Magento\Framework\App\Request\DataPersistorInterface;

/**
 * Class DataProvider
 */

class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{
    /**
     * @var \Magento\Cms\Model\ResourceModel\Block\Collection
     */

    protected $collection;

    /**
     * @var DataPersistorInterface
     */

    protected $dataPersistor;

    /**
     * @var array
     */

    protected $loadedData;

    /**
     * Constructor
     *
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param CollectionFactory $blockCollectionFactory
     * @param DataPersistorInterface $dataPersistor
     * @param array $meta
     * @param array $data
     */

    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        CollectionFactory $helloworldCollectionFactory,
        DataPersistorInterface $dataPersistor,
        array $meta = [],
        array $data = []
    ) {
        $this->collection = $helloworldCollectionFactory->create();
        $this->dataPersistor = $dataPersistor;
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
    }

    /**
     * Get data
     *
     * @return array
     */

    public function getData()
    {
        if (isset($this->loadedData)) {
            return $this->loadedData;
        }
        $items = $this->collection->getItems();
        /** @var \Magento\Cms\Model\Block $block */
        foreach ($items as $block) {
            $this->loadedData[$block->getId()] = $block->getData();
        }

        $data = $this->dataPersistor->get('helloworld');
        if (!empty($data)) {
            $block = $this->collection->getNewEmptyItem();
            $block->setData($data);
            $this->loadedData[$block->getId()] = $block->getData();
            $this->dataPersistor->clear('helloworld');
        }

        return $this->loadedData;
    }
}

Edit Form Generic Button

Create GenericButton.php in following directory

QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit;

use Magento\Backend\Block\Widget\Context;
use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Class GenericButton
 */

class GenericButton
{
    /**
     * @var Context
     */

    protected $context;

    /**
     * @var BlockRepositoryInterface
     */


    /**
     * @param Context $context
     */

    public function __construct(
        Context $context
    ) {
        $this->context = $context;
    }

    /**
     * Return Post ID
     *
     * @return int|null
     */

    public function getBlockId()
    {
        try {
            return $this->context->getRequest()->getParam('post_id');

        } catch (NoSuchEntityException $e) {
        }
        return null;
    }

    /**
     * Generate url by route and parameters
     *
     * @param   string $route
     * @param   array $params
     * @return  string
     */

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

Edit Form Back Button

Create BackButton.php in following directory

QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\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('*/*/');
    }
}

Edit Form Delete Button

Create DeleteButton.php in following directory

QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit;

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

/**
 * Class DeleteButton
 */

class DeleteButton extends GenericButton implements ButtonProviderInterface
{

    /**
     * @return array
     */

    public function getButtonData()
    {
        $data = [];
        return $data;
        if ($this->getId()) {
            $data = [
                'label' => __('Delete Block'),
                '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', ['id' => $this->getId()]);
    }
}

Edit Form Reset Button

Create ResetButton.php in following directory

QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\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
        ];
    }
}

Edit Form SaveAndContinue Button

Create SaveAndContinueButton.php in following directory

QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\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,
        ];
    }
}

Edit Form Save Button

Create SaveButton.php in following directory

QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit;

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

/**
 * Class SaveButton
 * @package Magento\Customer\Block\Adminhtml\Edit
 */

class SaveButton extends GenericButton implements ButtonProviderInterface
{
    /**
     * @return array
     */

    public function getButtonData()
    {
        return [
            'label' => __('Save Post'),
            'class' => 'save primary',
            'data_attribute' => [
                'mage-init' => ['button' => ['event' => 'save']],
                'form-role' => 'save',
            ],
            'sort_order' => 90,
        ];
    }
}

Edit Form UI Component

Now create the ui component for the grid. You can read detail of edit form from tutorial Magento 2 create custom ui component admin form. Now we Create helloworld_edit.xml in following directory

QaisarSatti\HelloWorld\view\adminhtml\ui_component\

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
* Hello World
   *
   * @category    QaisarSatti
   * @package     QaisarSatti_HelloWorld
   * @author      Muhammad Qaisar Satti
   * @Email       [email protected]
   *
*/
-->
<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">helloworld_edit.helloworld_data_source</item>
            <item name="deps" xsi:type="string">helloworld_edit.helloworld_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">Manage Post</item>
         <item name="config" xsi:type="array">
            <item name="dataScope" xsi:type="string">data</item>
            <item name="namespace" xsi:type="string">helloworld_edit</item>
        </item>
        <item name="template" xsi:type="string">templates/form/collapsible</item>
         <item name="buttons" xsi:type="array">
            <item name="back" xsi:type="string">QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\BackButton</item>
            <item name="delete" xsi:type="string">QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\DeleteButton</item>
            <item name="reset" xsi:type="string">QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\ResetButton</item>
            <item name="save" xsi:type="string">QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\SaveButton</item>
            <item name="save_and_continue" xsi:type="string">QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\SaveAndContinueButton</item>
        </item>        
    </argument>
    <dataSource name="helloworld_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">QaisarSatti\HelloWorld\Model\HelloWorld\DataProvider</argument>
            <argument name="name" xsi:type="string">helloworld_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">post_id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="submit_url" xsi:type="url" path="helloworld/index/save"/>
                </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/form/provider</item>
            </item>
        </argument>
    </dataSource>
    <fieldset name="general">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string"/>
            </item>
        </argument>
        <field name="id">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="visible" xsi:type="boolean">false</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="source" xsi:type="string">helloworld</item>
                </item>
            </argument>
        </field>
        <field name="title">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string">Title:</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="source" xsi:type="string">helloworld</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
        </field>
        <field name="content">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string">Content:</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="dataType" xsi:type="string">textarea</item>
                    <item name="formElement" xsi:type="string">textarea</item>
                    <item name="source" xsi:type="string">helloworld</item>
                </item>
            </argument>
        </field>        
     </fieldset>
 </form>

Save Form Data

Save controller have two parts. First is check PostDataProcessor, and second is save controller.

Post Data Processor

This is for validation purposes of form. Create PostDataProcessor.php in following directory

QaisarSatti\HelloWorld\Controller\Adminhtml\Index\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Controller\Adminhtml\Index;

class PostDataProcessor
{
    /**
     * @var \Magento\Framework\Stdlib\DateTime\Filter\Date
     */

    protected $dateFilter;

    /**
     * @var \Magento\Framework\View\Model\Layout\Update\ValidatorFactory
     */

    protected $validatorFactory;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */

    protected $messageManager;

    /**
     * @param \Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     * @param \Magento\Framework\View\Model\Layout\Update\ValidatorFactory $validatorFactory
     */

    public function __construct(
        \Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\View\Model\Layout\Update\ValidatorFactory $validatorFactory
    ) {
        $this->dateFilter = $dateFilter;
        $this->messageManager = $messageManager;
        $this->validatorFactory = $validatorFactory;
    }

    /**
     * Filtering posted data. Converting localized data if needed
     *
     * @param array $data
     * @return array
     */

    public function filter($data)
    {
        $filterRules = [];

        foreach (['custom_theme_from', 'custom_theme_to'] as $dateField) {
            if (!empty($data[$dateField])) {
                $filterRules[$dateField] = $this->dateFilter;
            }
        }

        return (new \Zend_Filter_Input($filterRules, [], $data))->getUnescaped();
    }

    /**
     * Validate post data
     *
     * @param array $data
     * @return bool     Return FALSE if someone item is invalid
     */

    public function validate($data)
    {
        $errorNo = true;
        if (!empty($data['layout_update_xml']) || !empty($data['custom_layout_update_xml'])) {
            /** @var $validatorCustomLayout \Magento\Framework\View\Model\Layout\Update\Validator */
            $validatorCustomLayout = $this->validatorFactory->create();
            if (!empty($data['layout_update_xml']) && !$validatorCustomLayout->isValid($data['layout_update_xml'])) {
                $errorNo = false;
            }
            if (!empty($data['custom_layout_update_xml'])
                && !$validatorCustomLayout->isValid($data['custom_layout_update_xml'])
            ) {
                $errorNo = false;
            }
            foreach ($validatorCustomLayout->getMessages() as $message) {
                $this->messageManager->addError($message);
            }
        }
        return $errorNo;
    }

    /**
     * Check if required fields is not empty
     *
     * @param array $data
     * @return bool
     */

    public function validateRequireEntry(array $data)
    {
        $requiredFields = [
            'title' => __('Title')
        ];
        $errorNo = true;
        foreach ($data as $field => $value) {
            if (in_array($field, array_keys($requiredFields)) && $value == '') {
                $errorNo = false;
                $this->messageManager->addError(
                    __('To apply changes you should fill in hidden required "%1" field', $requiredFields[$field])
                );
            }
        }
        return $errorNo;
    }
}

Form Save Data Controller

Now we save the data to our table.Create Save.php in following directory

QaisarSatti\HelloWorld\Controller\Adminhtml\Index\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Controller\Adminhtml\Index;

use Magento\Backend\App\Action;
use QaisarSatti\HelloWorld\Model\HelloWorld;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Exception\LocalizedException;

class Save extends \Magento\Backend\App\Action
{
   
    const ADMIN_RESOURCE = 'QaisarSatti_HelloWorld::helloworld1';    
    protected $dataProcessor;    
    protected $dataPersistor;
    protected $model;

    public function __construct(
        Action\Context $context,
        PostDataProcessor $dataProcessor,
        HelloWorld $model,
        DataPersistorInterface $dataPersistor
    ) {
        $this->dataProcessor = $dataProcessor;
        $this->dataPersistor = $dataPersistor;
        $this->model = $model;
        parent::__construct($context);
    }

    public function execute()
    {
       
        $data = $this->getRequest()->getPostValue();
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($data) {

            $data = $this->dataProcessor->filter($data);
           

            $id = $this->getRequest()->getParam('id');
            if ($id) {
                $this->model->load($id);
            }
           

            $this->model->setData($data);

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

            if (!$this->dataProcessor->validate($data)) {
                return $resultRedirect->setPath('*/*/edit', ['id' => $this->model->getId(), '_current' => true]);
            }

            try {
                $this->model->save();
                $this->messageManager->addSuccess(__('You saved the Post.'));
                $this->dataPersistor->clear('helloworld');
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath(
                        '*/*/edit',
                        ['id' => $this->model->getId(),
                         '_current' => true]
                    );
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the Post.'));
            }

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

Form Delete Button Controller

Create Delete.php in following directory

QaisarSatti\HelloWorld\Controller\Adminhtml\Index\

<?php
/**
 * Hello World
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
 */

namespace QaisarSatti\HelloWorld\Controller\Adminhtml\Index;

use Magento\Backend\App\Action;

class Delete extends \Magento\Backend\App\Action
{

    const ADMIN_RESOURCE = 'QaisarSatti_HelloWorld::helloworld1';
       
    protected $model;
    public function __construct(
        Action\Context $context,
        \QaisarSatti\HelloWorld\Model\HelloWorld $model
    ) {
        $this->model = $model;
        parent::__construct($context);
    }
    public function execute()
    {
        // check if we know what should be deleted
        $id = $this->getRequest()->getParam('id');
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($id) {
            $title = "";
            try {
                $this->model->load($id);
                $title = $this->model->getTitle();
                $this->model->delete();
                // display success message
                $this->messageManager->addSuccess(__('The post has been deleted.'));
                // go to grid
                $this->_eventManager->dispatch(
                    'adminhtml_helloworld_on_delete',
                    ['title' => $title, 'status' => 'success']
                );
                return $resultRedirect->setPath('*/*/');
            } catch (\Exception $e) {
                $this->_eventManager->dispatch(
                    'adminhtml_helloworld_on_delete',
                    ['title' => $title, 'status' => 'fail']
                );
                // display error message
                $this->messageManager->addError($e->getMessage());
                // go back to edit form
                return $resultRedirect->setPath('*/*/edit', ['id' => $id]);
            }
        }
        // display error message
        $this->messageManager->addError(__('We can\'t find a post to delete.'));
        // go to grid
        return $resultRedirect->setPath('*/*/');
    }
}

Now we complete the custom admin form. Now move to fourth part Magento 2 create basic module frontend part 4.

Author: Qaisar Satti
Category: Magento 2
Last Modified: February 9, 2018