:::: MENU ::::
Posts tagged with: magento 2

Magento 2 overriding or Rewriting controller

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 override core blocks. In start we are overriding or rewriting controller. We are just checking our rewrite is working or not. You can modify the blocks as you want by 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 controller

A Controller has one or more files in Controller folder of module, it includes actions of class which contain execute() method. There are 2 different controllers, they are frontend controller and backend controller.Now we start to overriding or rewriting core Product controller. The controller we are overriding is Product View controller. Magento 2 use controller for category product listing.

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\Controller\Product\View" type="QaisarSatti\HelloWorld\Controller\Rewrite \Product\View" />
</config>

Step 2
The step2 to overriding or rewriting Magento 2 controller is to create a View.php controller file in the following directory QaisarSatti\HelloWorld\Controller\Rewrite \Product\

<?php
/**
* Catalog Product Rewrite controller
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
*
*/

namespace QaisarSatti\HelloWorld\Controller\Rewrite\Product;
class View extends \Magento\Catalog\Controller\Product\View
{
public function execute() {


echo "Controller Rewrite Working"; die();
  }
}

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

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


Magento 2 get min price or max price from product collection

Today we learn about how to get min price and max price from product collection. First you have to get collection of product. Then their two predefined function for get min price getMinPrice and get max price getMaxPrice Now you can get the collection following tutorial Magento 2 get product collection.

Now we implement the code for getting min price and max price.

protected $_productCollectionFactory;

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
      $productCollection = $this->_productCollectionFactory->create();
      $maxPrice = $productCollection>getMaxPrice();
     $minPrice = $productCollection>getMinPrice();
    }

}

You can see the example of Min Price and Max Price in Layer collection.Follow Magento\Catalog\Model\Layer\Filter\AbstractFilter.php

$this->getLayer()->getProductCollection()->getMaxPrice();
$this->getLayer()->getProductCollection()->getMinPrice();
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 get product collection

Today we talk about Magento 2 get product collection. First we need to familiar with model collection structure of magento 2. Magento 2 use the collection class for get all record from database table. SO let start with coding. We are using the Factory method here.

protected $_productCollectionFactory;

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
      return   $this->_productCollectionFactory->create()->addAttributeToSelect('*');
     
     }

To Fetch Data in phtml file

$productCollection = $block->getProductCollection();

foreach ($productCollection as $product) {

   
        echo $product->getName().'<br />';

}
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 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: July 12, 2018


Magento 2 available commands

Today we talk about Magento 2 available commands. In this tutorail we listed all the command that we can use in magento 2. Command like deploy content, setup upgrade, indexing command, cache command and other command too. you can create custom command too with the help of Magento 2 create custom command. So let’s start with our list.

Available commands:

help         Displays help for a command
list         Lists commands

admin

admin:user:create         Creates an administrator
admin:user:unlock         Unlock Admin Account

cache

cache:clean         Cleans cache type(s)
cache:disable         Disables cache type(s)
cache:enable         Enables cache type(s)
cache:flush         Flushes cache storage used by cache type(s)
cache:status         Checks cache status

catalog

catalog:images:resize         Creates resized product images
catalog:product:attributes:cleanup         Removes unused product attributes.

cron

cron:run         Runs jobs by schedule

customer

customer:hash:upgrade         Upgrade customer’s hash according to the latest algorithm

deploy

deploy:mode:set         Set application mode.
deploy:mode:show         Displays current application mode.

dev

dev:source-theme:deploy         Collects and publishes source files for theme.
dev:tests:run         Runs tests
dev:urn-catalog:generate         Generates the catalog of URNs to *.xsd mappings for the IDE to highlight xml.
dev:xml:convert         Converts XML file using XSL style sheets

i18n

i18n:collect-phrases         Discovers phrases in the codebase
i18n:pack         Saves language package
i18n:uninstall         Uninstalls language packages

indexer

indexer:info         Shows allowed Indexers
indexer:reindex         Reindexes Data
indexer:reset         Resets indexer status to invalid
indexer:set-mode         Sets index mode type
indexer:show-mode         Shows Index Mode
indexer:status         Shows status of Indexer

info

info:adminuri         Displays the Magento Admin URI
info:backups:list         Prints list of available backup files
info:currency:list         Displays the list of available currencies
info:dependencies:show-framework         Shows number of dependencies on Magento framework
info:dependencies:show-modules         Shows number of dependencies between modules
info:dependencies:show-modules-circular         Shows number of circular dependencies between modules
info:language:list         Displays the list of available language locales
info:timezone:list         Displays the list of available timezones

maintenance

maintenance:allow-ips         Sets maintenance mode exempt IPs
maintenance:disable         Disables maintenance mode
maintenance:enable         Enables maintenance mode
maintenance:status         Displays maintenance mode status

module

module:disable         Disables specified modules
module:enable         Enables specified modules
module:status         Displays status of modules
module:uninstall         Uninstalls modules installed by composer

sampledata

sampledata:deploy         Deploy sample data modules
sampledata:remove         Remove all sample data packages from composer.json
sampledata:reset         Reset all sample data modules for re-installation

setup

setup:backup         Takes backup of Magento Application code base, media and database
setup:config:set         Creates or modifies the deployment configuration
setup:cron:run         Runs cron job scheduled for setup application
setup:db-data:upgrade         Installs and upgrades data in the DB
setup:db-schema:upgrade         Installs and upgrades the DB schema
setup:db:status         Checks if DB schema or data requires upgrade
setup:di:compile         Generates DI configuration and all missing classes that can be auto-generated
setup:install         Installs the Magento application
setup:performance:generate-fixtures         Generates fixtures
setup:rollback         Rolls back Magento Application codebase, media and database
setup:static-content:deploy         Deploys static view files
setup:store-config:set         Installs the store configuration
setup:uninstall         Uninstalls the Magento application
setup:upgrade         Upgrades the Magento application, DB data, and schema

theme

theme:uninstall         Uninstalls theme

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


Magento 2 call static block

Today we learn about how to call 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: July 12, 2018