Magento 2 Overriding Controller

This post walks through the process to override a controller in Magento 2.

There are a few steps to override a Magento 2 controller.

Step 1. Building a Magento 2 extension structure

Building directories as given following:

magento2 --- app --- code
                       |--- A2bizz --- Sample
                       | --- Controller
                       | --- etc
                              | --- module.xml
                              | --- di.xml

Creating module.xml to define a Magento2 extension:

<?xml version="1.0"?>
<!--
/**
 * Created by blog.a2bizz@gmail.com
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="A2bizz_Sample" setup_version="0.0.1"/>
</config>

Step 2. Setting preference in di.xml

Creating di.xml to refer the overriding class:

<?xml version="1.0"?>
<!--
/**
 * Created by blog.a2bizz@gmail.com
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="Magento\Cms\Controller\Index\Index" type="A2bizz\Sample\Controller\Index\Index" /> 
</config>

A2bizz\Sample\Controller\Index\Index will be used to override Magento\Cms\Controller\Index\Index, which is the homepage in original Magento 2.

Step 3. Defining an overriding controller class

Under magento2/app/code/A2bizz/Sample/Controller, defining Index.php as following.

<?php
/**
 * Created by blog.a2bizz@gmail.com
 */
namespace A2bizz\Sample\Controller\Index;
class Index extends \Magento\Cms\Controller\Index\Index
{
    public function execute($coreRoute = null)
    {
        $this->messageManager->addSuccess('Message from new controller.');
        return parent::execute($coreRoute);
    }
} 

Index.php redefines function execute() to override the function in \Magento\Cms\Controller\Index\Index. The new execute() adds a message to homepage, but it may also implements a complex logic.

Magento2: Overriding Block

This post go through the process to extend a block in Magento2.

There are a few steps to override a Magento2 block as given below –

Step 1. Building a Magento 2 extension structure

Building directories as following:

magento2 --- app --- code
                       |--- A2bizz --- Sample
                                             | --- Block
                                             | --- etc
                                                    | --- module.xml
                                                    | --- di.xml

Creating module.xml to define a Magento2 extension:

<?xml version="1.0"?>
<!--
/**
 * Created by blog.a2bizz@gmail.com
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="A2bizz_Sample" setup_version="0.0.1"/>
</config>

Step 2. Setting preference in di.xml

Creating di.xml to refer the overriding block class:

<?xml version="1.0"?> 
<!-- /** * Created by blog.a2bizz@gmail.com */ --> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd"> 
<preference for="Magento\Theme\Block\Html\Title" type="A2bizz\Sample\Block\HelloTitle" /> 
</config> 

A2bizz\Sample\Block\HelloTitle will be used to override Magento\Theme\Block\Html\Title.

Step 3. Defining an overriding class

Under magento2/app/code/A2bizz/Sample/Block, defining HelloTitle.php as following.

<?php
/**
 * Created by blog.a2bizz@gmail.com
 */
namespace A2bizz\Sample\Block;
use Magento\Framework\View\Element\Template;
class HelloTitle extends \Magento\Theme\Block\Html\Title
{
    public function getPageTitle()
    {
        return 'A2bizz Custom';
    }
    protected function _toHtml()
    {
        $this->setModuleName($this->extractModuleName('Magento\Theme\Block\Html\Title'));
        return parent::_toHtml();
    }
}

HelloTitle.php redefines function getPageTitle() to override the function in \Magento\Theme\Block\Html\Title. The new getPageTitle() just return a text string, but it may also implements a complex logic.

HelloTitle.php also redefines function _toHtml(). Although HelloTitle overrides \Magento\Theme\Block\Html\Title, the template file of \Magento\Theme\Block\Html\Title is still supposed to be used. And the real path of a template file is determined by both the module name of a block and the template attribute of the block. Therefore, the module name of HelloTitle is still Magento_Theme, rather than A2bizz_Sample.

This line

$this->setModuleName($this->extractModuleName('Magento\Theme\Block\Html\Title'));

sets the correct nominal module name. This module name is necessary to render with the template originally defined for Magento\Theme\Block\Html\Title.

Magento2: indexer re-indexing manually using terminal

Indexing is how Magento2 transforms data such as products, categories, and so on, to improve the performance of your storefront. As data changes, the transformed data must be updated—or reindexed. Magento2 has a very sophisticated architecture that stores lots of merchant data (including catalog data, prices, users, stores, and so on) in many database tables. To optimize store front performance, Magento2 accumulates data into special tables using indexers.

In Magento2, there is none interface from admin, to re-index manually at a time as we did in magento1, for doing this we need to use terminal. Using Terminal we can did full indexing of magento2, whenever we need, to do this we just only need to open terminal and reach the root directory of magento2 installation and type below mentioned command.

