How to create a Module in Magento 2

Here I’m going to explain step-by-step how you can create a module in Magento 2 (A module is called component in Magento 2). In Magento 1 we used to write business logic, layout, template and module enabling code in different places but Magento 2, gives us flexibility to create everything in one folder i.e app/code.

I’ve uploaded a simple Magento 2 module on github which will be taken as a reference in this tutorial. If you have any question, leave in the comments section and I will be happy to answer.

Magento 2 has introduced the concept of composer which is helpful to manage components details, components installation, and helps with managing component dependency.

Let’s start creating a new component. Create a folder app/code/Amit/Helloworld/ in root Magento directory, where Amit is the vendor name and Helloworld is the component/module name.
Now inside Helloworld folder create file composer.json with following code.

{
  "name": "amit/helloworld-module",
  "description": "Simple Magento 2 module that shows uses of Controller, Block & Template.",
  "type": "magento2-module",
  "version": "1.0.0",
  "license": [
    "OSL-3.0",
    "AFL-3.0"
  ],
  "require": {
    "php": "~5.5.0|~5.6.0|~7.0.0",
    "magento/framework": "~100.0"
  },
  "autoload": {
    "files": [ "registration.php" ],
    "psr-4": {
      "Amit\\Helloworld\\": ""
    }
  }
}

Explanation of the tags defined in composer.json
1. name is the unique name of your component.
2. description describes about your component.
3. type is the type of component.
There are 3 component types:
Module (defined as magento2-module)
Theme (defined as magento2-theme)
Language (defined as magento2-language)
4. version defines version of the component.
5. license defines license type of the component.
6. require defines dependency modules. All modules on which this component will be dependent will be listed here.
7. autoload defines which files should be auto-loaded when this component is installed.

Next, create a file registration.php php with following code

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Amit_Helloworld',
    __DIR__
);

Using Magento’s ComponentRegistrar’s register function we are registering our component.
create a file etc/module.xml. It is used to enable our component.

<?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="Amit_Helloworld" setup_version="2.0.0"/>
</config>

Controllers in Magento 2
A frontend controller should be created at app/etc/frontend/routes.xml with following code.

 <?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="helloworld" frontName="helloworld">
            <module name="Amit_Helloworld" />
        </route>
    </router>
</config>

Where router id is standard which means this controller should be applied on storefront, route id should be a unique id and front name is defined in frontName keyword which is used to access your controller like http://example.cpm/helloworld/ .

Now create your controller file at app/code/Controller/Index/Index.php with following content:

<?php
namespace Amit\Helloworld\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()
    {
       echo "Hello World!";
     }
 }

Now clear var/cache, var/page_cache and var/generation folders and in your browser run your controller like http://example.cpm/helloworld/ and you should see output Hello World! .

Leave a comment if you’re having issue making it work. In next tutorial I’ll be explaining how to create and use layout, block and template.

Magento: Export product attributes with category name and product URL

You can use following code to export product attributes, categories, and complete product URL link. Customize it according to your need.

<?php
require_once 'app/Mage.php';
umask(0);
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*') //Select everything from the table
->addUrlRewrite(); //Generate nice URLs

fputcsv($output, array(
'sku', 'Category ', 'Color', 'url_key'
)
);

foreach($collection as $product) {
$_cat = array();
$categoryName = array();

foreach ($product->getCategoryIds() as $Id) {
$_cat = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($Id);
$categoryName[] = $_cat->getName();
}
$color = array();
$color = implode(',', $product->getAttributeText('color'));
$comma_separated = implode(",", $categoryName);
fputcsv($output, array(
$product->getSku(),
$comma_separated,
$color,
str_replace('export.php/','',Mage::getBaseUrl()).$product->getUrlPath($category)
)
);
}
?>

Installing solr search with Magento Enterprise Edition

Solr

Recently I struggled a lot to integrate solr search with Magento as it is one of the most popular search engine nowadays.

Most of the informations are covered here: How to Use the Solr Search Engine With Magento Enterprise Edition .

What is the process you have to follow to make solr work with Magento?

  • Grab the solr version compatible with your Magento enterprise edition.
  • Install solr in your system.
  • Copy all the files from [magento-installation-root]/lib/Apache/Solr/Conf to [solr-installation-folder]/example/solr/conf
  • Start start.jar file available in [solr-installation-folder]/example using command java -jar start.jar .
  • Test solr connection in Magento admin panel. Successful??

Solr Connection test

  • Save the configurations and server settings as it is. By default solr runs at port 8983.
  • Now everything is ready. But most of the times you wont be able to see products in your catalog. Why?? Because Solr needs re-indexing of the documents.

PmVHV

How to re-index all the documents ?

  1. First go to shell(magento root) folder using command prompt  [magento-installation-root]/shell
  2. Check the current status of indexing using php indexer.php –status . Here you may see all the index types with current status.
  3. Re-index all the data using php indexer.php –reindexall . You can also re-index individual data’s as php indexer.php –reindex catalog_product_attribute

On completion of the re-indexing you will see

Solr re-indexing

Wooha. Solr re-indexing is successful. Now you should be able to see products in your categories and your solr search should be enabled.

References: Magento re-indexing by Shell scripting , Solr category search is not working in Magento EE

                       

Magento Files and Folder Structure

Hello Devs,

I’m Amit, a Magento Developer building cool e-commerce websites for RetailOn.

Magento is one of the widely used e-commerce platform based on Zend framework. Today I would like to explain few important Magento files and folders. Please have patience and let me know if you have any queries. I would love to help you out.

Once you will install Magento on your server you will see the following files/folders. MagentoFolderapp Directory
This is one of the most important directory of Magento.It contains different application development related files, module configuration files, design and theme related files and different localization files. app directory contains following folders and files.

  • code
  • design
  • etc
  • locale
  • Mage.php

code Directory
Most of the time developers have to play around this code directory only. It contains three different directories.

  • core
  • community
  • local

app/code/core: It contains Magento core folders. Only Core Magento Developers, who have written Magento are allowed to make modification in this folder. If your are planning to upgrade your your Magento version in future, never modify this folder.

app/code/community: It contains extensions installed from Magento Connect.

app/code/local:  It contains modules developed by developers locally. It is highly recommended to make your modification in this folder only(If you are not developing an extension).

app/design It contains all the designing files/folders . It contains following three sub folders.
  frontend : It contains all the design files related to fronend of Magento.
adminhtml: It contains all the design files related to back-end of Magento.
  install: It contains all the design Files related to Magento Installer.

app/etc: This directory contains all the configuration files related to the website (xml files).

app/locale: This directory contains localization specific csv files.