:::: MENU ::::
Posts tagged with: phtml

Cookie in magento 2

This tutorial is about Use or Set cookie in magento 2. i.e how to set or use cookie in magento 2?. Suppose you want to set a value to the cookie in a phtml file and need to get it’s value in another phtml file.

There are many ways in magento 2.I will try to discuss some in this tutorial.
Certainly magento uses jquery and it is possible to set and get the values using jQuery.

First of all lets have a look at our first setp. i.e

Set the cookies

You can set the cookies using below code:

<script>
    require([
        'jquery',
        'mage/cookies'
    ], function ($) {
       $.cookie('cookie_name', 'value', { path: '/' });//Set the cookies
    });
</script>

Please note that if you want to get the value from another page, notice the path setting { path: ‘/’ }!

Because cookies are only accessible to the specified path and any subpaths.

Similarly to get cookies:

Get Cookies

<script>
    require([
        'jquery',
        'mage/cookies'
    ], function ($) {
        var temp = $.cookie('cookie_name');//Get the cookies
    });
</script>

Similarly another piece of code is as below:

<script>
    require(
        [ 'jquery'],function($){
            //set cookie
            $.cookie('customname', 'customvalue', { expires: 365, path: '/' });

            //get cookie
            getCookieValue(customname)
        });

        function getCookieValue(cookiename) {
                var name = cookiename + "=";
                var cookieSplit = document.cookie.split(';');
                for(var i = 0; i <cookieSplit.length; i++) {
                    var a = cookieSplit[i];
                    while (a.charAt(0)==' ') {
                        a = a.substring(1);
                    }
                    if (a.indexOf(name) == 0) {
                        return a.substring(name.length,a.length);
                    }
                }
                return "";
            }
</script>

Furthermore there are other way too to do so. I am going to discuss them below. Wil try to keep it short and precise.

Create Cookie

Create a test controller to create:

app/code/QaisarSatti/HelloWorld/Controller/Cookie/Addcookie.php

<?php
namespace QaisarSatti\HelloWorld\Controller\Cookie;
class Addcookie extends \Magento\Framework\App\Action\Action
{
const COOKIE_NAME = 'test';
const COOKIE_DURATION = 86400; // lifetime in seconds
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface
*/

protected $_cookieManager;
/**
* @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
*/

protected $_cookieMetadataFactory;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
* @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
*/

public function __construct(
     \Magento\Framework\App\Action\Context $context,
     \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
     \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
)
{
     $this->_cookieManager = $cookieManager;
     $this->_cookieMetadataFactory = $cookieMetadataFactory;
     parent::__construct($context);
}
public function execute()
{
     $metadata = $this->_cookieMetadataFactory
         ->createPublicCookieMetadata()
         ->setDuration(self::COOKIE_DURATION);
     $this->_cookieManager->setPublicCookie(
         self::COOKIE_NAME,
         'YOUR COOKIE VALUE',
         $metadata
     );
     echo('Create Cookie');
}
}

Similarly to Read cookie

Read Cookie

Create a Readcookie.php controller to read cookie

app/code/QaisarSatti/HelloWorld/Controller/Cookie

<?php
namespace QaisarSatti\HelloWorld\Controller\Cookie;
class Readcookie extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface
*/

protected $_cookieManager;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
*/

public function __construct(
     \Magento\Framework\App\Action\Context $context,
     \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
)
{
     $this->_cookieManager = $cookieManager;
     parent::__construct($context);
}
public function execute()
{
     $cookieValue = $this->_cookieManager->getCookie(\[Name_Space]\[Your_Module]\Controller\Cookie\Addcookie::COOKIE_NAME);
     echo($cookieValue);
}
}

Furthermore Delete Cookie.

Delete Cookie

Create a Deletecookie.php controller to create cookie.

<?php
namespace QaisarSatti\HelloWorld\Controller\Cookie;
class Deletecookie extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface
*/

protected $_cookieManager;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
*/

public function __construct(
     \Magento\Framework\App\Action\Context $context,
     \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
)
{
     $this->_cookieManager = $cookieManager;
     parent::__construct($context);
}
public function execute()
{
     $this->_cookieManager->deleteCookie(
         \[Name_Space]\[Your_Module]\Controller\Cookie\Addcookie::COOKIE_NAME
     );
     echo('DELETED');
}
}

Hence above mentioned steps are the shortest process for you to Use Cookie in Magento 2. I have tried to provide you the code with simple logic.

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: October 22, 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


Magento 2 get media path

Today we discuss about Magento 2 get media path .This tutorial include how to get media path in your block or phtml file. 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 media path. First your need to inject \Magento\Store\Model\StoreManagerInterface.

<?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 $storeManager;

public function __construct(
   
    \Magento\Store\Model\StoreManagerInterface $storeManager,
   
) {
   
    $this->storeManager = $storeManager;
   
}

public function getMediaUrl()
{
    return $mediaUrl = $this->storeManager
                     ->getStore()
                     ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
   
}


}

Object Manager

In this example we will get media path. Using object manager is not recommended.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
echo $objectManager->get('Magento\Store\Model\StoreManagerInterface')
                    ->getStore()
                    ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
Author: Qaisar Satti
Category: Magento 2
Last Modified: August 20, 2018


Magento 2 check if customer logged in or not

Today we talk about how in Magento 2 check if customer logged in or not. This tutorial includes check if customer logged in or not.Magento 2 use the model session for storing the current customer session data like customer id, customer email, customer name and other customer information. You have to inject \Magento\Customer\Model\Session to get current customer session data. So let start with our example.

Dependency Injection

protected $_customerSession;



public function __construct(
           
        \Magento\Customer\Model\Session $customerSession,

    ) {


        $this->_customerSession = $customerSession;

    }

public function getGroupId(){
 if($this->_customerSession->isLoggedIn()):
   //Get current group
         echo $this->_customerSession->getCustomer()->getId();  // get customer id
         echo $this->_customerSession->getCustomer()->getName();  // get  customer Full Name
         echo $this->_customerSession->getCustomer()->getEmail(); // get customer Email
else:

   echo “no logged in”;            


endif;

}

Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');

if ($customerSession->isLoggedIn()):
   //Get current group
         echo $this->_customerSession->getCustomer()->getId();  // get customer id
         echo $customerSession->getCustomer()->getName();  // get  customer Full Name
         echo $customerSession->getCustomer()->getEmail(); // get customer Email
else:

   echo “no logged in”;            


endif;
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 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: September 26, 2018


Magento 2 Set Block template

Today we talk about how in Magento 2 Set Block template. This tutorial included set block template in layout file, block file . Following this example you can get store date and time in block, helper, controller or model too. So let start with our example.

In layout File

    <block class="QaisarSatti\HelloWorld\Block\HelloWorld" name="HelloWorld" template="QaisarSatti_HelloWorld::HelloWorld.phtml"></block>

In Block File

Used the _construct() method to set template.

protected function _construct()
    {
        parent::_construct();
        $this->setTemplate('QaisarSatti_HelloWorld::HelloWorld.phtml');
    }

Another way to set template in block in set the $_template variable to your template.

protected $_template = 'QaisarSatti_HelloWorld::HelloWorld.phtml';
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


Pages:1234