:::: MENU ::::
Posts tagged with: frontend

Magento 2 get base directory

Today we discuss about Magento 2 get base directory .This tutorial include how to get base directory like media and other directories. There are two ways to do it. One is factory method and other is use object manager. So let start with our example.

Factory Method

In this example we will get base directory of media.

<?php
/**
* Simple Hello World Module
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email [email protected]
*
*/

namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $directoryList;

public function __construct(
\Magento\Framework\App\Filesystem\DirectoryList $directoryList
) {
    $this->directoryList=$directoryList
}
public function getbaseDir()
{
   return $this->_directorylist->getPath('media');

}

}

Object Manager

In this example we will get base directory of media. Using object manager is not recommended.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$dir = $objectManager->create('Magento\Framework\App\Filesystem\DirectoryList');
$mediaPath = $dir->getPath('media');
Author: Qaisar Satti
Category: Magento 2
Last Modified: August 20, 2018


Magento 2 call js css file homepage

Today we discuss about Magento 2 call js css file homepage.This tutorial include how to add js file on homepage, How to add css file on home.There are two way to add css or js file on homepage.You can add js or css file from admin or you can add file from layout. So let’s start with our example.

Admin Panel

You can add js or css file from admin panel.

content->page -> edit page in design tab Layout Update XML

Add following code.

   <head><script src="js/myfile.js"/></head>
   <css src="css/mystyle.css"/>

Layout File

Add Js

If you are adding js in your theme create cms_inde_index.xml in following path.

app/design/frontend/QaisarSatti/theme/Magento_Theme/layout/cms_inde_index.xml

myfile.js location will

app/design/frontend/QaisarSatti/theme/Magento_Theme/web/js

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head><link src="js/myfile.js"/></head>
</page>

If You want it to add from module xml then create cms_inde_index.xml in following path.

app/code/QaisarSatti/view/HelloWorld/frontend/layout/cms_inde_index.xml

myfile.js location will

app/code/QaisarSatti/view/HelloWorld/frontend/web/js

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head><link src="FME_GoogleMapsStoreLocator::js/myfile.js"/></head>
</page>

Add css

If you are adding cs in your theme create cms_inde_index.xml in following path.

app/design/frontend/QaisarSatti/theme/Magento_Theme/layout/cms_inde_index.xml

mystyle.css location will

app/design/frontend/QaisarSatti/theme/Magento_Theme/web/css

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head><link src="css/mystyle.css"/></head>
</page>

If you want it to add css from module xml then create cms_inde_index.xml in following path.

app/code/QaisarSatti/view/HelloWorld/frontend/layout/cms_inde_index.xml

mystyle.css location will

app/code/QaisarSatti/view/HelloWorld/frontend/web/css

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head><link src="FME_GoogleMapsStoreLocator::css/mystyle.css"/></head>
</page>
Author: Qaisar Satti
Category: Magento 2
Last Modified: August 7, 2018


Magento 2 create retrieve system configuration

Today we talk about how in Magento 2 create retrieve system configuration. This tutorial includes the knowledge of get value of system configuration, how to add your custom configurations in system configurations and also how to retrieve their values too. Configuration values are saved in core_config_data table , in this table you can see the path and value of your configuration settings. So let’s start with our example.

Create system.xml

First step is create system.xml in following directory.

QaisarSatti/HelloWorld/etc/adminhtml/

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
     <system>
            <tab id="qaisarsatti_helloworld" translate="label" sortOrder="200">
                <label>QaisarSatti HelloWorld</label>
            </tab>
        <section id="helloworld" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>HelloWorld COnfiguration</label>
            <tab>qaisarsatti_helloworld</tab>
            <resource>qaisarsatti_helloworld::config</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General</label>
                <field id="enabled" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Enabeld </label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="title" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Title</label>
                </field>                                            
            </group>
        </section>
    </system>
</config>

Retrieve System configuration

For retrieving the values we create the helper file Data.php in following directory

QaisarSatti/HelloWorld/Helper/Data.php

First thing you need to know for retrieving the values in is combination of sestionid/groupid/fieldid to get value.

<?php

