:::: MENU ::::
Browsing posts in: Magento 2

Indexer in Magento 2

This tutorial is about Indexer in Magento 2. First of all lets discuss what is indexing in magento 2? The answer is how Magento 2 transforms data ( products, categories) to improve the performance of your storefront is called indexing.To optimize storefront performance, Magento accumulates data into special tables using indexers. As magento stores lots of data (including catalog data, prices, users, stores) in many database tables.

Lets have an example to clarify the concept. Suppose you changed the price of an item from $4.99 to $3.99. Magento must reindex the changed price to display it on your storefront. Otherwise loading the product information would take a long time, which may result in cart abandonment.

So this was a brief introduction of indexing.Now, lets come to our topic. In this tutorial we will look at different aspects and functionalities of indexing.

Above all lets start learning

indexing in magento 2

We will start with Magento 2 indexers.

Magento 2 indexers

There are basically 10 indexers. we can say that there are 10 default indexers. Which are as follows:

– Design Config Grid ( name: design_config_grid )
– Customer Grid ( name : customer_grid )
– Category products ( name: catalog_category_product )
– Product categories ( name: catalog_product_category)
– Product price ( name: catalog_product_price)
– Product entity attribute value ( name: catalog_product_attribute)
– Catalog search ( name: catalogsearch_fulltext)
– Stock ( name: cataloginventory_stock)
– Catalog rule product ( name: catalogrule_rule)
– Catalog product rule ( name: catalogrule_product)

Furthermore you can look indexer info using following command:

php bin/magento indexer:info

Now we will discuss Indexer status.

Indexer status

An indexer status can be one of following:

– valid: data is synchronized, no reindex required
– invalid: the original data was changed, the index should be updated
– working: indexing is in progress

Similarly you can get indexer status using the following command:

php bin/magento indexer:status

Furthermore lets have a look at Indexing modes.

Indexing modes

Re-indexing can be performed in two modes:

Update on Save: index tables are updated immediately after the dictionary data ( product, category, store…) is changed.
Update by Schedule: index tables are updated by cron job according to the configured schedule.

Similarly you can get indexer status using the following command:

php bin/magento indexer:show-mode

Following command can change indexer mode:

php bin/magento indexer:set-mode {realtime|schedule} [indexer-name]

For the reason that “realtime” is equal to “Update on Save” and “schedule” is equal to “Update by Schedule”.


Rather using “System -> Index Management” in Magento backend, we can also re-index using the following command:

php bin/magento indexer:reindex [indexer-name]

You will get the result like:
1 Customer Grid index has been rebuilt successfully in

Futhermore reset indexer when it’s locked.h3>

Reset indexer

During re-index process, you may get the message like:

Stock index is locked by another reindex process. Skipping.

So we need to reset that indexer status to be able to re-index ( in this case, it’s “cataloginventory_stock” )

Similarly you can reset indexer using following command:

php bin/magento indexer:reset [indexer-name]

That’s it from this tutorial. I hope it serves the purpose.

Since these tutorials are for learning purpose please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: October 12, 2018

Magento 2 Call Helper method in phtml

This tutorial is about Magento 2 Helper method in phtml.i.e Helper method in magento 2. First of all i assume you are familiar with magento 2. And if you are not familiar with advance magento concepts and are looking for basics,please look for magento 2 basic tutorials.

lets start our tutorial.Suppose you want to call a Helper method in template(.phtml) file.How can you do it?. We will discuss it briefly in this tutorial.

It is not a good practice to use helper calls directly in the template.Because it introduces an undeclared dependency. If you want to do this properly you should only call in the template only methods from the block that renders it.Rather you can have your helper instance provided as a dependency to the block that renders the template and create a method in your block that calls the helper and call that method in the template.

You can defined your block like:

