:::: MENU ::::
Monthly Archives: January 2018

Magento 2 jquery ajax request

Today topic 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: November 5, 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: July 12, 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: July 12, 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: July 12, 2018


Magento 2 get current category information

Today we talk about how to get Magento 2 current category information.Information like current category id, current category name and other category 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->getId();
            echo $currentCategory->getName();
 ?>

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->getId();
    echo $currentCategory->getName();
?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 get current product information

Today we talk about how to get Magento 2 current product information like product id, product name and other information on product 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 product data from registry. Now i use HelloWorld module block example for getting current product.

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 getCurrentProduct()
    {      
        return $this->registry->registry('current_product');
    }  

}
?>

Get product information In your phtml file

<?php
  $currentProduct = $block->getCurrentProduct();
            echo $currentProduct->geId();
            echo $currentProduct->geName();
 ?>

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

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $currentProduct = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product information
    echo $currentProduct>getId();
    echo $currentProduct>getName();
?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 most viewed product collection

Let’s talk about using report collection so today we talk about how to get Magento 2 most viewed product collection. Most viewed production collection in depend on number of time product viewed by user. First we have to inject the Reports\ProductCollection in you block or helper any other file you want to use it. So let start with coding. In this example I am going to inject into my block.

Step 1: Create a block file

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

namespace QaisarSatti\HelloWorld\Block;
class BestSeller extends \Magento\Framework\View\Element\Template
{
 
  protected $_collectionFactory;
  protected $_productsFactory;
   public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory,
    array $data = []
   ) {
 
        $this->_productsFactory = $productsFactory;
    parent::__construct($context, $data);
   }
public function getMostViewedData(){
   
    $mostViewedCollection = $this->_productsFactory->create()->addViewsCount();  
    return $mostViewedCollection;
   }
}

Step 2: Show Output

Getting collection in phtml file from block.

<!--/**
  * Simple Hello World Module
  *
  * @category QaisarSatti
  * @package  QaisarSatti_HelloWorld
  * @author   Muhammad Qaisar Satti
  * @Email    [email protected]
  *
  */
-->
  <?php
      $mostViewedProduct =  $block->getMostViewedData(); ?>
      <h1>Most Viewed Collection.....</h1>
      <ul>
          <?php foreach ($mostViewedProduct as $viewedProduct) {
              ?>
              <li><?php echo $viewedProduct>getSku();?>--<?php echo $viewedProduct>getViews();?></li>
          <?php } ?>
</ul>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Pages:12