:::: MENU ::::
Posts tagged with: magento 2

Get all module list in Magento 2

This tutorial is about Get all module list in Magento 2 .i.e how to get all module or extension list in magento 2. Also the status, whether it’s enable or disabled. I assume your question is,how to get it? And in this tutorial i will try to explain it briefly and also make it convenient.

There are few ways to achieve it. We will discuss few here.

Lets start with a method, in which we can get the desired result using CLI command.

Using CLI command

There is a CLI command

bin/magento module:status

which returns the list of enabled and disbaled modules. Check the below given path to know how it’s done.

\Magento\Setup\Console\Command\ModuleStatusCommand::execute

Basically

\Magento\Framework\Module\ModuleList::getNames

returns you a list of enabled modules. Similarly

\Magento\Framework\Module\FullModuleList::getNames

returns you a full list of all modules.Furthermore we will have to do an array_diff() to get the disabled modules.

Secondly we can take help from Magento’s core codebase.

Magento Corebase

Since we already discuss the command that lists all modules:

php bin/magento module:status

Let me share with you that magento uses

\Magento\Framework\Module\FullModuleList

class to get the list of enabled and disabled modules.

Based on Magento’s implementation, I have implemented my code in the following way:

<?php
namespace QaisarSatti\HelloWorld\Block;

class Modules extends \Parent\Class
{
    protected $fullModuleList;

    public function __construct(
        \Other\Dependenciy\Classes,
        \Magento\Framework\Module\FullModuleList $fullModuleList
    ) {

        $this->fullModuleList = $fullModuleList;
    }

    public function modulesList()
    {
        ...
        $allModules = $this->fullModuleList->getAll();
        ...
    }
}

I hope it is quite efficient and fulfill its use.

Furthermore there are another two ways to get this done.

Lets have a look at the them respectively.

1.

Following code will give the enabled and disabled modules list. I have commented the code to make it easy to understand what the code is doing.

protected $fullModuleList;
protected $moduleManager;

public function __construct(
    ...................
    \Magento\Framework\Module\FullModuleList $fullModuleList,
    \Magento\Framework\Module\Manager $moduleManager,
    ...................
) {

    $this->fullModuleList = $fullModuleList;
    $this->moduleManager = $moduleManager;
}

public function yourFunction()
{
    ...
    $allModules = $this->fullModuleList->getAll();
    $listOfModules = [];
    foreach ($allModules as $key => $value) {
        $listOfModules[] = $key;
    }
    foreach ($listOfModules as $key => $value) {
        if ($this->moduleManager->isEnabled($value)) {
            echo $value; //Enable Module List
        } else {
            echo $value; //Disable Module List
        }
    }
    ...
}
Similarly the second method is as follows.<strong>
2.</strong>

protected $fullModuleList;
protected $moduleList;

public function __construct(
    ...................
    \Magento\Framework\Module\FullModuleList $fullModuleList,
    \Magento\Framework\Module\ModuleList $moduleList,
    ...................
) {

    $this->fullModuleList = $fullModuleList;
    $this->moduleList = $moduleList;
}

public function yourFunction()
{
    ...
    $allModules = $this->fullModuleList->getNames(); //List of All Module Names
    $enabled_list = $this->moduleList->getNames(); //List of Enabled Module Names
    $disabled_list = array_diff($enabled_list, $allModules); //List of Disabled Module Names

That’s it from this tutorial. I hope it serves the purpose.
Since these are learning tutorials,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: November 9, 2018


Magento 2 after save and before save method

This tutorial is about Magento 2 after save and before save method .i.e how to use after save and before save methods in magento 2.I assume you want to add after save and before save method of Magento 2 in your model.So, how can we do this?. This tutorial will tell us,how we can do that?

Magento is a flexible platform and it covers almost all the basic and necessary functionalities. Magento has its own _beforeSave and _afterSave functions. You can use them in your ResourceModel using below code.

Before Save

_beforeSave function called when you tried to update or insert data in database table with your model. Then _beforeSave function is called. You can implement you logic like validation, Post data change or any other functionality you want perform.

<?php
    namespace QaisarSatti\HelloWorld\Model\ResourceModel;
    class Test extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb  {

        protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
        {
            // do your logic here

        }

 

    }

After Save

_afterSave function called when After update or insert data in database table with your model. Then _afterSave function is called. You can implement you logic like sending email, Add related data or any other functionality you want perform.

<?php
    namespace QaisarSatti\HelloWorld\Model\ResourceModel;
    class Test extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb  {

       protected function _afterSave(\Magento\Framework\Model\AbstractModel $object)
        {  
          //do your logic here
        }

    }

That’s it from this tutorial. I hope it serves the purpose.
Since these are learning tutorials,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: November 9, 2018


Magento2 load Customer by Id

This tutorial is about Magento 2 Load Customer by Id. I assume the question arises is What is the best way to load Customer by Id?. And how can we do it?.Furthermore,there are different ways in magento 2, to do so.

Like we can do so using customer interface or customer factory.

Like i said there are many ways,But the best practice is to use service contracts.

Api Repository:

In my case i would use

\Magento\Customer\Api\CustomerRepositoryInterface

Similarly use the below code.

protected $_customerRepositoryInterface;
public function __construct(
    ....
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
    ....
) {
    ....
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
}

Furthermore call this function in your code like:

$customerId = 1;
$customer = $this->_customerRepositoryInterface->getById($customerId);

Factory Method:

namespace QaisarSatti\Module\Block;

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

  protected $customer;  


  public function __construct(
     
        \Magento\Customer\Model\Customer $customer

    ) {


        $this->customer = $customer;
     
    }
    public function getLoadProduct()
    {
        $customer_id=7;
        return $this->customer->create()->load($customer_id);
    }

}

