:::: MENU ::::
Posts tagged with: admin form

Magento 2 create basic module part 1

Today we discuss how in magento 2 create basic module. This tutorial include the complete module sections frontend, admin end, custom model, custom admin grid, custom admin form, frontend controller, admin controller and admin menu. I already posted a tutorial about create a hello world module. Now we will go one step further and create a complete basic module. So let start with our example. My module name is hello world.

Module registration

First you register your module or extension. Create registration.php in following directory

QaisarSatti/HelloWorld/

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


\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'QaisarSatti_HelloWorld',
    __DIR__
);

Module declaration

First you declare your module or extension. In module.xml you declare your schema_version and setup_version of module that are stored in setup_module table . Now Create module.xml in following directory

QaisarSatti/HelloWorld/etc/

<?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:Module/etc/module.xsd">
   <module name="QaisarSatti_HelloWorld" schema_version="0.0.1" setup_version="0.0.1"/>
</config>

Module Setup

Now we create custom table sample_posts for module. You can read further on tutorial Magento 2 Create a install Schema. Now we Create InstallSchema.xml in following directory

QaisarSatti/HelloWorld/Setup/

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

namespace QaisarSatti\HelloWorld\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface {

    public function install( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
        $installer = $setup;

        $installer->startSetup();

        $table = $installer->getConnection()->newTable(
            $installer->getTable( 'sample_posts' )
        )->addColumn(
            'post_id',
            Table::TYPE_SMALLINT,
            null,
            [ 'identity' => true, 'nullable' => false, 'primary' => true ],
            'Post ID'
        )->addColumn(
            'title',
            Table::TYPE_TEXT,
            255,
            [ 'nullable' => false ],
            'Post Title'
        )->addColumn(
            'content',
            Table::TYPE_TEXT,
            '2M',
            [ ],
            'Post Content'
        )->setComment(
            'Sample Post Table'
        );

        $installer->getConnection()->createTable( $table );

        $installer->endSetup();
    }
}

Module Model

I already discuss model in Magento 2 create custom model tutorial. So we go to directly creating models file.

Model File

Create HelloWorld.php in following directory

QaisarSatti/HelloWorld/Model/

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


namespace QaisarSatti\HelloWorld\Model;



    class HelloWorld extends \Magento\Framework\Model\AbstractModel  
    {  
        protected function _construct()
        {
            $this->_init('QaisarSatti\HelloWorld\Model\ResourceModel\HelloWorld');
        }
}

ResouceModel File

Create HelloWorld.php in following directory

QaisarSatti/HelloWorld/Model/ResouceModel/

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



namespace QaisarSatti\HelloWorld\Model\ResourceModel;


use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class HelloWorld extends AbstractDb

{
    protected function _construct()

    {
        $this->_init('sample_posts', 'post_id');

    }
   

}

AbstractCollection Model File

Create AbstractCollection.php in following directory

QaisarSatti/HelloWorld/Model/ResouceModel/

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

namespace QaisarSatti\HelloWorld\Model\ResourceModel;

use Magento\Store\Model\Store;

/**
 * Abstract collection of CMS pages and blocks
 */

abstract class AbstractCollection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */

    protected $storeManager;

    /**
     * @var \Magento\Framework\EntityManager\MetadataPool
     */

    protected $metadataPool;

   
    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\EntityManager\MetadataPool $metadataPool,
        \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        $this->storeManager = $storeManager;
        $this->metadataPool = $metadataPool;
        parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
    }

    /**
     * Perform operations after collection load
     *
     * @param string $tableName
     * @param string|null $linkField
     * @return void
     */

    protected function performAfterLoad($tableName, $linkField)
    {
        $linkedIds = $this->getColumnValues($linkField);
       
       
    }

    /**
     * Add field filter to collection
     *
     * @param array|string $field
     * @param string|int|array|null $condition
     * @return $this
     */

    public function addFieldToFilter($field, $condition = null)
    {
       

        return parent::addFieldToFilter($field, $condition);
    }

    /**
     * Add filter by store
     *
     * @param int|array|Store $store
     * @param bool $withAdmin
     * @return $this
     */

    abstract public function addStoreFilter($store, $withAdmin = true);

    /**
     * Perform adding filter by store
     *
     * @param int|array|Store $store
     * @param bool $withAdmin
     * @return void
     */

    protected function performAddStoreFilter($store, $withAdmin = true)
    {
        if ($store instanceof Store) {
            $store = [$store->getId()];
        }

        if (!is_array($store)) {
            $store = [$store];
        }

        if ($withAdmin) {
            $store[] = Store::DEFAULT_STORE_ID;
        }

        $this->addFilter('store', ['in' => $store], 'public');
    }

    /**
     * Join store relation table if there is store filter
     *
     * @param string $tableName
     * @param string|null $linkField
     * @return void
     */

    protected function joinStoreRelationTable($tableName, $linkField)
    {
        if ($this->getFilter('store')) {
            $this->getSelect()->join(
                ['store_table' => $this->getTable($tableName)],
                'main_table.' . $linkField . ' = store_table.' . $linkField,
                []
            )->group(
                'main_table.' . $linkField
            );
        }
        parent::_renderFiltersBefore();
    }

    /**
     * Get SQL for get record count
     *
     * Extra GROUP BY strip added.
     *
     * @return \Magento\Framework\DB\Select
     */

    public function getSelectCountSql()
    {
        $countSelect = parent::getSelectCountSql();
        $countSelect->reset(\Magento\Framework\DB\Select::GROUP);

        return $countSelect;
    }
}

