:::: MENU ::::
Browsing posts in: Magento 2

Magento 2 create custom command

Today we discuss how in Magento 2 create custom command. Sometime we need to import sample data or use the long queries to get data so for that it is better to use command line interface. Magento 2 use mostly command line interface for upgrade, reindex, static content deploy and many other command available. Here is list of default magento available command. So let’s start with our custom command.

Step 1: Define Command

For custom command keep in mind in item name qaisarSatti_helloworld first letter will your nameSpace. Now add following code to your di.xml

QaisarSatti\HelloWorld\etc\di.xml
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Console\CommandList">
        <arguments>
            <argument name="commands" xsi:type="array">
                <item name="qaisarSatti_helloworld" xsi:type="object">QaisarSatti\HelloWorld\Console\Command\HelloWorld</item>
            </argument>
        </arguments>
    </type>
</config>

Step 1: Create Command

Now Create file HelloWorld.php in following directory.

QaisarSatti\HelloWorld\Console\Command

In your configure method just set

setName(‘qaisarsatti:helloworld’) // this will be your command that you run from cli
setDescription(‘Command Description’) // add your command detail

In you execute method you add your custom logic

<?php


namespace QaisarSatti\HelloWorld\Console\Command;

use \Symfony\Component\Console\Command\Command;
use \Symfony\Component\Console\Input\InputInterface;
use \Symfony\Component\Console\Output\OutputInterface;


class HelloWorld extends Command
{
   

    public function __construct(
    ) {
        parent::__construct();
    }

   
    protected function configure()
    {
        $this->setName('qaisarsatti:helloworld')
            ->setDescription('Just Checking for command'); //add you description here

        parent::configure();
    }

   
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try{
    //add your logic here
            $output->writeln('<info>Yahoooo command Successfully working!</info>');
        } catch (\Exception $e) {
            $output->writeln("<error>{$e->getMessage()}</error>");
        }
    }
}

Now check our command is listed or not. Just run following command

php bin/magento list

qaisarsatti
  qaisarsatti:helloworld                   Just Checking for command
command list

Now we execute the our command

php bin/magento qaisarsatti:helloworld

The output will be shown

Yahoooo command Successfully working!
run command

Now following this you can add new custom command in magento 2.

Author: Qaisar Satti
Category: Magento 2
Last Modified: March 29, 2018


Magento 2 get product attribute by attribute groups

Today we talk about how in Magento 2 get product attribute by attribute groups. Sometime custom requirement need to show the product attributes by its own groups. So we learn how to get product attribute by their attribute groups. So let’s start it.
Create a block with following injecting class

\Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory

<?php
namespace QaisarSatti\HelloWorld\Block;

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

  protected $_productloader;
  protected $request;
  protected $_groupCollection;


  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $_productloader,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory $_groupCollection,
        \Magento\Framework\App\Request\Http $request

    ) {


        $this->_productloader = $_productloader;
        $this->request = $request;
        $this->_groupCollection = $_groupCollection;
        parent::__construct($context);
    }
//get the product
    public function getLoadProduct()
    {
          $id=10;
     
        return $this->_productloader->create()->load($id);
    }
//Get attribute group id
    public function getAttributeGroupId($attributeSetId)
    {
         $groupCollection = $this->_groupCollection->create();
         $groupCollection->addFieldToFilter('attribute_set_id',$attributeSetId);
         $groupCollection->addFieldToFilter('attribute_group_name','Grid Attributes');
         
         
         return $groupCollection->getFirstItem();

    }
    //Get all attribute groups
    public function getAttributeGroups($attributeSetId)
    {
         $groupCollection = $this->_groupCollection->create();
         $groupCollection->addFieldToFilter('attribute_set_id',$attributeSetId);
         
         $groupCollection->setOrder('sort_order','ASC');
         return $groupCollection;

    }