Object Manager:

No recommended method to use in magento2 but so magento use it so here it is just for knowledge.

$customer_id=7;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerData = $objectManager->create('Magento\Customer\Model\Customer')->load($customer_id);

That’s it from this tutorial. I hope it serves the 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: November 18, 2018


Magento 2.3 new features

Today we will talk about magento 2.3 new features. Though the magento version 2.3 is not released yet,but magento is planning to release it by the end of this year.During its imagine conference magento announced its plans for the upcoming Magento 2.3 release.Like every major release, there are various exciting features that are set to bring new opportunities for magento clients to sell to their customers, as well as notable back-end efficiencies.

In this article we will look at new features of an enhanced version.i.e magento 2.3.

Magento 2.3 new features

We will have a brief look at the new features and improvements.

PWA

A Progressive Web App is an application,built to take advantage of modern technology features. It provides the feature of caching of data so the website can be used (partially or fully) in an offline mode when internet service is unavailable.
Magento recognizes the multiple benefits to this, and in late 2017 announced its efforts in building what it calls the PWA Studio. PWA Studio will contain tools to develop and deploy a PWA for Magento’s front end. Along with PWA Studio will come a lightweight (not feature-full) demo site. The immediate benefits will be a major increase in front-end performance and a close to 10X increase in speed of onboarding new Magento front-end developers.

GraphQL

GraphQL is a query language for using APIs. With advancement in PWA,it is the need of the hour to get smaller amounts of data and to make fewer API requests.GraphQL’s query language makes this possible by allowing the requestor to request a limited subset of attributes to be returned about an entity (significantly smaller responses) and allows you to chain requests (smaller number of requests).

Magento currently supports REST and SOAP API requests that use Service Contracts. However, to support GraphQL,Magento is writing an entirely new layer that interfaces directly to the Query API. The GraphQL implementation will be the underpinnings on how a PWA frontend will retrieve the data it needs.

Declarative Database Schema

Until now the to change the schema of magento database, you can do that using InstallSchema and UpgradeSchema classes where code is written to modify the schema.

Furthermore Magento 2.3 will change the recommended way by implementing a declarative database schema. This technique will try to accomplish multiple goals, some of which were discussed here. Instead of the database schema definitions being fragmented throughout many install and upgrade scripts, it will be fully defined via XML.

Multi-Source Inventory (MSI)

Magento is introducing multi-source inventory management to Magento’s core.This will let merchants to natively manage inventory via multiple sources.This will also enhance the shipping methods like the shipping of items and tracking of stock levels from multiple warehouses,as well as inventory within retail stores to support “ship from store” and “pick up in store”.
Furthermore Magento 2.3 will also include new functionality around the reservation mechanism of inventory. Inventory is now reserved within a new table structure instead of the direct decrementing of stock. This will increase performance and prevent database unnecessary locking during the order.

Asynchronous API

The Asynchronous WebAPI allows a system to execute API calls asynchronously against the Magento REST API.Because of this, integrations don’t have to wait for requests to fully process when making the calls. This improves the performance of integrations that require many API calls, such as a bulk product integration or customer import. A separate status reporting API will be available to check on the progress of the request by ID. This functionality will be available in both Magento Commerce 2.3 and Magento Open Source.

Page Builder

