Magento: Create Custom Module

Today, We are going learn to create custom module in Magento, so here are the below steps to create a sample ‘Helloworld’ module-

New Custom Module Creator for Magento2

Sample file structure:

[root]\app\code\local\{Namespace}\{Modulename}
[root]\app\code\local\{Namespace}\{Modulename}\controllers
[root]\app\code\local\{Namespace}\{Modulename}\etc
[root]\app\code\local\{Namespace}\{Modulename}\etc\config.xml
[root]\app\code\local\{Namespace}\{Modulename}\Helper
[root]\app\code\local\{Namespace}\{Modulename}\Model
[root]\app\code\local\{Namespace}\{Modulename}\{Modulename}.php

{Namespace} is a user defined variable. Basically it’s just a mechanism that allows the user to create disparate classes that would otherwise have the same names.

{Modulename} this is the name of your module.

controllers is where all the controllers go.

Model holds all of the models for your module.

For example we use “A2bizz” as namespace and “Helloworld” as Module. we entirely sure if it matters or not, but as a general rule we always capitalize the first letter and leave the rest lower case.

Step One

Inform Magento that you have a custom module. Note the file locations (need to create directories as necessary).

app/etc/modules/A2bizz_HelloWorld.xml

<?xml version=”1.0″?>
<config>
	<modules>
		<A2bizz_HelloWorld>
			<active>true</active>
			<codePool>local</codePool>
		</A2bizz_HelloWorld>
	</modules>
</config>

In this way we have informed Magento that we have an active module (you can turn it off from here by setting ‘active’ to false. we have also informed Magento that it is located in the ‘local’ code pool.

Step Two

Configure your new module. Note the file locations (need to create directories as necessary).

app/code/local/A2bizz/HelloWorld/etc/config.xml

<?xml version=”1.0″?>
<config>
	<global>
		<modules>
			<a2bizz_helloworld>
				<version>0.1.0</version>
			</a2bizz_helloworld>
		</modules>
		<blocks>
			<helloworld>
				<rewrite>
					<helloworld>A2bizz_HelloWorld_Block_HelloWorld</helloworld>
				</rewrite>
			</helloworld>
		</blocks>
	</global>
	<frontend>
		<routers>
			<helloworld>
				<use>standard</use>
				<args>
					<module>A2bizz_HelloWorld</module>
					<frontName>helloworld</frontName>
				</args>
			</helloworld>
		</routers>
		<layout>
			<updates>
				<helloworld>
					<file>helloworld.xml</file>
				</helloworld>
			</updates>
		</layout>
	</frontend>
</config>

Here we informed Magento of module version (it’s an arbitrary version). Version matters when you set up your module to be update-able. (A newer version will inform Magento to run the update files if you have them).

We aware Magento that module contains block files which are found in A2bizz/HelloWorld/Block. Here class name will have A2bizz_HelloWorld_Block. If you want to see the many possibilities of stuff that goes in here, check out Magento config files (such as Catalog/etc/config.xml). You’ll also see other xml files in there.

Step Three

Here is my block code. It doesn’t really do anything, but shows some functionality.

app/code/local/A2bizz/HelloWorld/Block/HelloWorld.php

<?php
class A2bizz_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
{
	public function _prepareLayout()
	{
		$this->getLayout()->getBlock(‘breadcrumbs’)
			->addCrumb(‘home’, array(‘label’=>Mage::helper(‘catalogsearch’)->__(‘Home’),
						‘title’=>Mage::helper(‘catalogsearch’)->__(‘Go to Home Page’),
						‘link’=>Mage::getBaseUrl())
						)
			->addCrumb(‘customer’, 
						array(‘label’=>Mage::helper(‘customer’)->__(‘Foo’))
						);
		return parent::_prepareLayout();
	}

	public function myMessage(){
		return “This is A2bizz, This is our module.”;
	}
}
?>

Step Four

Now we create a template file (.phtml) file.

app/design/frontend/default/default/template/helloworld/helloworld.phtml

<?php

echo ‘Hello World ! This A2bizz’;
echo “<BR/>”;
echo $this->myMessage();

?>

Now, Our custom module has been created you can use it, for additional functionality.

Magento2 create custom theme

Today, We going to learn, how to create custom theme in magento2 , or how we can start to add our own customized theme, to do so, please follow the below steps –

1. Create the path app/design/frontend/a2bizz/custom, where a2bizz and custom are your own package and theme names respectively, whatever you like to give name, give it.

2. Now create a file theme.xml inside the above path, and write below given code –

<theme xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation = "../../../../../lib/internal/Magento/Framework/Config/etc/theme.xsd">
 <title>A2bizz Custom theme</title>
 <parent>Magento/blank</parent> <!--the parent theme, in case your theme inherits from an existing theme -->
 <media>
   <preview_image>media/preview.jpg</preview_image>
  </media>
</theme>

Now, register your theme and create a file registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::THEME,
    'frontend/a2bizz/custom',
    __DIR__
);