//get attribute by groups
 public function getGroupAttributes($pro,$groupId, $productAttributes){
        $data=[];
        $no =__('No');
        foreach ($productAttributes as $attribute){
   
          if ($attribute->isInGroup($pro->getAttributeSetId(), $groupId) && $attribute->getIsVisibleOnFront() ){
              if($attribute->getFrontend()->getValue($pro) && $attribute->getFrontend()->getValue($pro)!='' && $attribute->getFrontend()->getValue($pro)!=$no){
                $data[]=$attribute;
              }
          }

        }
 
  return $data;
 }
 
 }

Now we use the block code in our phtml file.

$_product=$block->getLoadProduct();
$groupid=$block->getAttributeGroupId($_product->getAttributeSetId());
$attributesgroups=$block->getAttributeGroups($_product->getAttributeSetId());

$productAttributes=$_product->getAttributes();




?>
 
<?php
foreach ($attributesgroups as $attributesgroup):


 $attributes=$block->getGroupAttributes($product,$attributesgroup->getAttributeGroupId(),$productAttributes);
 

 
 
 if($attributes){ ?>

 

   
            <h3 class="col label" scope="row"><?php echo $attributesgroup->getAttributeGroupName() ?></h3>
           
           
            <div class="additional-attributes-wrapper table-wrapper block">
        <table class="data table additional-attributes" id="product-attribute-specs-table">
            <tbody>
           
    <?php
    foreach ($attributes as $attribute): ?>
       
       
       
             <tr>
                    <td class="col label" scope="row"><?php echo $attribute->getFrontendLabel() ?></td>
                    <td class="col data feature" data-th="<?php echo $attribute->getFrontendLabel() ?>"><?php /* @escapeNotVerified */ echo $attribute->getFrontend()->getValue($product) ?></td>
                </tr>
           
           
       
        <?php    
    endforeach; ?>
           </tbody>
        </table>
        </div>
 <?php }
endforeach;

?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: February 6, 2018


Magento 2 jquery ajax request

Sometime we need to load data with loading the page so for that we need ajax to load data. So today we focus how to use jquery ajax request in magento 2. Magneto have already added the jquery library.you can inject it with require. Here is example of using of jqery ajax for getting the json response from controller

<script> require(['jquery', 'jquery/ui'], function($){
$.ajax({
          method: "POST",
          url: "<?php  echo $block->getUrl(helloworld/ajax/index); ?>",
          data: { q: "test"},
          dataType: "json"
        })
      .done(function( msg ) {
 
        //do something with you return data
 

      });
    }
});

you we use controller ResultFactory to get back json response.