One of the most amazing and waited for feature of magento is Magento’s native CMS.Magento purchased the Blue Foot CMS technology from Gene Commerce and has made that available to its Magento Commerce merchants. Page Builder is a rewrite of Blue Foot CMS using much of the same foundational features and concepts. These features include template creation, drag-and-drop layout management, and a UX that is clean and friendly to use for a non-technical user.
Page Builder will come natively with Magento Commerce 2.3 and will be available for purchase inside the Magento Marketplace for Open Source implementations.

2FA

Magento 2.3 will have enhanced security.To protect against malicious users that have obtained a password,in any way magento is implementing two-factor authentication. This extra layer of security will require a user to prove that they have access by sending a security code to their phone or email.Similar to many web applications as it is already implemented across the globe extensively.

Message Queue

Support for message queuing is being extended from Magento Commerce to Magento Open Source. Message queues enable asynchronous communication between systems.

ElasticSearch

Support for ElasticSearch is being extended from Magento Commerce to Magento Open Source. ElasticSearch, in addition to many other usages, powers Magento’s site search capabilities, including faceted search (filtering by attributes).

PHP 7.2

PHP 7.2 brings new development features, as well as an increase in performance and security.

Libsodium

Because 7.2 is dropping support for mcrypt (PHP’s go to encryption module), the libsodium module will now be used for encryption.

Import/Export Improvements

Through community engineering, many improvements in speed and usability of import/export functionality are being added to the Magento core.

Contact DEG to learn how our customized ecommerce solutions can boost engagement and improve your conversion rate.

Cache Management ACL

Magento is adding fine-grained administration access control around the ability to interact with the system cache. Caching provides a much-needed layer of performance for Magento, and in the wrong hands, performance can dramatically suffer.

Google reCAPTCHA

Magento is switching the technology used for proving that users are humans, not bots, when interacting with a site. Google’s reCAPTCHA tool will now come native.

So after knowing that what will magento 2.3 bring in, it seems really a hard worked and enhanced version.And certainly it will bring more flexibility and versatile features in magento.

Right then this article is purely informational.I hope it will serve its purpose.I am always open to queries and suggestions. Please feel free to drop any.

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


Magento 2 Get base url in js

This tutorial is about magento 2 Get base url in js file. 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 to get base url from js file in magento 2. Above all if you are not familiar with advance magento concepts and are looking for basics,please look for magento 2 basic tutorials.

So lets start our tutorial and focus on our topic. For example if you want to get base url from .js file and append it with your module controller link from. How can we do it? It is almost impossible to use block to get the base url.

Get base url

So we will look at the way how we can get base url. to do that,paste the following code in your routes.xml file

define([

   'mage/url'
], function (url) {

  var linkUrl = url.build('test/test/test');
  console.log(linkUrl);
});

Where frontname is your routes.xml file frontname.

Since it is necessary,you have to pass your frontname from routes.xml file instead of module name(namespace_module).

Furthermore you can lookup your routes.xml file from

app/code/QaisarSatti/HelloWorld/etc/frontend/routes.xml

It might work for some and might not for others.

Further more Add this code in phtml file:

<input type="hidden" value="<?php echo $this->getUrl(); ?>" id="baseUrl"/>

having done that you can use this base url in js file by id :

$("#baseUrl").val();

It is a quite useful and tested trick. So i thought to share it.

There is another approach for this task.Having said that it may too be useful.

You should pass url to js(widget).Url is a parameter of js widget.And put script below to your template where you want to.

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "yourWidget": {
                    "dataUrl": "<?php echo $block->getBaseUrl(); ?>"
                }
            }
        }
    }
}
</script>

Similarly in javascript widget, you can access to dataUrl by below code.

define(['uiComponent'], function(Component) {
    'use strict';

    return Component.extend({
        initialize: function() {
            console.log(this.dataUrl);
        }
    });
});

Another simple approach is

<script>
window.testUrl = <?php echo json_encode($block->getBaseUrl()); ?>
</script>

Using your custom js you can have easy access to window.testUrl global variable.

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:

$block->doSomething()

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:

$this->helper('QaisarSatti\HelloWorld\Helper\Data')

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:

/var/www/html/magento2/app/code/QaisarSatti/HelloWorld/Block/Test.php

  <?php
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

/var/www/html/magento2/app/code/QaisarSatti/HelloWorld/view/frontend/templates/homehorizontalwidget.phtml

you can modify:

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

Furthermore in

/var/www/html/magento2/app/code/QaisarSatti/HelloWorld/Helper/Data.php

. we can use below code:

<?php
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

/var/www/html/magento2/app/code/QaisarSatti/HelloWorld/etc/adminhtml/system.xml

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

<?php
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.

<?php
$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


Pages:1234567...15