namespace QaisarSatti\HelloWorld\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    const HELLOWORLD_MODULE_ENABLED    = 'helloworld/general/enabled';
    const HELLOWORLD_LABEL             = 'helloworld/general/title';



    public function __construct(
        \Magento\Framework\App\Helper\Context $context
    ) {
   
   
   
   
        parent::__construct($context);
    }
    public function getEnabled()
    {
        return $this->scopeConfig->getValue(
            self::HELLOWORLD_MODULE_ENABLED,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
    public function getLabel()
    {
        return$this->scopeConfig->getValue(
            self::HELLOWORLD_LABEL,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

Now: Following you can retrieve system configuration.

Author: Qaisar Satti
Category: Magento 2
Last Modified: August 6, 2018


Magento 2 shopping cart items subtotal grand total billing and shipping address

Today we talk about how in Magento 2 shopping cart items subtotal grand total billing shipping address. In this tutorial you will learn how to get data of shopping cart item detail example product name, product sku, price and quantity and cart total item count, cart item total quantity, cart subtotal, cart grand total also quote shipping address and quote billing address. There are two method of get the cart detail. One is inject the class \Magento\Checkout\Model\Session in your block and get data from it. Second is use the object manager to get data.

Dependency Injection

<?php
namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
 
    public $_checkoutSession;
 
    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,

    ) {
        $this->_checkoutSession = $checkoutSession;
 
    }
 
}

Get cart information in phtml file.

//Get session object in phtml file
$getCurrentQuote = $block->_checkoutSession()->getQuote();
$getAllitems = $getCurrentQuote->getAllItems();
 
foreach($getAllitems as $item) {
    echo 'Product Id: ' . $item->getProductId() . '<br />';
    echo 'Name: ' . $item->getName() . '<br />';
    echo 'Sku: ' . $item->getSku() . '<br />';
    echo 'Quantity: ' . $item->getQty() . '<br />';
    echo 'Price: ' . $item->getPrice() . '<br />';
    echo "<br /><br />";
}
 
// Get cart total items and total quantity
$totalItems = $getCurrentQuote->getItemsCount();
$totalQuantity = $getCurrentQuote->getItemsQty();
 
//get cart subtotal and grand total
$subTotal = $getCurrentQuote->getSubtotal();
$grandTotal = $getCurrentQuote->getGrandTotal();
 
//get cartbilling and shipping addresses
$billing = $getCurrentQuote->getBillingAddress();
$shipping = $getCurrentQuote->getShippingAddress();

Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$getCurrentQuote = $objectManager->get('\Magento\Checkout\Model\Session');

$getAllitems = $getCurrentQuote->getAllItems();
 
foreach($getAllitems as $item) {
    echo 'Product Id: ' . $item->getProductId() . '<br />';
    echo 'Name: ' . $item->getName() . '<br />';
    echo 'Sku: ' . $item->getSku() . '<br />';
    echo 'Quantity: ' . $item->getQty() . '<br />';
    echo 'Price: ' . $item->getPrice() . '<br />';
    echo "<br /><br />";
}
 
// Get cart total items and total quantity
$totalItems = $getCurrentQuote->getItemsCount();
$totalQuantity = $getCurrentQuote->getItemsQty();
 
//get cart subtotal and grand total
$subTotal = $getCurrentQuote->getSubtotal();
$grandTotal = $getCurrentQuote->getGrandTotal();
 
//get cartbilling and shipping addresses
$billing = $getCurrentQuote->getBillingAddress();
$shipping = $getCurrentQuote->getShippingAddress();
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 redirect user from observer to custom controller

Today we talk about how in Magento 2 redirect user observer custom controller. This tutorial includes example of redirect user from observer. Using this example you can redirect from block, helper and model . You need to inject \Magento\Framework\App\Response\Http class to make the redirection from anywhere.So let’s start with our example.

<?php
namespace QaisarSatti\HellowWorld\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;
class [YourClass] implements ObserverInterface {

   protected $_redirect;
   protected $_url;
   public function __construct(


       \Magento\Framework\UrlInterface $url,
       \Magento\Framework\App\Response\Http $redirect,

   ) {

       $this->_url = $url;
        $this->_redirect = $redirect;

    }
    public function execute(Observer $observer) {
             $event = $observer->getEvent();
             $CustomRedirectionUrl =          $this->_url->getUrl('test/test/test');
             $this->_redirect->setRedirect($CustomRedirectionUrl);

    }
}

Note: You can use this example with any observer event.

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


Magento 2 remove page title

Today we talk about how in Magento 2 remove page title. In this tutorial we will learn how to remove page title that are shown under top menu navigation. We will remove the page title by xml layout file. If you want to remove on all page create a default.xml or you want to remove title for a specific page for example product view page catalog_product_view.xml. So let’s start with our example to remove for all pages.

Remove Title From all Pages in Module

First create the default.xml in QaisarSatti/HelloWorld/view/frontend/layout/

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="page.main.title" remove="true" />
    </body>
</page>

Remove Title From all Pages in Theme

First create the default.xml in QaisarSatti/theme/Magento_Theme/layout/

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="page.main.title" remove="true" />
    </body>
</page>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 event observer

Today we talk about how in Magento 2 event observer. This tutorial included observing event sales_order_save_commit_after. Following this example you can observe any event in magento 2. So let start with our example.

Create event.xml

First create the events.xml in QaisarSatti/HelloWorld/etc/events.xml. If you want to observe the event that trigger only the frontend you create events.xml file QaisarSatti/HelloWorld/etc/frontend/events.xml. Same as you want to observe the events that trigger in admin side create file QaisarSatti/HelloWorld/etc/adminhtml/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_save_commit_after">
        <observer name="helloworld_sales_order_save_after" instance="QaisarSatti\HelloWorld\Observer\Observer" />
    </event>
</config>

Create Observer.php

Now we create Observer.php in following directory QaisarSatti\HelloWorld\Observer. Inject \Magento\Framework\Event\Observer in your method to get event data.

<?php
namespace QaisarSatti\HelloWorld\Observer;
use Magento\Framework\Event\ObserverInterface;
 
class Observer implements ObserverInterface {
  public function execute(\Magento\Framework\Event\Observer $observer) {
                 $order = $observer->getEvent()->getOrder(); //get order information      
    }
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Pages:1234