Collection Model File

Create Collection.php in following directory

QaisarSatti/HelloWorld/Model/ResouceModel/HelloWorld/

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



namespace QaisarSatti\HelloWorld\Model\ResourceModel\HelloWorld;


use QaisarSatti\HelloWorld\Model\ResourceModel\AbstractCollection;

class Collection extends AbstractCollection
{
    /**
     * @var string
     */

    protected $_idFieldName = 'post_id';

    /**
     * Load data for preview flag
     *
     * @var bool
     */

    protected $_previewFlag;

    /**
     * Define resource model
     *
     * @return void
     */

    protected function _construct()
    {
        $this->_init('QaisarSatti\HelloWorld\Model\HelloWorld', 'QaisarSatti\HelloWorld\Model\ResourceModel\HelloWorld');
    }

   
    public function setFirstStoreFlag($flag = false)
    {
        $this->_previewFlag = $flag;
        return $this;
    }

    /**
     * Add filter by store
     *
     * @param int|array|\Magento\Store\Model\Store $store
     * @param bool $withAdmin
     * @return $this
     */

    public function addStoreFilter($store, $withAdmin = true)
    {
       
        return $this;
    }

    /**
     * Perform operations after collection load
     *
     * @return $this
     */

    protected function _afterLoad()
    {
       
        return parent::_afterLoad();
    }

    /**
     * Perform operations before rendering filters
     *
     * @return void
     */

    protected function _renderFiltersBefore()
    {
        return parent::_renderFiltersBefore();
    }
}

Now the part 1 is complete now we got part 2 Magento 2 create basic module admin.

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


Magento 2 create custom ui component admin form

Today we talk about How in Magento 2 create custom ui component admin form. For creating the admin from you must familiar with ui component of magento2. The form consist of these major node that must be used for creating the form.

Data Argument

The argument data basically have three item js_config,label,config,template and buttons. Js_config contain js configuration of grid data. In buttons you can add button that are need to added into form like save button, delete button , save and continue button, reset button or any custom button as your requirement.

js_config

helloworld_listing this will be you ui component file name. helloworld_listing_data_source will be name of your dataSource.

<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>

buttons

You can add button in your form in buttons item. like save button, delete button , save and continue button, reset button or any custom button as your requirement.

 <item name="buttons" xsi:type="array">
            <item name="back" xsi:type="string">QaisarSatti\HelloWorld\Block\Adminhtml\HelloWorld\Edit\BackButton</item>
</item>

template

You can set template type in this node.

       <item name="template" xsi:type="string">templates/form/collapsible</item>

label

<item name="label" xsi:type="string" translate="true">Manage Post</item>

config

<item name="config" xsi:type="array">
            <item name="dataScope" xsi:type="string">data</item>
            <item name="namespace" xsi:type="string">helloworld_edit</item>
 </item>

dataSource

Second component of ui component form is dataSource. That have unique name that are use in ui component from. Name of my example helloworld_data_source.

<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

You can add multiple fieldset in form. Fieldset have unique name like general. Fieldset consist of following elements.

Data argument

In data argument you can add the label for fieldset and sort order.

<argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="collapsible" xsi:type="boolean">true</item>
                <item name="label" xsi:type="string" translate="true">General Information</item>
                <item name="sortOrder" xsi:type="number">20</item>
            </item>
</argument>

Field

This is element you add field as your requirement like select, input and etc. Here is simple example of 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>

Complete example for ui component is below.

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<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>
Author: Qaisar Satti
Category: Magento 2
Last Modified: February 9, 2018