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

Magento 2 Send Email Programmatically

This tutorial is about Magento 2 Send email programmatically,functionality of Magento 2.We will discuss how we can send email programmatically in Magento 2.People often ask whether Magento 2 have any built-in integration with third-party transaction email delivery systems like Amazon SES, Mandrill, etc., or is the built-in email functionality still based around PHP’s mail function? Or the emails sent with some third party software? Also, people ask are there any third party extensions like SMTP Pro for Magento 2 that would let a developer replace the standard email system?

Here we will discuss how it actually is done. After thorough research and digging of Magento 2 codebase for strings such as ’email’, ‘message’, etc until I found something that sends out an email. I stumbled upon sendPaymentFailedEmail() in

vendor/magento/module-checkout/Helper/Data.php

This sets a lot of variables but eventually ties them to a transport object, which is created through a ‘transportBuilder’. This transportBuilder is an instance of

\Magento\Framework\Mail\Template\TransportBuilder

In that file a

$transport

variable exists, which is an instance of

\Magento\Framework\Mail\TransportInterface

Because there is an interface,there is also a regular class called

\Magento\Framework\Mail\Transport

. When we open the file

vendor/magento/framework/Mail/Transport.php

we see that this extends

Zend_Mail_Transport_Sendmail

.

It actually look like this

class Transport extends \Zend_Mail_Transport_Sendmail implements \Magento\Framework\Mail\TransportInterface

So using DI, you’ll be able to replace this transport with another email framework instead of Zend_Mail, such as Mandrill or Amazon SES.

Just be sure to include the send() method since that is the method called in sendMessage().

public function sendMessage()
{
    try {
        parent::send($this->_message);
    } catch (\Exception $e) {
        throw new \Magento\Framework\Exception\MailException(new \Magento\Framework\Phrase($e->getMessage()), $e);
    }
}

Furthermore, there are assumptions about PHPs mail() being outdated and not supporting any 3rd party services.But it is not correct, as every good 3rd party service supports an SMTP interface, and so does mail() too.Also, Amazon SES does support SMTP.

Similarly, there is another simple and easy method to send the email. Magento 2 TransportBuilder uses email templates to compose email’s body. You can send plain text simply using – Zend1 mail

$email = new \Zend_Mail();
        $email->setSubject("Feedback email");
        $email->setBodyText($body);
        $email->setFrom($from, $nameFrom);
        $email->addTo($to, $nameTo);
        $email->send();

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 the comments section. That will be highly appreciated surely.

Author: Qaisar Satti
Category: Magento 2
Last Modified: February 4, 2019


Magento 2 Create Yes No Attribute Programmatically

This tutorial is about Create Yes No Attribute Programmatically 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. Creating Yes No attributes programmatically in Magento 2 is explained below. Let’s have a look at how we can do this.

Here I am creating the upgradeData script that will add custom product attribute with yes and no options.

<?php
 namespace QaisarSatti\HelloWorld\Setup;

 use Magento\Eav\Setup\EavSetup;
 use Magento\Eav\Setup\EavSetupFactory;
 use Magento\Framework\Setup\UpgradeDataInterface;
 use Magento\Framework\Setup\ModuleContextInterface;
 use Magento\Framework\Setup\ModuleDataSetupInterface;

class upgradeData implements UpgradeDataInterface {
 private $eavSetupFactory;
 protected $logger;

public function __construct(EavSetupFactory $eavSetupFactory,\Psr\Log\LoggerInterface $logger) {
 $this->eavSetupFactory = $eavSetupFactory;
 $this->logger = $logger;
 }

public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
 
 
 $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
 $eavSetup->addAttribute(
 \Magento\Catalog\Model\Product::ENTITY,
 'subscripion_product',[
 'type' => 'text',
 'backend' => '',
 'frontend' => '',
 'label' => 'Enable Subscription',
 'input' => 'select',
 'class' => '',
 'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
 'visible' => true,
 'required' => true,
 'user_defined' => false,
 'default' => '',
 'searchable' => false,
 'filterable' => false,
 'comparable' => false,
 'visible_on_front' => false,
 'used_in_product_listing' => true,
 'unique' => false,
 'apply_to' => ''
 ]
 );
 
 
 }
 
 }