magento indexer:reindex [indexer]

where [indexer] is a space-separated list of indexers. Omit [indexer] to reindex all indexers.

Magento2 : adding menu in admin section of custom module

As we already know of Structure of a custom module in Magento2, lets begin with creating Menu for our custom module in Admin section, in magento2 the management of a menu section is totally controlled by menu.xml file which exists inside etc/adminhtml directory –

Let for example you have a following directory path of a custom module  –

 magento2/app/code/A2bizz/Blog/

Where A2bizz is the name of namespace and Blog is the name of our custom module, now inside this structure we will have a etc folder which is again have two directories, adminhtml and frontend.

magento2/app/code/A2bizz/Blog/etc/adminhtml/menu.xml

a sample of menu.xml is given below –

<?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="A2bizz_Blog::blog" title="Designer" module="A2bizz_Blog" sortOrder="0" resource="A2bizz_Blog::blog"/>
        <add id="A2bizz_Blog::blog_page" title="Pages" module="A2bizz_Blog" sortOrder="0" parent="A2bizz_Blog::blog" action="blog/page" resource="A2bizz_Blog::page"/>
    </menu>
</config>

Magento 2 : Return a json response from a controller

Here the way to return a json response from admin controller

<?php namespace A2bizz\Xyz\Controller\Adminhtml\Abc; 
class  A2bizz extends \Magento\Backend\App\AbstractAction { 
/** 
 * @param \Magento\Backend\App\Action\Context $context 
 * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory 
 */ 
public function __construct( 
    \Magento\Backend\App\Action\Context $context ,
    \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory 
    ) { 
         parent::__construct($context); 
         $this->resultJsonFactory = $resultJsonFactory;
      }

 /**
 * @return \Magento\Framework\Controller\Result\Json
 */
public function execute() {
 /** @var \Magento\Framework\Controller\Result\Json $result */
 $result = $this->resultJsonFactory->create();
 return $result->setData(['success' => true]);
 }
}

etc/adminhtml/routes.xml:

<?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='admin'>
		<route id='adminhtml' frontName='admin'>
                  <module name='A2bizz_Xyz' before='Magento_Backend' />
		</route>
	</router>
</config>

Magento2: Composer and Installation

Magento now uses Composer to install the Magento software. Composer enables Magento to manage the Magento components and their dependencies.

If You have already installed Composer then go for the Next step, for the installation of Magento2 setup.

Anyone who uses the Magento software must install Composer to update components and Magento Ssoftware. If you install Magento using an archive or setup, you don’t need Composer to install Magento, but for getting updates you do need Composer.

Composer provides following advantages:

  • Enables to reuse third-party libraries without bundling them with source code
  • Component-based architecture with robust dependency management
  • Manages dependencies to reduce extension conflicts and compatibility issues
  • Versioned dependencies
  • Semantic versioning
  • Supports PHP Framework Interoperability standard

Install Composer

First, check if Composer is already installed:

In a command prompt, enter any of the following commands:

  • composer --help
  • composer list --help

If command help displays, Composer is already installed; in that case, you can skip the next section and continue with magento installation.

If an error displays, use the following steps to install Composer.

To install Composer:

  1. Change to or create an empty directory on your Magento server.
  2. Enter the following commands:
    curl -sS https://getcomposer.org/installer | php
    mv composer.phar /usr/local/bin/composer

    For additional installation options, see the Composer installation documentation.

Magento2: Module File Structure

Magento 2 Module File structure

In Magento2, there are lots of differences you will find out, due to security purposes. Magento2 looks for the files that make up a module, including configuration files, in particular places inside the module file structure. Follow the predefined file structure to ensure that your module works as expected.

A module can live or can be place now anywhere in Magento root directory. Regardless of where you add it, you must be registered, for Registering your module we need to implement registeration.php file.

A typical file structure for a Magento 2 module:

module-file-structure

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Main Directories

The main directories are:

  • Block — it contains PHP classes as part of MVC vertical implementation of module logic.
  • Controller — it contains PHP classes as part of MVC vertical implementation of module logic.
  • Helper — it contains PHP classes as part of MVC vertical implementation of module logic.
  • Model — it contains PHP classes as part of MVC vertical implementation of module logic.
  • Setup — it contains classes for module database structure and data setup which are invoked when installing or upgrading.

Additional directories

Additionally, there are folders for configuration and other ancillary functions for items like plug-ins, internationalization, and front-end layout files.

  • Api— it contains any PHP classes exposed to the API.
  • etc — it contains configuration files.
  • i18n — it contains localization different files, like language files.
  • Plugin — it contains any needed plugin files.
  • view — it contains non-object-oriented and non-static view level parts of the module such as design templates, email templates, and layout files.