protected $helperData;
public function __construct(
    \QaisarSatti\HelloWorld\Helper\Data $helperData,
) {
    $this->helperData = $helperData;

public function doSomething()
    return $this->helperData->doSomething();

Finally you can call this block like:


Where block something in my case is just for understanding.You will use your own function name.

Similarly there is another way of doing it.Lets have a look at the code:

$helper = $this->helper('QaisarSatti\HelloWorld\Helper\Data');
$values = $helper->YourHelperMethod();

Furthermore you have to write the whole class name in helper as below:


You can use it in phtml file using above code.

Further more with some modifications, there is another approach of doing it.

Lets have a look at it.

Likewise you can look at the directory,in which this code is implemented:


namespace QaisarSatti\HelloWorld\Block;

class Test extends \Magento\Framework\View\Element\Template

protected $_helper;

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    array $data = [],
    \QaisarSatti\HelloWorld\Helper\Data $helper
) {
    parent::__construct($context, $data);

    $this->_helper = $helper;

public function getEnable(){
        return $this->_helper->getEnable();


Similarly in


you can modify:

 <?php  echo $block->getEnable(); ?>

Furthermore in


. we can use below code:

namespace QaisarSatti\HelloWorld\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper {

    /** * @var \Magento\Framework\App\Config\ScopeConfigInterfac

    protected $_scopeConfig;
    CONST ENABLE = 'helloworld/general/enable_module';

    public function __construct( \Magento\Framework\App\Helper\Context $context,
            \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig ) {

             parent::__construct($context); $this->_scopeConfig = $scopeConfig;

    public function getEnable(){
        return $this->_scopeConfig->getValue(self::ENABLE);


Similarly in


System configurations are created.

Author: Qaisar Satti
Category: Magento 2
Last Modified: October 12, 2018

Magento 2 call any block function in phtml

This tutorial is about magento 2 call block function in phtml. First of all i assume that you are familiar with magento 2 and hence you are at this level where you want to know how in magento 2 call any block function in phtml. Above all if you are not familiar and are looking for basics please look for magento 2 basic tutorials.

Seems like i have conveyed my message so lets start our tutorial and focus on our topic. For example if you want to call your custom block function in product list.phtml?.How can we do it? I will try to explain it in a simple way.

Call custom block funtion

Lets have a look at the code.
For example your block class is as below

namespace QaisarSatti\HelloWorld\Block;
use Magento\Framework\View\Element\Template;

class Test extends Template
    public function getMyCustomMethod()
        return 'Get Your custom method';

Then in any phtml file,you can use the following code to get method of this block.

$blockObj= $block->getLayout()->createBlock('QaisarSatti\HelloWorld\Block\Test');
echo $blockObj->getMyCustomMethod();

That is how it can be done.Certainly, i have tried to explain these codes and their logic in a simple way, i hope they help you learn in an easy and better way. That’s it from this tutorial.

Since these tutorials are for learning purpose please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: October 4, 2018

Add remove product from compare programmatically in Magento2

In this tutorial we will discuss another technique of magento 2, we will learn How to add and remove product from compare in Magento 2. Obviously there are many ways and techniques of doing a task but if you are looking for a better and dynamic way then this tutorial may satisfy your needs. If a product is already added to the compare collection then on next click on that icon should remove that product from compare collection.

Remove product from compare

To remove product from compare collection , following piece of code will get the desired results.

protected  $_productloader;
protected $_compareItemFactory;
protected $_catalogProductCompareList;

public function __construct(
    \Magento\Catalog\Model\Product\Compare\ItemFactory $compareItemFactory,
    \Magento\Catalog\Model\Product\Compare\ListCompare $catalogProductCompareList,
    \Magento\Catalog\Model\ProductFactory $productloader
) {
    $this->_productloader = $productloader;
    $this->_compareItemFactory = $compareItemFactory;
    $this->_catalogProductCompareList = $catalogProductCompareList;

public function execute()
    $productId = (int)$this->getRequest()->getParam('product');

As you can see magento 2 is using following code for removing the product from compare you can use this code too.

<a href="#" class="action tocompare" title="<?php echo $block->escapeHtml(__('Remove Compare')); ?>"
           aria-label="<?php echo $block->escapeHtml(__('Remove Compare')); ?>"
         data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataRemove($_product); ?>'
      <span><?php /* @escapeNotVerified */ echo __('Remove Compare') ?></span>

Add product to compare

To perform the add product to compare collection task, following code should be able to get the desired result.

protected  $_productloader;

protected $_catalogProductCompareList;

public function __construct(

    \Magento\Catalog\Model\Product\Compare\ListCompare $catalogProductCompareList,
    \Magento\Catalog\Model\ProductFactory $productloader
) {
    $this->_productloader = $productloader;
    $this->_catalogProductCompareList = $catalogProductCompareList;

public function execute()
    $productId = (int)$this->getRequest()->getParam('product');


A new file can be created to implement the above mentioned code and can be considered as a good technique but you can modify the existing file as well as per your requirements.

It is also a good practice to add your module and redirect it on your controllers, don’t try to edit the core file as it may get complicated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: September 26, 2018

Magento 2 design patterns

In this tutorial we will learn about the magento 2 design patterns . Magento 2 have numerous design patterns MVC, Front controller, Factory, Singleton, Registry, prototype, object pool,Iterator,lazy loading , service locator,module, observer,Active record,service contract, object manager,injectable objects,non-injectable objects, dependecy injection, factory pattern or factory classes and proxy pattern. we will have a brief look of most design patterns provided by magento 2. Although it will be brief but will try to cover all the important aspects and functionalities of these design patterns.

Lets have a look at different design patterns one by one with brief description.


Magento utilizes a unique MVC pattern, utilizing a DOM based configuration layer. It leverages xml to drive the configuration and actions of the application on top of the regular Model-View-Controller architecture.

Front Controller

Magento uses the Front Controller pattern to implement workflows for it’s application. It has a single entry point (index.php) for all of it’s requests. Let’s see how it all works.


The Factory Method is used to instantiate classes in Magento. You instantiate a class in Magento by calling an appropriate method passing an abstract name representing a class group followed by a class name. Class groups and their appropriate abstractions are declared in your configuration XML files in your module’s /etc/ folder.


Much like factory class abstraction and class groups in Magento, the Singleton pattern is instantiated for Blocks and Classes just the same.


The registry pattern is basically a pattern that allows any object or data to be available in a public global scope for any resource to use.


The Prototype pattern in Magento is used as an extension of the Abstract Factory pattern. It ensures that an appropriate subclass is instantiated via appropriate types that are assigned to an object. What does this mean? Basically, it means that whenever you need to get a specific class that is defined via its parent type, the prototype pattern ensures you get the right class that can handle what you need.

Object Pool

The Object Pool Pattern keeps objects ready for use over and over again instead of re-instantiating them and destroying them once finished. It is a great way to save on memory consumption and compute cycles.


The Iterator Pattern is a design pattern that allows an object traverse through the elements of another class. This allows you to specify an iterator and allow for multiple different sets of data to be passed without changing the underlying structure that allows the iteration.

Lazy Loading

Lazy Loading is a design pattern that delays the loading of an object until the time that the object is called upon. With Magento, they don’t utilize this with objects, but data.

Service Locator

The service locator is a design pattern that allows a user to get a service by encapsulating the process inside an abstraction layer. This allows the user to retrieve the appropriate or best service without knowing what that service is at runtime.


The Module Design Pattern is a form of modular programming that emphasizes the grouping of functionality of a program into independent, interchangeable modules.


The observer pattern is where an event listener is set at a certain point during an application’s execution. Other components of the application can “hook” into this event listener and execute their code during this point.

Active record

Objects are a representation of a row in the database table. These objects should have properties that reflect the columns representing the structure of the table, and methods to allow modifications of these properties in the database.

The use of the patterns by Magento.

The classes that inherit after Mage_Core_Model_Abstract class have access to load(), save() and delete() methods that allow loading, modification, creating or deleting records in a table that the class is connected with. Additionally, Mage_Core_Model_Abstract class inherits from Varien_Object, which gives us access to truly magical methods __set() and __get() that are responsible for automatic mapping of columns in a database table with the properties of a given object.

Above all also use in Magento 1


Magento 2 is an extension based or modular system, which allows a third-party developer to customize and overwrite core parts of its framework. These customization may lead to several issues, for example, it will become difficult for developers to keep track of customization done by external extensions. Thus to overcome this Magento comes up with service contract pattern. A service contract is a set of interfaces which act as a layer between an end user and business layer. Thus rather than directly exposing business logic for customization to end user, a layer called service contract comes in between.

Service contracts enhances the modularity of Magento. Helps merchants for easy upgrade of Magento and ensure well-defined and durable API that other external and Magento module implements.It also provides an easy way to expose business logic via REST or SOAP interfaces.


It consists of various patterns such as:- Dependency injection, Singleton, Factory, Abstract Factory, Composite, strategy, CQRS, Decorator and many more. We will discuss some most used patterns among these. Object manager has a very big role to play, Magento prohibits the direct use of it. Object manager is responsible for implementing factory, singleton and proxy patterns. It automatically instantiates parameter in class constructors.
Before moving further lets understand about injectable and non-injectable objects:-


They does not have their own identity such as EventManager, CustomerAccountManagementService.


These entities usually have their identities and state, since they have their identities it is important to know on which exact instance of entity we have to work.


It is an alternative to Mage in magento 1. It is a concept of injecting the dependent object through external environment rather than creating them internally. Thus we will be asking for resource when our object is being created instead of creating resource when needed. This helps in future modification and testing becomes very easy by mocking required objects.


In Magento 2 Factory classes create a layer between the object manager and business code. Factory classes does not needs to be defined explicitly as they are auto-generated. We should create factory classes for non-injectable objects.


Proxy classes are used to work in place of another class and in Magento 2 they are sometimes used in place of resource hungry classes. To understand what proxy classes do let’s see the reason which leads to the occurrence of proxy classes. As we know Magento uses constructor injection for object creation and when we instantiate an object all the classes in its constructor will also instantiate thus leading to a chain of instantiation via a constructor, this can really slow down the process and impact the performance of an application, so to stop chain instantiation Magento uses proxy classes.

Lets see following code:-


So in above code, we are using proxy classes for catalogProductStatus and productLink. When we run below mentioned command:

 php bin/magento setup:di:compile

Magento creates proxy classes on the fly using di.xml with some fixed conventions, thus replacing the original object with a proxy class object. Now let us look at our proxy class to understand how it works.

Some common convention Magento follow while creating proxy:-

Namespace of proxy class will be same as original (Magento\Catalog\Model\Product\Attribute\Source\Status)
Proxy class only extends one object i.e, object manager
Has magic functions such as __sleep, __wake which are invoked only on certain action and function such as __clone will make an object of original class and will provide the object only when it is needed (making use of lazy loading design pattern), thus improving the performance of application https://devdocs.magento.com/guides/v2.0/extension-dev-guide/proxies.html
Plugins (Interceptors)


A plugin, or interceptor, is a class that modifies the behavior of public class functions by intercepting a function call and running code before, after, or around that function call. This allows you to substitute or extend the behavior of original, public methods for any class or interface.

Extensions that wish to intercept and change the behavior of a public method can create a Plugin class which are referred to as plugins.

This interception approach reduces conflicts among extensions that change the behavior of the same class or method. Your Plugin class implementation changes the behavior of a class function, but it does not change the class itself. Because they can be called sequentially according to a configured sort order, these interceptors do not conflict with one another.


Plugins cannot be used with any of the following:

Final methods
Final classes
Non-public methods
Static methods
Virtual types
Objects that are instantiated before Magento\Framework\Interception is bootstrapped
Objects that are not instantiated by the ObjectManager (e.g. by using new directly). https://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html



Large applications, such as the Magento application, use an object manager to avoid boilerplate code when composing objects during instantiation.

In the Magento framework, the implementation of the ObjectManagerInterface performs the duties of an object manager.


The object manager has the following responsibilities:

– Object creation in factories and proxies
– Implementing the singleton pattern by returning the same shared instance of a class when requested
– Dependency management by instantiating the preferred class when a constructor requests its interface
– Automatically instantiating parameters in class constructors

Author: Qaisar Satti
Category: Magento 2
Last Modified: September 26, 2018

list all customer groups in Magento 2

Today we will learn how to list all customer group in magento 2. Getting the complete list of customers/users means displaying a list of all the customer groups including not logged in group as well.

So,you can get the complete list of customer groups,using following code:

Factory Method:

namespace QaisarSatti\Module\Block;

class Product extends \Magento\Framework\View\Element\Template

  protected $groupCollection;  

  public function __construct(
        \Magento\Customer\Model\ResourceModel\Group\CollectionFactory $groupCollection

    ) {

        $this->groupCollection = $groupCollection;
    public function getCustomerGroup()
        return $this->groupCollection->create()->toOptionArray();


Object Manager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$groupOptions = $objectManager->get('\Magento\Customer\Model\ResourceModel\Group\Collection')->toOptionArray();

        'name' => 'customer_group[]',
        'label' => __('Customer Group'),
        'title' => __('Customer Group'),
        'values' => $groupOptions,
        'disabled' => $isElementDisabled

One can also use the following class:


This class provides the


method which can be used to get an array of customer groups.

That’s it for this tutorial. I hope it will help you in a certain and easy way.

Author: Qaisar Satti
Category: Magento 2
Last Modified: October 2, 2018

Magento 2 admin panel Unable to sign in or Account temporarily disabled

Today we will discuss about how you can solve the issue of magento 2 admin panel unable to sign in or account temporarily disabled. This mainly occurs due to secure functionality of magento 2. Magento 2 have introduced account disabled functionality keeping in mind the security of business. if you tried the wrong password repeatedly in admin panel login. Then you account got locked and temporary disabled. There are various methods to do so but we will discuss few here.

Lets have a look at the first method, in which you will learn to unlock and access the root folder

Unlock admin user

One can unlock the temporarily disabled account by going to Magento 2 root folder SSH and running the
the following command:

php bin/magento admin:user:unlock admin

There is another way of solving this problem but that might work for some and might not work for others. But is worth giving a try.

By resetting the username and password

For doing so do the following

sudo php bin/magento admin:user:create --admin-user="pearlbells" --admin-password="pear122l**all" --admin-email="[email protected]" --admin-firstname="Admin" --admin-lastname="Admin"

As i told you earlier there are many ways but we just discussed few simple and efficient methods.I Hope they will serve the purpose ad be useful.

Author: Qaisar Satti
Category: Magento 2
Last Modified: September 26, 2018