:::: MENU ::::
Posts tagged with: custom theme

Magento 2 enable template path hints

Today we discuss how in Magento 2 enable template path hints. This topic will cover how to enable template path hints on frontend and also backend too. There are two ways to enable the template path hints. One way is to enable hints from admin configurations and the other way is by using MySql query.

Using Admin Panel

Login to admin panel.

Front end

Store > Configuration > Advanced > Developer > Debug > Enabled

Template Path Hints for Storefront > Yes

Admin Panel

Store > Configuration > Advanced > Developer > Debug > Enabled  

Template Path Hints for Admin > Yes

Using Mysql Query

Enable Temaote Path Hints

UPDATE core_config_data SET value = '1' WHERE path LIKE '%template_hints%';

Disable Temaote Path Hints

UPDATE core_config_data SET value = '0' WHERE path LIKE '%template_hints%';

Note: this command only work if it have already entry in core_config_data table.

Author: Qaisar Satti
Category: Magento 2
Last Modified: April 23, 2018


Magento 2 display discount percent product page

Today we discuss how in Magento 2 display discount percent product page. This topic will cover how to show % percentage saving on current product. You can use this code on any product product listing or product widget page. You can also use this code product detail page. So let’s start with our example. You need to get $_product->getFinalPrice() and $_product->getPrice() to calculate the percentage of current product.

$_finalPrice = $_product->getFinalPrice();
$_price = $_product->getPrice();
if($_finalPrice < $_price):
   $_savingPercent = 100 - round(($_finalPrice / $_price)*100);
      echo $_savingPercent; ?> % Off
<?php endif; ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: April 23, 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 best Seller product collection

Let’s talk about using sales report collection so today we talk about how to get Magento 2 best seller product collection. Best seller collection in depend on number of time product quantity is sold. First we have to inject the Bestsellers\CollectionFactory in you block or helper any other file you want to use it. You can get the report of monthly,yearly and daily and also custom date. 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;
   public function __construct(
       \Magento\Backend\Block\Template\Context $context,
      \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
               array $data = []
   ) {
 
       $this->_collectionFactory = $collectionFactory;
             parent::__construct($context, $data);
   }


public function getBestSellerData(){
     
$bestSellerProdcutCollection = $this->_collectionFactory->create()
                    ->setModel('Magento\Catalog\Model\Product')
                    ->setPeriod('month') //you can add period daily,yearly
                   ;
           
       return $bestSellerProdcutCollection;
   }
}

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
        $bestSeller =  $block->getBestSellerData(); ?>
        <h1>Best Seller Collection.....</h1>
        <ul>
            <?php foreach ($bestSeller as $product) {
                ?>
                <li><?php  echo $product->getProductName();?>--<?php  echo $product->getQtyOrdered();?></li>
            <?php } ?>
</ul>
Author: Qaisar Satti
Category: Magento 2
Last Modified: January 5, 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: December 15, 2017


Magento 2 custom image resize

Today we talk about how to resize image in custom module. So let start talk about it with some background classes that are use to resize the image. In framework we use classes of Filesystem and Image\AdapterFactory. So here we go First we create the method resize in your block or you can create method in helper. In my example i am creating in my block.

   protected $_filesystem ;
   protected $_imageFactory;
   public function __construct(            
        \Magento\Framework\Filesystem $filesystem,        
        \Magento\Framework\Image\AdapterFactory $imageFactory        
        ) {        
        $this->_filesystem = $filesystem;              
        $this->_imageFactory = $imageFactory;        
        }

    // pass image Name, width and height
    public function resize($image, $width = null, $height = null)
    {
        $absolutePath = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('helloworld/images/').$image; //complete path of image

        $imageResized = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('resized/'.$width.'/').$image;        
        //create image factory...
        $imageResize = $this->_imageFactory->create();        
        $imageResize->open($absolutePath);
        $imageResize->constrainOnly(TRUE);        
        $imageResize->keepTransparency(TRUE);        
        $imageResize->keepFrame(FALSE);        
        $imageResize->keepAspectRatio(TRUE);        
        $imageResize->resize($width,$height);  
        //destination folder                
        $destination = $imageResized ;    
        //save image      
        $imageResize->save($destination);        

        $resizedURL = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'resized/'.$width.'/'.$image;
        return $resizedURL;
     }

Now we call our block method in our phtml.

$block->resize('test.jpg',500,400);
Author: Qaisar Satti
Category: Magento 2
Last Modified: December 15, 2017


Magento 2 call a static block

Today we learn about how to call a static block from phtm fiile,cms page and layout (xml) file. First you have to create a static block from admin panel, go to menu Content , choose Blocks and Click Add New Block button from top right. Every static block have identifier that are unique. You can call static block by identifier. For example our identifier is QaisarSattiTest.Now we use this identifier in phtml file, layout file and cam page.

Phtml:

echo $this->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId(QaisarSattiTest)->toHtml();

Layout (xml):

<block class="Magento\Cms\Block\Block" name="footersocial" before="-">                     
      <arguments>
            <argument name="block_id" xsi:type="string">QaisarSattiTest</arguments>
      </arguments>
 </block>

CMS Page:

{{block  id="QaisarSattiTest"}}
Author: Qaisar Satti
Category: Magento 2
Last Modified: December 15, 2017


Pages:123