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

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


Magento 2 available install schema columns type

Today we talk about Magento 2 available install schema columns type That we can use in install schema that is already mention in my post Magento 2 Create a install Schema. There are different type available in magneto 2. Type of column that you can is listed below with example.

Type boolean

TYPE_BOOLEAN = ‘boolean’;
Boolean: These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.
Example

addColumn(
            'post_id',
            Table::TYPE_BOOLEAN,
            null,
            [ 'identity' => false, 'nullable' => false, 'primary' => true ],
            'Post ID'
        )

Type smallint

TYPE_SMALLINT = ‘smallint’;
Example

addColumn(
            'post_id',
            Table::TYPE_SMALLINT,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type integer

TYPE_INTEGER = ‘integer’;
Example

addColumn(
            'post_id',
            Table::TYPE_INTEGER,
            null,
            ['nullable' => false],
            'Post ID'
        )

Type bigint

TYPE_BIGINT = ‘bigint’;
Example

addColumn(
            'post_id',
            Table::TYPE_BIGINT,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type float

TYPE_FLOAT = ‘float’;
Example

addColumn(
            'post_id',
            Table::TYPE_FLOAT,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type numeric

TYPE_NUMERIC = ‘numeric’;
Example

addColumn(
            'post_id',
            Table::TYPE_NUMERIC,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type decimal

TYPE_DECIMAL = ‘decimal’;
Example

addColumn(
            'post_id',
            Table::TYPE_DECIMAL,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type date

TYPE_DATE = ‘date’;
Example

addColumn(
            'data',
            Table::TYPE_DATE,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type timestamp

TYPE_TIMESTAMP = ‘timestamp’;
Example

->addColumn(
            'creation_time',
            Table::TYPE_TIMESTAMP,
            null,
            ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
            'Creation Time'
        )

Type datetime

Capable to support date-time from 1970 + auto-triggers in some RDBMS
TYPE_DATETIME = ‘datetime’;
Example

addColumn(
            'data',
            Table::TYPE_DATETIME,
            null,
            [ 'nullable' => false ],
            'Post ID'
        )

Type text

Capable to support long date-time before 1970
TYPE_TEXT = ‘text’;
Example

addColumn(
            'data',
            Table::TYPE_TEXT,
            255,
            [ 'nullable' => false],
            'Post ID'
        )

Type blob

TYPE_BLOB = ‘blob’;
Example

addColumn(
            'data',
            Table::TYPE_BLOB ,
            null,
            [ 'nullable' => false],
            'Post ID'
        )

Type varbinary

Used for back compatibility, when query param can’t use statement options
TYPE_VARBINARY = ‘varbinary’;
Example

addColumn(
            'data',
            Table::TYPE_VARBINARY,
            null,
            [ 'nullable' => false],
            'Post ID'
        )
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 get single column values from collection

Today we learn about how to get single column values from collection. For this example we use the product collection to get names of product. You can get product collection by following the Magento 2 get product collection.

protected $_productCollectionFactory;

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

Note: You can use same method with any collection.

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


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 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 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


Pages:123