:::: MENU ::::
Posts tagged with: helper

Magento 2 create retrieve system configuration

Today we talk about how in Magento 2 create retrieve system configuration. This tutorial includes the knowledge of 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: July 12, 2018


Magento 2 get product categories

In our daily coding routine you have to work with product and category. So today we learn how to get Magento 2 product categories from product object.You can always get the assigned categories of a product using following code.

In Constructor:

protected $_productFactory;
public function __construct(
        \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        $this->_productFactory = $productFactory;
    }
    public function getProductCategories()
    {
      $product = $this->_productFactory->create()->load($pid); // $pid = Product_ID

      return  $product->getCategoryIds();
     }

Now we get all categories from product collection.

protected $_productCollectionFactory;
protected $_productloader;
public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory,
         \Magento\Catalog\Model\ProductFactory $productloader
    ) {
        $this->_productCollectionFactory = $productFactory;
        $this->_productloader = $productloader;
    }
    public function getProductCollectionCategories()
    {
      $prodIds= $this->_productCollectionFactory->create(); // $pid = Product_ID
      foreach($prodIds as $pid){          
         $product = $this->_productloader->create()->load($pid);  
         $proCats = $product->getCategoryIds();    
         $catIds= array_merge($catIds, $pproCats);  
       }
      $finalCat = array_unique($catIds);
      return  $finalCat;
     }
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 overriding Rewriting helper

Today we talk about Magento 2 overriding Rewriting helper. In our daily coding routine we need to customization with core files. For that we need to overriding or rewrite the core classes because modify the core classes is not good practice. If you modify the code classes when you update the new version your code will be loss. So today we learn how to Magento 2 overriding or Rewriting helper. In start we are overriding core Product helper. We are jut checking our rewrite is working or not. You can modify the helper as you want following this tutorial. But first you need to know How to create module in Magneto 2.For any suggestions & question, please feel free to drop a comment.

Overriding or Rewrite Magento 2 Helper

sometimes, you may want to add new classes or override different functions in your Magento 2 module. Therefore, Magento 2 came up with the Helpers that are the right entity to fulfill your needs. A Helper in Magento 2 is an object that contains practical methods.Now we start to overriding or rewriting core Product helper. The helper we are overriding is Product helper.
Step 1.

Create a di.xml file in a following directory QaisarSatti/HelloWorld/etc/

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Helper\Product" type="QaisarSatti\HelloWorld\Helper\Rewrite\Product" />
</config>

Step 2
The step2 to overriding or rewriting Magento2 Helper is to create a Product.php helper file in the following directory QaisarSatti/HelloWorld/Helper/Rewrite/

<?php
/**
* Catalog Product overridingHelper
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Qaisar Satti
*
*/

namespace QaisarSatti\HelloWorld\Helper\Rewrite;
class Product extends \Magento\Catalog\Helper\Product
{
   public function __construct()
   {
     echo "Our Rewrite Working"; die();
   }
}

As following code you can rewrite or override any Magento 2 helper using the same method.

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


Magento 2 load product by id

Tpday we talk about how in Magento 2 load product by id. There are three way to get product load in magento 2. First Object Manager second factory Method and third on is Api Repository.

Factory Method:

Best practice method always use this method.

namespace QaisarSatti\Module\Block;

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

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function getLoadProduct()
    {
        $product_id=7;
        return $this->_productloader->create()->load($id);
    }

}

Api Repository:

This was introduce in Magento 2.1 by magento.

    namespace QaisarSatti\Module\Block;
    use Magento\Catalog\Api\ProductRepositoryInterface;
    class Product extends \Magento\Framework\View\Element\Template
     {
          protected $_productRepository;
       

          public function __construct(
         
            ProductRepositoryInterface $productRepository
          ) {
         

              $this->_productRepository = $productRepository;
          }
          public function getProduct()
          {
              $productId=7;
              return $product = $this->productRepository->getById($productId);
          }
      }

Object Manager:

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

$product_id=7;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 create  and use helper

Using helper you can put your methods in there that you have no idea where to put them. For example if you want create the thumbnail of image you use the helper method. The method you don’t know where to put put in helper class.

Now creating the helper and use of it.

Create Helper folder in module directory.



namespace QaisarSatti\HelloWorld\Helper

 

Now create the your helper class what name you want to put.In my case i will use Data file. Now the complete path will be.

namespace QaisarSatti\HelloWorld\Helper\Data.php



This file will be extend with.



 \Magento\Framework\App\Helper\AbstractHelper



Now create helper Data class.

 


<?php

/**

* Simple Hello World Module

*

* @category QaisarSatti

* @package QaisarSatti_HelloWorld

* @author Muhammad Qaisar Satti

* @Email [email protected]

*

*/


namespace QaisarSatti\HelloWorld\Helper;



use Magento\Store\Model\Store;



class Data extends \Magento\Framework\App\Helper\AbstractHelper

{



public function getTitle()

{

return  'First Hello World Module';

}

}

Now we will use helper method  in our block.

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

public function __construct(

\QaisarSatti\HelloWorld\Helper\Data $_helper,

) {



$this->_helper=$_helper;



}

public function _prepareLayout()

{

parent::_prepareLayout();

$this->pageConfig->getTitle()->set($this->_helper->getTitle());

return $this;

}

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