:::: MENU ::::

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


Magento 2 create custom model

Every custom module that need to interact with database for that we need to create model. So today we talk about how to create magento 2 create custom model. Model consist of three files model file, resource model file and collection. So let create the our model file.

Step 1: Model file

Model file is pointing out our resource model. Here is example code model file on Github.

<?php


namespace QaisarSatti\HelloWorld\Model;



    class Helloworld extends \Magento\Framework\Model\AbstractModel  
    {  
        protected function _construct()
        {
            $this->_init('QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld');
        }
    }

Step 2: Create Resource model file

In resource model file we initialize table name and primary key column name. Here is example code resource model file on Github.

<?php


namespace QaisarSatti\HelloWorld\Model\ResourceModel;


use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class Helloworld extends AbstractDb

{

    protected function _construct()

    {

        $this->_init('blog_posts', 'post_id');

    }

}

Step 3: Collection model

In collection model file have initialize model and resource model. Here is example code collection model file on Github.

<?php


namespace QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld;


use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;


class Collection extends AbstractCollection

{

    protected function _construct()
    {

        $this->_init(
        'QaisarSatti\HelloWorld\Model\Helloworld',
        'QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld');

    }

}

Here is complete example code on Github

Author: Qaisar Satti
Category: Magento 2
Last Modified: January 2, 2018


Magento 2 Create a install Schema

When we creating custom module sometime we need to add the table for that module. So in magento 2 we use install Schema. So today we learn how to in Magento 2 Create a install Schema? First we need to create the folder in our module directory name Setup. The folder location will be.

QaisarSatti\HelloWorld\Setup

Now we create our InstallSchema file. The file location will be.

QaisarSatti\HelloWorld\Setup\InstallSchema.php

Below is example code to create a table from install Schema.

<?php

namespace QaisarSatti\HelloWorld\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface {

    public function install( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
        $installer = $setup;

        $installer->startSetup();

        $table = $installer->getConnection()->newTable(
            $installer->getTable( 'sample_posts' )
        )->addColumn(
            'post_id',
            Table::TYPE_SMALLINT,
            null,
            [ 'identity' => true, 'nullable' => false, 'primary' => true ],
            'Post ID'
        )->addColumn(
            'title',
            Table::TYPE_TEXT,
            255,
            [ 'nullable' => false ],
            'Post Title'
        )->addColumn(
            'content',
            Table::TYPE_TEXT,
            '2M',
            [ ],
            'Post Content'
        )->setComment(
            'Sample Post Table'
        );

        $installer->getConnection()->createTable( $table );

        $installer->endSetup();
    }
}

Example code is available on Github.

Author: Qaisar Satti
Category: Magento 2
Last Modified: January 2, 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: December 19, 2017


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 ListProduct.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: December 20, 2017


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: December 15, 2017