:::: MENU ::::
Monthly Archives: September 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="pearl@gmail.com" --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