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

Magento 2 use plugin

Today we talk about how in Magento 2 use plugin. The plugin or Interceptor is a class the modify the behaviour of public class method by interceptions. The plugin give use three option to use After methods, Before methods and Around Method. This tutorial included example of how to add button on sales order view page. Now Following this example you can use plugin with any public class method in magento 2. So let start with our example.

Create di.xml

First create the di.xml in QaisarSatti/HelloWorld/etc/di.xml if it is not already created. If it is already create just add the plugin code.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="\Magento\Sales\Block\Adminhtml\Order\View">
        <plugin name="QaisarSatti_HelloWorld::AddButtonOrderView" type="QaisarSatti\HelloWorld\Plugin\AddButtonOrderView" />
    </type>
</config>

Create AddButtonOrderView.php

Now we create AddButtonOrderView.php in following directory QaisarSatti\HelloWorld\Plugin. Inject \Magento\Sales\Block\Adminhtml\Order\View in your method to get block obejct.

namespace QaisarSatti\HelloWorld\Plugin;

class AddButtonOrderView
{
   

    public function beforeSetLayout(\Magento\Sales\Block\Adminhtml\Order\View $object)
    {
       
   
            $message = __('Are you sure you want to perform this action?');
  $url = $object->getUrl('addurlhere', ['order_id' =>$object->getOrderId()]);
            $object->addButton(
                'UnCancel',
                [
                    'label' => __('Test Buttonl'),
                    'onclick' => "confirmSetLocation('{$message}', '{$url}')"
                ]
            );
   
    }
}

Note: Following this example you can use plugin with other public class methods too.

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


Magento 2 event observer

Today we talk about how in Magento 2 event observer. This tutorial included observing event sales_order_save_commit_after. Following this example you can observe any event in magento 2. So let start with our example.

Create event.xml

First create the events.xml in QaisarSatti/HelloWorld/etc/events.xml. If you want to observe the event that trigger only the frontend you create events.xml file QaisarSatti/HelloWorld/etc/frontend/events.xml. Same as you want to observe the events that trigger in admin side create file QaisarSatti/HelloWorld/etc/adminhtml/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_save_commit_after">
        <observer name="helloworld_sales_order_save_after" instance="QaisarSatti\HelloWorld\Observer\Observer" />
    </event>
</config>

Create Observer.php

Now we create Observer.php in following directory QaisarSatti\HelloWorld\Observer. Inject \Magento\Framework\Event\Observer in your method to get event data.

<?php
namespace QaisarSatti\HelloWorld\Observer;
use Magento\Framework\Event\ObserverInterface;
 
class Observer implements ObserverInterface {
  public function execute(\Magento\Framework\Event\Observer $observer) {
                 $order = $observer->getEvent()->getOrder(); //get order information      
    }
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


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


Magento 2 create product programmatically

Today we discussed how in Magento 2 create product programmatically. This tutorial includes the process of creating a simple product, set image to product and set quantity to product. So lets start with creating a simple product. We can do this in two ways- one is creating product with factory method and other is creating product with object manager.

Create Product with Factory Method

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function createProduct()
    {
       
        $_product = $this->_productloader->create();
        $_product->setName('First Test Product');
        $_product->setTypeId('simple');
        $_product->setAttributeSetId(4);
        $_product->setSku('test-SKU');
        $_product->setWebsiteIds(array(1));
        $_product->setVisibility(4);
        $_product->setPrice(400);
        $_product->setImage('/simpeproduct/test.jpg');
        $_product->setSmallImage('/simpeproduct/test.jpg');
        $_product->setThumbnail('/simpeproduct/test.jpg');
        $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 1000 //qty
            )
        );

        $_product->save();
        echo $_product->getId();
    }

Update Product with factory method

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function updateProduct()
    {
       
        $_product = $this->_productloader->create()->load(2047);
        $_product->setName('First Test Product Updated');
        $_product->save();
    }

Create Product with Object manager

 <?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $_product = $objectManager->create('Magento\Catalog\Model\Product');
    $_product->setName('First Test Product');
    $_product->setTypeId('simple');
    $_product->setAttributeSetId(4);
    $_product->setSku('test-SKU');
    $_product->setWebsiteIds(array(1));
    $_product->setVisibility(4);
    $_product->setPrice(400);
    $_product->setImage('/simpeproduct/test.jpg');
    $_product->setSmallImage('/simpeproduct/test.jpg');
    $_product->setThumbnail('/simpeproduct/test.jpg');
    $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 1000 //qty
            )
        );

$_product->save();
echo $_product->getId();

Update Product with Object manager

Now our custom product is created. Now we will update product. So doing with following example just.

            $_product = $objectManager->create('Magento\Catalog\Model\Product')->load(2047);
    $_product->setName('First Test Product Updated');
    $_product->save(); ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: August 2, 2018


Magento 2 use custom query

Today we will discuss how in Magento 2 custom query works. Sometime magento 2 model is not enough to get data from database as per our requirements. So to fulfill this requirement we use custom query. In this example we will use select custom query, custom delete query, custom insert query and custom update query. So let’s start with example.

Get connection

First of all we will establish a connection to execute the query.

 $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\ResourceConnection');          
        $connection= $this->_resources->getConnection();

Insert Query

It is simple to use insert query just set the values for columns. Use the inset method.

$array=array(‘column1’=>'column1','column2'=>'column2');

$connection->insert($this->_resources->getTableName(test_table), $array);

Select Query

Selecting table data in custom query you can use following code.

$select = $connection->select()->from(['o' =>  $this->_resources->getTableName(test_table)]);
$result = $connection->fetchAll($select);

       foreach ($result as $data) {
           echo $data['id'];
            }

Update Query

Updating table data in custom query you can use following code.

$id = 1;
 $sql = "Update " . $this->_resources->getTableName('test_table') . " Set `title` ='test title' where `id` = ".$id;
     $connection->query($sql);

Delete Query

To delete table data in custom query you can use following code.

$id = 1;
$condition = $this->getConnection()->quoteInto('id = ?', $id);
            $this->getConnection()->delete($this->getTable('test_table'), $condition);

Join Table

To join table in custom query you can use following code.

        $select = $connection->select()->from(['o' =>  $this->_resources->getTableName('test_table')])->joinleft(
        ['test_table1' => $this->_resources->getTableName('test_table1')],
        'o.id = test_table1.id',
        ['column1','column2']
    );
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 reset admin password

Today we discuss how in Magento 2 reset admin password. This topic include how to reset admin password with sql query, reset password through command line interface (cli). Sometime you forgot the admin password so today we discuss how to reset your admin password. There are two ways to do that. First go to database and reset your with sql query and second create new user from command line and then login and reset the password from admin panel.

Reset with Query

Change test123 to your required password.

UPDATE `admin_user` SET `password` = CONCAT(SHA2('xxxxxxxxtest123', 256), ':xxxxxxxx:1') WHERE `username`= 'admin'

Reset From Cli

Create new user and login to admin panel and change you old user password.

<path_to_magento> php bin/magento admin:user:create --admin-user="admin" --admin-password="123123q" --admin-email="[email protected]" --admin-firstname="Admin" --admin-lastname="Admin"
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018