Magento2: Registration of module

For Registering our custom module, we need to create a php file named registration.php in the root of our custom folder and write the below given code

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

if examine this code then you will see that after the name of module there is a __DIR__ variable which is a php variable to identify the current working directory, it means that you can register your module from any where in Root of magento directory.

Enjoy this Article, don’t miss to comment us or write us if you need to know more about magento2

Magento2: Command Line or Terminal installation on Ubuntu

A long-waited Magento2 now appeared on Magento site for installation. Of course we couldn’t sit still and installed Magento2 on our server. And described the installation process for you, including the issues we dealt with and how we fixed them.

Pre Installation

The first steps lead us to the installation guide page. It is required to check whether your server suits minimal Magento 2 requirements:

Apache: 2.2 or 2.4

PHP: 5.5.x or 5.6.x

MySQL: 5.6.x

Composer

As we are using Ubuntu 14.4,  so the system suits minimal database requirements, and we already have PHP 5.5.x support. Also you’ll need Git and Composer, install it if you haven’t done it before.

Use these commands in command line or terminal for root user permissions:

apt-get update
apt-get install git wget
wget -O /usr/local/bin/composer http://getcomposer.org/composer.phar
chmod +x /usr/local/bin/composer

Magento 2 download

Now it’s time to clone Magento 2 code from GitHub repository. http://magento2/ is the URL of our website, and the document root is /var/www/magento2. Use these commands if you don’t plan to install Sample data for Magento 2:

cd /var/www 
git clone https://github.com/magento/magento2.git
cd /var/www/magento2
composer install

If you plan to install Sample data – refer to this link for details. As for now Magento 2 is still under development, the best variant is to read the latest documentation at Magento docs.

File permissions

create a root user, which is the owner of all magento files on your server, and Apache web server runs on behalf of ‘www-data’ user. Magento 2 documentation describes the access permission settings for files and directories on the principle that the web server runs on behalf of the user which is the owner of all Magento files. Our opinion is: it’s not the best decision, as it can lead to security issues (as the web server has permissions to write and run the code) as well as issues with setting access permissions for third party developers (as you’re not logging in as www-data user). We normally use the following access permissions:

chown -R :www-data /var/www/magento2
find /var/www/magento2 -type f -print0 | xargs -r0 chmod 640
find /var/www/magento2 -type d -print0 | xargs -r0 chmod 750
chmod -R g+w /var/www/magento2/{pub,var}
chmod -R g+w /var/www/magento2/{app/etc,vendor}

Database

now create database –

echo 'CREATE DATABASE `magento2` DEFAULT CHARSET utf8 COLLATE utf8_general_ci; GRANT ALL PRIVILEGES ON `magento2`.* to `magento2`@`%` IDENTIFIED BY "magento2";' | mysql -h mysql56.local -u root -p

Magento2 installation

Now all is set start you magento installation using below command

/var/www/magento2/bin/magento setup:install --base-url=http://magento2/ --db-host=localhost --db-name=magento2 --db-user=root --db-password=root --admin-firstname=a2bizz --admin-lastname=user --admin-email=a2bizz@gmail.com --admin-user=a2bizz --admin-password=a2bizz@123 --language=en_US

Magento2: Step by step installation

As we are known of pre installation requirements of magento2 software installation, now we starting to install magento2 step by step, if you have not gone through the pre installation process and system requirements for magento2 installation, then go through our pre-installation article for magento2

For installation we are using Linux system Operating system Ubuntu version 14.04

Step 1 – Extarct your zip installation file –

copy your installation magento2 zip folder to the desired location of your server, or in your local computer, it will be – /var/www/html/magento2. In magento2 folder extract your magento installation files.

magentoExtract

Now hit your magento2 url, it should be http://localhost/magento2/ and screen will be displayedsetupStart

If this installation screen not comes in first attempt, then change the permission of var directory to 777, inside your root directory in extracted files.

Now click button Agree and Setup Magento

Step 1 – Rediness Check

A next will come in this screen click button “Start Rediness Check”, this will check the basic requirements to install magento2.

ReadinessCheck

 

 

See what is required and fullfil that

Step 2 – Add a Database –

create a database in you host/ localhost and fill the details, if you do not have mysql version 5.6 or later then setup will show error.

Add a Database

 

 

Step 3 – Web Configuration –

here set your admin address, write the name for your admin, for example – we have given a admin address as “admin”.

Step 4 – Customize Your Store –

here set your currency, language and time zone

Step 5 – Create Admin Account –

here set the admin user name and password for your magento2 application.

Step 6 – Install –

Now all set, you click on start and your installation process will start.