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

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: January 17, 2018


Magento 2 Find value comma separated string column

Today we discuss Magento 2 find value comma separated string column. Sometime you need to search in comma separated values in database. So for that we use the Finset to search in comma separated values. Let’s take the example of product collection. Let’s spose the field name test_sku have the comma separated values. So here is example

protected $_productCollectionFactory;
public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
       $sku=’test’;    
      return   $this->_productCollectionFactory->create()->addFieldToFilter('test_sku', array('finset' => $sku));
     
     }
Author: Qaisar Satti
Category: Magento 2
Last Modified: March 28, 2018


Magento 2 store information

Today we talk about how to get Magento 2 store information. In Store information we get the current store id , store code , store website id ,store name and also the available currencies in current store.So let start with example.

<?php
namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        array $data = []
    )
    {            
        parent::__construct($context, $data);
    }
   public function getStoreInfromation()
   {
        return $this->_storeManager->getStore();
   }
}

In phtml file get the information

$storeInformation = $block->getStoreInfromation();

$storeInformation->getStoreId();  //get store id
$storeInformation->getCode();  // get store code
$storeInformation->getWebsiteId(); // get store website id
$storeInformation->getName();  //get store name

//To get available currencies in store you check

foreach($storeInformation->getAvailableCurrencyCodes() as $codes):
  echo $codes;
endforeach;
Author: Qaisar Satti
Category: Magento 2
Last Modified: January 8, 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 Create custom renderer in admin grid

Today we discussed How to create Magento 2 Create custom renderer in admin grid. Sometime we need get some other values than current values. For example get product name instead of product id. For that we need to create a custom renderer for gird that will show the product name instead of product id so here we start. First we need to add column class that we need to renderer.

Step 1:

Create a ui class of column.

<column name="vendor_id" class="QaisarSatti\HelloWorld\Ui\Component\Listing\Column\Testing">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Vendor</item>
                </item>
            </argument>
        </column>

Step 2:

Create a renderer file for that particular column.

PME\PoManager\Ui\Component\Listing\Column\Vendor

<?php
namespace QaisarSatti\HelloWorld\Ui\Component\Listing\Column;
 
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
 

class Testing extends Column
{
        protected $escaper;
 
      protected $systemStore;
      protected $productloader;
 
 
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        \Magento\Catalog\Model\ProductFactory $productloader,
        Escaper $escaper,
        array $components = [],
        array $data = []
    ) {
        $this->escaper = $escaper;
       $this->productloader = $productloader;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }
 
    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */

    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {
                               $product = $this->productloader>create()->load((int)$item[$this->getData('name')]);


                $item[$this->getData('name')] =$product->getName();
            }
        }
 
        return $dataSource;
    }
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: January 2, 2018


Magento 2 mass action to admin grid

Today we talk about how to add magento 2 mass action to admin grid. Like add mass action to Order gird, add mass action to product grid, add mass action to customer grid or add mass action to any custom grid. So we are going to add the mass action in order gird. You can add mass action to any other admin grid just following the example. For any kind of suggestion kindly do comments in below section of post. So first we create or duplicate the ui component file in our view/adminhtml/ui_component folder and then add our mass action into it.

Step 1: Duplicate Grid Component File

In your module create the duplicate gird file name for example order grid use sales_order_grid.xml so we create same name file our module view/adminhtml/ui_component folder we create the following file:

QaisarSatti/HelloWorld/view/adminhtml/ui_component/sales_order_grid.xml

Step 2: Add Mass Action

Now we are going to add mass action to grid. So first we call the container listing_top then in massaction node we add reference of parent ui_coponent listing_massaction. Now we add our custom mass action.

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
  <container name="listing_top">
  <massaction name="listing_massaction">
      <action name="nameofaction">
              <argument name="data" xsi:type="array">
                  <item name="config" xsi:type="array">
                      <item name="type" xsi:type="string">testing</item>
                      <item name="label" xsi:type="string" translate="true">My Label</item>
                      <item name="url" xsi:type="url" path="adminrouter/filder/controllername"/>
                  </item>
              </argument>
          </action>
  </massaction>
</container>
</listing>

Step 3: Get Mass Action Values

Now getting the values in mass action to run our mass action.

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

namespace QaisarSatti\HelloWorld\Controller\Adminhtml\Index;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;

class MassOrder extends \Magento\Sales\Controller\Adminhtml\Order\AbstractMassAction
{
    /**
     * Authorization level of a basic admin session
     */


    /**
     * @param Context $context
     * @param Filter $filter
     * @param CollectionFactory $collectionFactory
     */

    public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory)
    {
        parent::__construct($context, $filter);
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * Cancel selected orders
     *
     * @param AbstractCollection $collection
     * @return \Magento\Backend\Model\View\Result\Redirect
     */

    protected function massAction(AbstractCollection $collection)
    {
        $countCancelOrder = 0;
        print_r($collection->getAllIds()); //to check the ids
        foreach ($collection->getItems() as $order) {
           
            //do your logic here
            $countCancelOrder++;
        }
        $countNonCancelOrder = $collection->count() - $countCancelOrder;

        if ($countNonCancelOrder && $countCancelOrder) {
            $this->messageManager->addError(__('%1 order(s) cannot be done it .', $countNonCancelOrder));
        } elseif ($countNonCancelOrder) {
            $this->messageManager->addError(__('You done it  the order(s).'));
        }

        if ($countCancelOrder) {
            $this->messageManager->addSuccess(__('We done it %1 order(s).', $countCancelOrder));
        }
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath($this->getComponentRefererUrl());
        return $resultRedirect;
    }
}

Following these example you can add mass action to any admin grid.

Author: Qaisar Satti
Category: Magento 2
Last Modified: February 9, 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: January 2, 2018