<?php namespace QaisarSatti\HelloWorld\Controller\Ajax;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Index extends Action {
protected $request;
public function __construct(Context $context,array $data = [])
{
parent::__construct($context,$data);
}
public function __execute() {
    $data=array("bdfb");
    $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
    $resultJson->setData($data);
    return $resultJson;

}
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: January 29, 2018


Magento 2 join multiple tables

Today we talk about how in Magento 2 join multiple tables. Sometime you need to get join collection with product collection data or category collection data or order collection or custom table collection. So today we focus on how to join two magento 2. Then we talk about multiple table join. Now taking a example of we need to join product collection with custom table. Here we go.

protected $_productCollectionFactory;  


      public function __construct(

            \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory

        ) {


            $this->_productloader = $_productCollectionFactory;

        }

    public getmyCollection(){
    $collection = $this->productCollectionFactory->create();
    $collection->getSelect()->join(
                ['table1join'=>$collection->getTable('table1join')],
                'main_table.entity_id = table1join.product_id',
                ['column1'=>'table1join.column1','column2'=>'table1join.column2']);
    return $collection;
    }

Now we try the example of multiple table join

public getmyCollection(){
    $collection = $this->productCollectionFactory->create();
    $collection->getSelect()->join(
                ['table1join'=>$collection->getTable('table1join')],
                'main_table.entity_id = table1join.product_id',
                ['column1'=>'table1join.column1','column2'=>'table1join.column2']);
    $collection->getSelect()->join(
                ['table1join'=>$collection->getTable('table1join')],
                'main_table.entity_id = table1join.product_id',
                ['table2column1'=>'table1join.column1','table2column1'=>'table1join.column2']);
       $collection->getSelect()->join(
            ['table2join'=>$collection->getTable('table2join')],
            'main_table.entity_id = table2join.product_id',
            ['table3column1'=>'table2join.column1','table3column1'=>'table2join.column2']);
      return $collection;
    }

You can use same example to join in any collection in magento 2.

Author: Qaisar Satti
Category: Magento 2
Last Modified: January 29, 2018


Magento 2 get product images

Today we talk about how in Magento 2 get product images for example thumbnail images, base images and small images.You can get these image in custom collection or product page. First you have to inject the ImageBuilder class in you block. You can get product collection or load the single product or get product current information. So let start with example. There is default available image types.

$imageType = 'product_base_image';  //For getting the base image
$imageType = 'product_small_image';  //For getting the small image
$imageType = 'product_thumbnail_image';   //For getting the thumbnail image

Now we inject the ImageBuilder class in our block.

protected $_imageBuilder;

public function __construct(
       
        \Magento\Catalog\Block\Product\ImageBuilder $_imageBuilder
    ) {
   
       
        $this->_imageBuilder=$_imageBuilder;
            }


 public function getImage($product, $imageId, $attributes = [])
    {
        return $this->_imageBuilder->setProduct($product)
            ->setImageId($imageId)
            ->setAttributes($attributes)
            ->create();
    }

Get Image in phtml

 <?php  

$imageType = 'product_thumbnail_image';
$image = $block->getImage($_item, $imageType); ?>
 <img src="<?php echo $image->getImageUrl(); ?> " />
Author: Qaisar Satti
Category: Magento 2
Last Modified: January 29, 2018


Magento 2 Front controller reached 100 router match iterations

Today we talk about most common error when you trying to add dynamic route in your module. There are three set need to be setModuleName, setControllerName and
setActionName. The problem is cause when there is no matching with your setModuleName, setControllerName and setActionName. May be is causing by spell mistake and any lower uppercase.
But the biggest confusion in this when you set setModuleName. You think of your module name but this is fronName that you are set in your frontend/routes.xml

    app/code/QaisarSatti/HelloWorld/etc/frontend/routes.xml
<?xml version="1.0"?>
<!--/**
* Simple Hello World Module
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email [email protected]
*
*/ -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="helloworld" frontName="helloworld">
<module name="QaisarSatti_HelloWorld" />
</route>
</router>
</config>

Now your setting will be in your router.php by following module

$request->setModuleName('helloworld')->setControllerName('index')->setActionName('index')
Author: Qaisar Satti
Category: Magento 2
Last Modified: January 29, 2018


Magento 2 get current category information

Today we talk about how to get Magento 2 current category information like category id, category name and other information on category page. Magneto 2 have feature of registry to store data. That is use to store data between execution of data. Like you want to set data in controller and use it in block or model the registry is best option for that. So let start with getting the category data from registry. Now i use HelloWorld module block example for getting current category information.
Create a Block

<?php
namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
    protected $registry;

    public function __construct(  
        \Magento\Framework\Registry $registry,

    )
    {      
        $this->registry = $registry;

    }


    public function getCurrentCategory()
    {      
        return $this->registry->registry('current_category');
    }  

}
?>

Get product information In your phtml file

<?php
  $currentCategory = $block->getCurrentCategory();
            echo $currentCategory->geId();
            echo $currentCategory->geName();
 ?>

If you want to get in current category information in phtml you can use following code.

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $currentCategory = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category information
    echo $currentCategory->geId();
    echo $currentCategory->geName();
?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: January 17, 2018