:::: MENU ::::
Monthly Archives: June 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 use registry

Today we talk about how in Magento 2 use registry. This tutorial includes register, registry, get registry value and unregister registry value. Registry is not a replacement of session in magento 2. Registry stores the value till the page loads. After the page loading the registry is unregister automatically. Registry can be helpful in many ways like you wish to register products Ids on one page from products collections and fetch them on another page , it’s so handy to work around registries. Following example will give you an insight to the actual implementation .So let’s start with our example registry example.

Registry Object

First we inject the registry class instance. So we can use registry in our class.

public function __construct(
   
    \Magento\Framework\Registry $registry,
   
) {
   
    $this->registry     = $registry;
   
}

Register Registry Object

Now we use registry instance to register the registry object.

public function registerValue()
{
 return $this->registry->register('test_var' , 'sometext');
}

get Registry Object

Now we use registry instance to get registry object.

public function getValue()
{
 return $this->registry->registry('test_var');
}

Unregister Registry Object

Now we use registry instance to unregister the registry object.

public function unSetValue()
{
   return $this->registry->unregister('test_var');
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 image upload system configuration

Today we talk about how in Magento 2 image upload system configuration. This tutorial include image upload in system configuration. Sometime you need to add general image for a module, a company logo , a marker or a custom theme. With the help of following code you would be able to add a single image in system configurations.

Add the image field in system configuration.

<field id="image" translate="label comment" type="image" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Store Image</label>
                    <backend_model>QaisarSatti\HelloWorld\Model\Config\Backend\Image</backend_model>
                      <base_url type="media" scope_info="1">image</base_url>
 </field>

Now create model for image upload.

<?php

namespace QaisarSatti\HelloWorld\Model\Config\Backend;

class Image extends \Magento\Config\Model\Config\Backend\Image
{
    /**
     * The tail part of directory path for uploading
     *
     */

    const UPLOAD_DIR = 'store'; // Folder save image

    /**
     * Return path to directory for upload file
     *
     * @return string
     * @throw \Magento\Framework\Exception\LocalizedException
     */

    protected function _getUploadDir()
    {
        return $this->_mediaDirectory->getAbsolutePath($this->_appendScopeInfo(self::UPLOAD_DIR));
    }

    /**
     * Makes a decision about whether to add info about the scope.
     *
     * @return boolean
     */

    protected function _addWhetherScopeInfo()
    {
        return true;
    }

    /**
     * Getter for allowed extensions of uploaded files.
     *
     * @return string[]
     */

    protected function _getAllowedExtensions()
    {
        return ['jpg', 'jpeg', 'gif', 'png', 'svg'];
    }
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 get set unset session

Today we talk about how in Magento 2 get, set, and unset session. This tutorial include set session, get session and unset the session. Sometimes in customization and module development we need to get the session information , that how long a user remains on our site or we may need to unset the session given the certain amount of time . Following piece of code will let us to play with the global session variable to achieve our intended goals.

protected $coreSession;

public function __construct(
   
    \Magento\Framework\Session\SessionManagerInterface $coreSession
    ){

    $this->coreSession = $coreSession;
   
}

public function setSession(){
    $this->coreSession->start();
    $this->coreSession->setTest('The Core session');
}

public function getSession(){
    $this->coreSession->start();
    return $this->coreSession->getTest();
}

public function unSetSessione(){
    $this->coreSession->start();
    return $this->coreSession->unsTest();
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 Current Store Date Time

Today we talk about how in Magento 2 Current Store Date Time. Following this example you can get store date and time in block, helper, controller or model too. So let start with our example.
You need to inject in your class constructor an instance of Magento\Framework\Stdlib\DateTime\DateTime.

protected $date;
public function __construct(
   
    \Magento\Framework\Stdlib\DateTime\DateTime $date,

) {
   
    $this->date = $date;

}

Then, you can use in your class this:

$date = $this->date->gmtDate();
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 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 product count by attribute

Today we talk about how in Magento 2 product count by attribute. This tutorial included get product count by product attribute values. Following this example you can get count product by any attribute. For using this example you just need to replace you_attribute_code with you attribute code i.e color. So let start with our example.

    protected $_productCollectionFactory;
    protected $attributFactory;
    protected $eavConfig;

    public function __construct(
   
        \Magento\Catalog\Model\ResourceModel\Product $productFactory,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory $attributFactory,
        \Magento\Eav\Model\Config $eavConfig,

       
    ) {
   
        $this->eavConfig = $eavConfig;
        $this->attributFactory = $attributFactory;
        $this->_productCollectionFactory = $productFactory;            

    }


    public function getProductCountByAttributeCode()
     {
        $attributeCode = ‘you_attribute_code’;
        $attribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);
        $attributFactory = $this->attributFactory->create()->setStoreFilter(0, false);
         $itemCollection = $this->_productCollectionFactory;
        $attributFactory->getSelect()
        ->joinLeft(
            array('value_table' => $itemCollection->getTable('catalog_product_entity_int')),
            'main_table.option_id=value_table.value AND main_table.attribute_id=value_table.attribute_id', 'entity_id')
        ->reset(\Zend_Db_Select::COLUMNS)
        ->columns(array('main_table.option_id',new \Zend_Db_Expr('COUNT(value_table.entity_id)')))
        ->where('main_table.attribute_id=:attribute_id')
        ->group('main_table.option_id');
        $result = $itemCollection->getConnection()->fetchPairs(
        $attributFactory->getSelect(), array('attribute_id' => $attribute->getId()));
        return $result;        
    }

Note: Using above example you can count product by any attribute.

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