That’s it from this tutorial. I strongly believe there is always room for improvement. So I am open to any suggestion and feedback. Please feel free to leave hat you are thinking in the comments section below. Cheers.

Author: Qaisar Satti
Category: Magento 2
Last Modified: February 4, 2019


Get base url current url in Magento 2

This tutorial is about Get base URL,current URL in Magento 2 .i.e how to get base URL current URL in Magento 2. you can also get media url and any custom url following this example. And in this tutorial, I will try to explain it briefly and in a simple way. I will share the code snippet below.

Get base url and current url in Magento 2

First lets note down the steps.

Step 1: Declare in (your module name)_HelloWorld
Step 2: Get current URL and base URL in the template (.phtml) file

Moving forward let us explain these steps step by step.

Declare in (your module name)_HelloWorld

You will use a block class of the module (your module name)_HelloWorld, then possibly inject the object of StoreManagerInterface and UrlInterface in the constructor of the module’s block class. You will work with two functions in the below class: getStoreManagerData() and getUrlInterfaceData().

  • In getStoreManagerData() function, you will use object of StoreManagerInterface to get the base and current url.
  • In getUrlInterfaceData() function, you will use object of UrlInterface to get the base and current url
  • .

    Open app/code/QaisarSatti/HelloWorld/Block/HelloWorld.php class and run the code:

    <?php
    namespace QaisarSatti\HelloWorld\Block;
    class HelloWorld extends \Magento\Framework\View\Element\Template
    {
            protected $_storeManager;
            protected $_urlInterface;
     
        public function __construct(
            \Magento\Store\Model\StoreManagerInterface $storeManager,
            \Magento\Framework\UrlInterface $urlInterface,    
        )
        {        
            $this->_storeManager = $storeManager;
            $this->_urlInterface = $urlInterface;
        }
       
       
       
        /**
         * Printing URLs using StoreManagerInterface
         */

        public function getStoreManagerData()
        {    
            echo $this->_storeManager->getStore()->getId() . '<br />';
           
            // by default: URL_TYPE_LINK is returned
            echo $this->_storeManager->getStore()->getBaseUrl() . '<br />';        
           
            echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB) . '<br />';
            echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK) . '<br />';
            echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . '<br />';
            echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC) . '<br />';
           
            echo $this->_storeManager->getStore()->getUrl('product/33') . '<br />';
           
            echo $this->_storeManager->getStore()->getCurrentUrl(false) . '<br />';
               
            echo $this->_storeManager->getStore()->getBaseMediaDir() . '<br />';
               
            echo $this->_storeManager->getStore()->getBaseStaticDir() . '<br />';    
        }
       
        /**
         * Printing URLs using URLInterface
         */

        public function getUrlInterfaceData()
        {
            echo $this->_urlInterface->getCurrentUrl() . '<br />';
           
            echo $this->_urlInterface->getUrl() . '<br />';
           
            echo $this->_urlInterface->getUrl('helloworld/general/enabled') . '<br />';
           
            echo $this->_urlInterface->getBaseUrl() . '<br />';
        }  
    }
    ?>

    Step 2:

    Get base URL and current URL in the template file

    Use the following piece of code:

    <?php echo $block->getUrl('hello/test'); ?>
    <?php echo $block->getBaseUrl(); ?>

    Furthermore, 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 the comments section. That will definitely be highly appreciated.

    Author: Qaisar Satti
    Category: Magento 2
    Last Modified: February 4, 2019


    Install magento 2 command line interface (CLI)

    This tutorial is about Install magento 2 command line interface (cli). Often i have faced little bit of trouble while installing magento or upgrading to a newer version. Also many people complain and ask about to how to install magento via command line.So here, we will discuss particularly about magento 2 version on any system. It is quite a simple process.We will discuss one or two methods here.So moving forward, lets have a look.

    So it can be done using a command which is as follows:

    php bin/magento setup:install --backend-frontname="admin" --key="admin" --session-save="files"
     --db-host="localhost" --db-name="magento2" --db-user="root" --db-password="root"
    --base-url="http://127.0.0.1/magento2/" --base-url-secure="https://127.0.0.1/magento2/"
     --admin-user="admin" --admin-password="admin123" --admin-email="[email protected]"
    --admin-firstname="Qaisar" --admin-lastname="Satti" --use-rewrites=1

    If you want to add extra setting in installation you can add language currency time zone and etc with adding following parameters.

    --language=en_US
    --currency=USD --timezone=America/Chicago

    That’s it from this tutorial. I strongly believe there is always room for improvement.So i am open for any suggestion and feed back. Please feel free to leave what you are thinking in the comments section below. Cheers.

    Author: Qaisar Satti
    Category: Magento 2
    Last Modified: January 1, 2019


    Magento 2 Color Picker in system configuration

    This tutorial is about addingColor Picker in Magento 2 admin configuration. In this article I will show how to add jquery color picker in Magento 2 system configuration. You can use following step to use this jquery color picker on frontend too. Magento 2 have default lib/web/jquery/colorpicker/js/colorpicker library so you don’t have to add any external library for that. Below are the steps of how to do it:

    Lets start with the Image to demonstrate you what it looks like:

    Magento 2 color picker

    Magento 2 color picker

    Here my Module Namespace is QaisarSatti.
    And my module name is: HelloWorld

    Lets have have a look at different steps below:

    1. Create system.xml at app/code/QaisarSatti/HelloWorld/etc/adminhtml/system.xml
    All admin config options for your module will go in this file. For color picker we will create a text field as below. Just for your information i have not added complete code here for sake of readability.

        <field id="color_background" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
             <label>Background Color</label>
             <frontend_model>QaisarSatti\HelloWorld\Block\ColorPicker</frontend_model> <!-- block for adding color picker on text box -->
         </field>

    2. Create the QaisarSatti\HelloWorld\Block\ColorPicker.php
    This code will enable color picker options with the text box.

    <?php

    namespace QaisarSatti\HelloWorld\Block;

    class Color extends \Magento\Config\Block\System\Config\Form\Field {

       
        public function __construct(
        \Magento\Backend\Block\Template\Context $context, array $data = []
        ) {
            parent::__construct($context, $data);
        }

        protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) {
            $html = $element->getElementHtml();
            $value = $element->getData('value');

            $html .= '<script type="text/javascript">
                require(["jquery","jquery/colorpicker/js/colorpicker"], function ($) {
                    $(document).ready(function () {
                        var $currentelement = $("#'
    . $element->getHtmlId() . '");
                        $currentelement.css("backgroundColor", "'
    . $value .'");  //adding already selected value

                        // Attach the color picker
                        $currentelement.ColorPicker({
                            color: "'
    . $value .'",
                            onChange: function (hsb, hex, rgb) {
                                $el.css("backgroundColor", "#" + hex).val("#" + hex);
                            }
                        });
                    });
                });
                </script>'
    ;
            return $html;
        }

    }

    Now
    3. Add the color picker JavaScript library.
    Now finally we need to add color picker JavaScript library to admin config pages. Magento 2 by default is shipped with Color picker jQuery plugin. This plugin is present in lib/web/jquery/colorpicker/ folder.
    Create the app/code/QaisarSatti/HelloWorld/view/adminhtml/layout/adminhtml_system_config_edit.xml. This layout file will be called on all admin configuration pages. We will add our color picker JavaScript and CSS to this layout.

    <!-- File: app/code/QaisarSatti/HelloWorld/view/adminhtml/layout/adminhtml_system_config_edit.xml -->

    <?xml version="1.0" encoding="UTF-8"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
        <head>
            <css src="jquery/colorpicker/css/colorpicker.css"/>
        </head>
    </page>

    Now clear the cache and refresh the page. You will see the color picker enabled in config option.

    That’s it from this tutorial. I strongly believe there is always room for improvement.So i am open for any suggestion and feed back. Please feel free to leave hat you are thinking in the comments section below. Cheers.

    Author: Qaisar Satti
    Category: Magento 2
    Last Modified: December 27, 2018


    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


    Pages:1234567...16