Now, the registration of a custom theme is being completed and it has been added to the list of themes, go to the admin section and Select your custom theme from admin >> store >> Configuration >> General >> Design. to change the theme.

Magento2: create custom module

Today we will learn to create custom module in magento2-

For installation and initial learning please visit our previous blogs of magento2.

The overall development we are doing on Ubuntu 14.4, local environment the base directory structure of my local is –
/var/www/html/magento2/app/code/A2bizz/Blog

You can download full code from GIT below given URL –
https://github.com/bloga2bizz/Magento2-Sample-Frontend-Module

customModule

Step 1.Initialization of your custom module –

First of all we will have to initialize our custom module to the list of modules with magento configuration, for which we will have to first create a /var/www/html/magento2/app/code/A2bizz/Blog/registration.php file and write below code –

<?php

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

?>

if you hit your magento2 URL i.e. http://localhost/magento2/, now you will get below issue –

Cannot read contents from file "/var/www/html/magento2/app/code/A2bizz/Blog/etc/module.xml"

Now create module.xml on file /var/www/html/magento2/app/code/A2bizz/Blog/etc/module.xml and write below code –

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="A2bizz_Blog" setup_version="2.0.0" />
</config>

Now we have initialised our custom module, To check that please check /var/www/html/magento2/app/etc/config.php where your created module will be listed down, if not then upgrade custom module.

Step 2. creating controller & routing –

Now Further create controller file /var/www/html/magento2/app/code/A2bizz/Blog/Controller/Index/Index.php

<?php

namespace A2bizz\Blog\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{    
	protected $resultPageFactory;

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

}

and a routes.xml file on path /var/www/html/magento2/app/code/A2bizz/Blog/etc/frontend/routes.xml,which will provide the path execution to your custom module –

<?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="standard">
        <route id="blog" frontName="blog">
            <module name="A2bizz_Blog" />
        </route>
    </router>
</config>

here, in this xml we initializing the calling path for our custom module. In this way we have successfully hit out the controller for our custom module. Here in our example hit – http://127.0.0.1/magento2/blog

if the hitting above URL is showing blank white page, it means controller is hitted in a proper manner and now asking for the page layout.

Step 3. designing layout (view) for our custom module –

Now Further create layout files for your custom module /var/www/html/magento2/app/code/A2bizz/Blog/view/frontend/layout/blog_index_index.xml

<?xml version="1.0"?>
<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="A2bizz\Blog\Block\Blog" name="blog" template="A2bizz_Blog::blog.phtml" />
        </referenceContainer>
    </body>
</page>

and add /var/www/html/magento2/app/code/A2bizz/Blog/view/frontend/templates/blog.phtml

<?php
echo "Blog Template";
?>

Now hit your custom module URL again, will show you below error
Object DOMDocument should be created.

it means it is unable to find corresponding Block method for its layout.

Now create your Block method, in /var/www/html/magento2/app/code/A2bizz/Blog/Block/Blog.php

<?php
namespace A2bizz\Blog\Block;

class Blog extends \Magento\Framework\View\Element\Template
{
	public function _prepareLayout()
	{
	    return parent::_prepareLayout();
	}
}
?>

Now, Executing your URL http://localhost/magento2/blog, will show you complete module functionality.

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.

add custom role

The key features of WordPress that is often overlooked is that there are a number of different user roles available. These user roles can  help make insure that only the people have access to just the areas they need and also helps minimize the chances of any  accidents happening that could potentially bring down the site. in this article we will look at those user roles briefly and also go into how to create your own custom roles.

User roles have been an important part of the WordPress experience since version 2.0. Most people don’t even know they exist and assign administrator rights to everyone who has access to their site dashboard (obviously not a good thing for a whole bunch of reasons). Off the shelf, WordPress comes with six default user roles:

