Our Work

How to Create a plugin/Module in Magento 2.0 or convert your 1.x Plugin

Posted 1 year, 10 months and 12 days ago

Magento has released its latest stable release Magento 2.0 last month, highlights which are listed below.

  • Extensive and efficient APIs, including new ones for promotions and taxes
  • Automated testing to improve code quality
  • Data Migration Tool helps transfer existing Magento 1.x store data to Magento 2.0.
  • Performance wise Client-side optimizations, such as minimizing and bundling JavaScript, to decrease page load times.
  • Server-side improvements, such as integrating Apache Varnish caching, enable faster performance out-of-the-box with minimal tuning.
  • Standalone databases for key subsystems like order management, product management and checkout; combined with support for MySQL Cluster, enable Magento to scale to handle rapid growth.
  • Comprehensive backend improvements enable larger teams to make product updates and process orders at the same time without diminished performance.
  • New shopper experience features to improve engagement, conversion rates, and sales
  • The new checkout flow speeds shoppers through the process by minimizing steps
  • Key payment gateways such as PayPal, Braintree, Authorize.Net, WorldPay, CyberSource and obtain easiest level of PCI compliance
  • PHP 7.0.2 Compatibility
  • Security Enhancements
  • USPS API Changes

One Major change is old plugins won't work, we need to recreate them from scratch or  you need to convert them by changing your code and file structure. KTree Magento team started converted their existing plugins and for the benefit of the community thought they will release an extensive How to.
Here is the current Magento 2.X module structure:

app

  • code
    • Ktree
      • Zoom
        • Block
        • Controller
        • etc
        • Model
        • Helper
        • view
        • i18n
        • Setup
        • registration.php

We have listed down the differences on what has been changed in files from the perspective of version 1.X to 2.0 and also what has been changed. To make it simpler user can download our Magento 1.X Product Zoom Module. We will also publish ou 2.X KTree Magento Product Zoom module also this month as free plugin in Magento Connect. Please do share your comments and thoughts @ https://www.magentocommerce.com/magento-connect/ktree-product-zoom.html

For direct download please click here

Global Configuration file

Magento1 : app/etc/modules/Ktree_Helloword.xml

Magento2 : app/code/Ktree/Helloword/etc/module.xml

 <?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="Ktree_Helloword" schema_version="0.0.1" setup_version="2.0.0" />
</config>

In Magento2 there is no codepool (core,community, local) like Magento1. So everything will go under app/code folder.

Module config.xml

Magento1 : Here we will define blocks, models, helpers , routes and events  all in one single file called config.xml

routes example :
<frontend>
       <routers>
           <helloworld>
               <use>standard</use>
               <args>
                   <module>Ktree_Helloworld</module>
                   <frontName>helloworld</frontName>
               </args>
           </helloworld>
       </routers>
</frontend>

Magento2 : Here we define individual things in different file  by differentiating with different paths inside etc with adminhtml and frontend.

  • routes

ex :

<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="helloworld" frontName="helloworld">
            <module name="Ktree_Helloworld" />
        </route>
    </router>
</config>
  • Default configurations we need to create in config.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../Magento/Store/etc/config.xsd">
   <default>
       <Ktree_Helloworld>
           <general>
               <enable>1</enable>
           </general>
       </Ktree_Helloworld>
   </default>
</config>
  • Events will be managed with event.xml

  • System configuration with system.xml  same as Magento1

ex:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../Magento/Config/etc/system_file.xsd">
   <system>
       <tab id="ktree" translate="label" sortOrder="10">
           <label>Ktree</label>
       </tab>
       <section id="ktree_helloworld" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1"
                showInStore="1">
           <label>Ktree_Helloworld</label>
           <tab>ktree</tab>
           <resource>Ktree_Helloworld::ktree_helloworld</resource>
           <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0"
                  showInStore="0">
               <label>General</label>
               <field id="enable" translate="label comment" type="select" sortOrder="1" showInDefault="1"
                      showInWebsite="1" showInStore="1">
                   <label>Enable</label>
                   <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
               </field>
</group>
       </section>
   </system>
</config>

Controllers

Compare to Magento1, Controller Structure is totally changed  in Magento2.

ex : Magento1 controller

Class IndexController extends FrontController {
public function indexAction(){
}
public function testAction() {
}
}

The above controller can be defined in the following way in Magento2. Need to create a folder  under Controller  folder  with Controller name.

In this example  it is Index. Then need to create each and every action as  single file.

like Index.php, Test.php  inside   Index folder.

ex :

<?php
namespace Ktree\Helloworld\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
  
    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
}

Setup Script

In Magento1 we will define our setup script in config.xml  and create individual script files with install and upgrade script.

Whereas in Magento2  we need to place our setup files under Setup folder.

fileName : installSchema.php

<?php
namespace Ktree\Helloworld\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class InstallSchema implements InstallSchemaInterface
{
   public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
   {
       $installer = $setup;
       $installer->startSetup();
       $table  = $installer->getConnection()
           ->newTable($installer->getTable('testtablename'))
           ->addColumn(
               'id',
               \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
               null,
               ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
               'Id'
           )
           ->addColumn(
               'label',
               \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
               null,
               ['default' => null, 'nullable' => false],
               'Name'
           )
           ->addColumn(
               'value',
               \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
               null,
               ['default' => null, 'nullable' => false],
               'Stores'
           );
       $installer->getConnection()->createTable($table);
       $installer->endSetup();
   }
}

 

Layouts and Templates

Inside view folder needs to differentiate frontend and admin view files with following folders.

  • frontend
  • adminhtml

In each of the above folder will have layout,template and web  folders.

layout files we need to create with route path.  So each and every action we need to create single layout file.

ex : helloworld_index_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">
   <head>
       <css src="Ktree_Helloworld/css/custom.css"/>
   </head>
   <body>
       <referenceContainer name="product.info.media">
            <referenceBlock name="product.info.media.image">
                <action method="setTemplate">
                    <argument name="template" xsi:type="string">Ktree_Helloworld::helloworld.phtml</argument>
                </action>
            </referenceBlock>
       </referenceContainer>
   </body>
</page>

Template : Where we will create frontend template files  with .phtml extension

web : We will place all our css/images/js files inside this folder.

Need to create  requirejs-config.js file inside web folder if we want to include any custom js files  with our module.

ex :

var config = {
   map: {
       '*': {
           customscript: 'Ktree_Kelloworld/js/customScript'
       }
   }
};

 

Related Posts