Administrator: someone who has access to all the administrative features and functions within a site.
Editor: someone who can publish and manage posts of all users, including their own.
Author: someone who can publish and manage their own posts.
Contributor: someone who can write and manage their own posts but can’t publish them.
Subscriber: someone who can only manage their profile.

Why Use Custom User Roles?

The most part the default user roles are all that are needed. But there are cases where you need a user role that doesn’t fit in with the parameters of the default roles. And in this article We’ll see how to create custom user roles without using a plugin.

Lets thought on why we want to use Custom User roles. Typically use Custom User roles to make sure that clients only have access to what they need.

But if you are responsible for making sure the site stays up 24/7, then We recommend restricting the access of the client through a custom user role. That way We can give the client everything they need to make their site effective, like add content, maybe add events whatever they need to do. What they can’t do is things that can bring the site down or mess-up some functionality. We restrict things like access to add or remove plugins, themes, update core, all the kinds of things We’d want to do as part of my ongoing maintenance.

But lets start with a quick review of the basics, shall we?

Basic WordPress Functions

In order to manage roles and capabilities effectively, there are five very straightforward functions:

add_role(): Enables you to add a custom role.
remove_role(): Enables you to remove a custom role.
add_cap(): Enables you to add a custom capability to a role.
remove_cap(): Enables you to remove a custom capability from a role.
get_role (): Gets information about a role as well as the capabilities associated with the role.

We are only going to use the add_role() function for this article as we are going to create a custom user role for our fictitious client.

Defining The User Role

So before we dive into the code we need to have a plan, because diving into code without a plan is never a good idea.

So we need to give the user role a name. We’ll keep it simple and call the user role ‘Customer’.

So what can the user role ‘Customer’ actually do? There are over 50 different capabilities available in a clean install of WordPress (the number increases once you start adding plugins, but we’ll go over that in another article). For our purposes we want the client to be able to do the following:

Create posts
Edit posts
Edit Others posts
Manage categories
Edit Pages

Equally important is what we don’t want them to be able to do:

Edit themes
Add or Remove Plugins
Update core

Writing the Code

We are going to put this code into the functions.php file for our active theme. So lets start by adding this to the file:

// Add a custom user role

$result = add_role( 'customer', __(
'Customer' ),
array( ) );

By adding that piece of code, you have technically created a new user role (you can check it in the drop down on the Add New User page and it should be there). The problem is this user role has no functionality assigned to it. So the next step is obviously to add the functionality we had previously identified in our requirements above. Just add the array code to what you have already entered into your functions.php file.

// Add a custom user role

$result = add_role( 'customer', __(

'Customer' ),

array(

'read' => true, // true allows this capability
'edit_posts' => true, // Allows user to edit their own posts
'edit_pages' => true, // Allows user to edit pages
'edit_others_posts' => true, // Allows user to edit others posts not just their own
'create_posts' => true, // Allows user to create new posts
'manage_categories' => true, // Allows user to manage post categories
'publish_posts' => true, // Allows the user to publish, otherwise posts stays in draft mode

)

);

That will give us the functionality we want the client to have but we still need to restrict them from doing things that could potentially cripple the site. So lets add that now.

// Add a custom user role

$result = add_role( 'customer', __(

'Customer' ),

array(

'read' => true, // true allows this capability
'edit_posts' => true, // Allows user to edit their own posts
'edit_pages' => true, // Allows user to edit pages
'edit_others_posts' => true, // Allows user to edit others posts not just their own
'create_posts' => true, // Allows user to create new posts
'manage_categories' => true, // Allows user to manage post categories
'publish_posts' => true, // Allows the user to publish, otherwise posts stays in draft mode
'edit_themes' => false, // false denies this capability. User can’t edit your theme
'install_plugins' => false, // User cant add new plugins
'update_plugin' => false, // User can’t update any plugins
'update_core' => false // user cant perform core updates
)
);

User Role Is Set Up Properly?

WordPress Sidebar Making sure your new user role is working as intended requires you to set up a new user with the appropriate role, log out and log back in as the new user.

Depending on what capabilities you’ve allowed and what you have denied, the first thing you should notice is a change in what’s available in the dashboard. The image below shows you what you would see if you set up the client role as we did above.

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