:::: MENU ::::
Posts tagged with: extension

Magento 2 addFieldToFilter

Today we discuss Magento 2 addFieldToFilter. addFieldToFilter is a method that can be use to filter collections in Magento 2. That will be use in product collection, category collection, order collection customer collection and other collection too. addFieldToFilter is adding WHERE condition in Mysql question to get collection.

addFieldToFilter condition

There are many condition you can use with addFieldToFilter. Example of condition equal, not equal, like , not like, in, not in, null, not null, greater than , less than , greater than equal to and less than equal to.

protected $_productCollectionFactory;

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

Equal: eq

Now we use equal to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('status', array('eq' => 1)); // Using the operator
$this->_productCollectionFactory->addFieldToFilter('status', 1); // Without using the operator

Not Equals – neq

Now we use not equal to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('sku', array('neq' => 'test-product'));

Like – like

Now we use Like to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('sku', array('like' => 'UX%'));

Not Like – nlike

Now we use not like to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('sku', array('nlike' => 'err-prod%'));

In – in

Now we use In to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('in' => array(1,4,98)));

Not In – nin

Now we use not In to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('nin' => array(1,4,98)));

NULL – null

Now we use null to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('description', array('null' => true));

Not NULL – notnull

Now we use not null to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('description', array('notnull' => true));

Greater Than – gt

Now we use greater than to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('gt' => 5));

Less Than – lt

Now we use less than to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('lt' => 5));

Greater Than or Equals To- gteq

Now we use greater than to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('gteq' => 5));

Less Than or Equals To – lteq

Now we use less than equal to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('lteq' => 5));
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 30, 2018


Magento 2 programmatically add custom order status

Today we talk about how in Magento 2 programmatically add custom order status. This tutorial includes set custom order status and also set the default magento order status too. You have to inject Magento\Sales\Model\Order to set order status. So let start with our example.

Dependency Injection

protected $orderFactory;
public function __construct(
           
        \Magento\Sales\Model\OrderFactory $orderFactory,

    ) {


        $this->orderFactory = $orderFactory;

    }

public function customOrderStatus(){
        $orderId = 3;
        $order = $this->orderFactory->create()->load($orderId);
        $state = $order->getState();
        $status = 'custom_cancel';
        $comment = 'This is test comment';
        $isNotified = false;
        $order->setState($state);
        $order->setStatus($status);
        $order->addStatusToHistory($order->getStatus(), $comment);
        $order->save();
}

Object Manager

        $orderId = 3;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $order = $objectManager->create('\Magento\Sales\Model\Order')->load($orderId);
        $state = $order->getState();
        $status = 'custom_cancel';
        $comment = '';
        $isNotified = false;
        $order->setState($state);
        $order->setStatus($status);
        $order->addStatusToHistory($order->getStatus(), $comment);
        $order->save();
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 shopping cart items subtotal grand total billing and shipping address

Today we talk about how in Magento 2 shopping cart items subtotal grand total billing shipping address. In this tutorial you will learn how to get data of shopping cart item detail example product name, product sku, price and quantity and cart total item count, cart item total quantity, cart subtotal, cart grand total also quote shipping address and quote billing address. There are two method of get the cart detail. One is inject the class \Magento\Checkout\Model\Session in your block and get data from it. Second is use the object manager to get data.

Dependency Injection

<?php
namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
 
    public $_checkoutSession;
 
    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,

    ) {
        $this->_checkoutSession = $checkoutSession;
 
    }
 
}

Get cart information in phtml file.

//Get session object in phtml file
$getCurrentQuote = $block->_checkoutSession()->getQuote();
$getAllitems = $getCurrentQuote->getAllItems();
 
foreach($getAllitems as $item) {
    echo 'Product Id: ' . $item->getProductId() . '<br />';
    echo 'Name: ' . $item->getName() . '<br />';
    echo 'Sku: ' . $item->getSku() . '<br />';
    echo 'Quantity: ' . $item->getQty() . '<br />';
    echo 'Price: ' . $item->getPrice() . '<br />';
    echo "<br /><br />";
}
 
// Get cart total items and total quantity
$totalItems = $getCurrentQuote->getItemsCount();
$totalQuantity = $getCurrentQuote->getItemsQty();
 
//get cart subtotal and grand total
$subTotal = $getCurrentQuote->getSubtotal();
$grandTotal = $getCurrentQuote->getGrandTotal();
 
//get cartbilling and shipping addresses
$billing = $getCurrentQuote->getBillingAddress();
$shipping = $getCurrentQuote->getShippingAddress();

Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$getCurrentQuote = $objectManager->get('\Magento\Checkout\Model\Session');

$getAllitems = $getCurrentQuote->getAllItems();
 
foreach($getAllitems as $item) {
    echo 'Product Id: ' . $item->getProductId() . '<br />';
    echo 'Name: ' . $item->getName() . '<br />';
    echo 'Sku: ' . $item->getSku() . '<br />';
    echo 'Quantity: ' . $item->getQty() . '<br />';
    echo 'Price: ' . $item->getPrice() . '<br />';
    echo "<br /><br />";
}
 
// Get cart total items and total quantity
$totalItems = $getCurrentQuote->getItemsCount();
$totalQuantity = $getCurrentQuote->getItemsQty();
 
//get cart subtotal and grand total
$subTotal = $getCurrentQuote->getSubtotal();
$grandTotal = $getCurrentQuote->getGrandTotal();
 
//get cartbilling and shipping addresses
$billing = $getCurrentQuote->getBillingAddress();
$shipping = $getCurrentQuote->getShippingAddress();
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 redirect user from observer to custom controller

Today we talk about how in Magento 2 redirect user observer custom controller. This tutorial includes example of redirect user from observer. Using this example you can redirect from block, helper and model . You need to inject \Magento\Framework\App\Response\Http class to make the redirection from anywhere.So let’s start with our example.

<?php
namespace QaisarSatti\HellowWorld\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;
class [YourClass] implements ObserverInterface {

   protected $_redirect;
   protected $_url;
   public function __construct(


       \Magento\Framework\UrlInterface $url,
       \Magento\Framework\App\Response\Http $redirect,

   ) {

       $this->_url = $url;
        $this->_redirect = $redirect;

    }
    public function execute(Observer $observer) {
             $event = $observer->getEvent();
             $CustomRedirectionUrl =          $this->_url->getUrl('test/test/test');
             $this->_redirect->setRedirect($CustomRedirectionUrl);

    }
}

Note: You can use this example with any observer event.

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


Magento 2 image upload system configuration

Today we talk about how in Magento 2 image upload system configuration. This tutorial include image upload in system configuration. Sometime you need to add general image for a module, a company logo , a marker or a custom theme. With the help of following code you would be able to add a single image in system configurations.

Add the image field in system configuration.

<field id="image" translate="label comment" type="image" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Store Image</label>
                    <backend_model>QaisarSatti\HelloWorld\Model\Config\Backend\Image</backend_model>
                      <base_url type="media" scope_info="1">image</base_url>
 </field>

Now create model for image upload.

<?php

namespace QaisarSatti\HelloWorld\Model\Config\Backend;

class Image extends \Magento\Config\Model\Config\Backend\Image
{
    /**
     * The tail part of directory path for uploading
     *
     */

    const UPLOAD_DIR = 'store'; // Folder save image

    /**
     * Return path to directory for upload file
     *
     * @return string
     * @throw \Magento\Framework\Exception\LocalizedException
     */

    protected function _getUploadDir()
    {
        return $this->_mediaDirectory->getAbsolutePath($this->_appendScopeInfo(self::UPLOAD_DIR));
    }

    /**
     * Makes a decision about whether to add info about the scope.
     *
     * @return boolean
     */

    protected function _addWhetherScopeInfo()
    {
        return true;
    }

    /**
     * Getter for allowed extensions of uploaded files.
     *
     * @return string[]
     */

    protected function _getAllowedExtensions()
    {
        return ['jpg', 'jpeg', 'gif', 'png', 'svg'];
    }
}
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 create basic module frontend part 4

As we finished with the basic module structure and admin part we move to Magento 2 create basic module frontend .Now this tutorial will be cover the create frontend router, create layout file, create frontend controller, create frontend block, add custom pagination. Now we start with frontend.

Create frontend router

Create routes.xml in following directory

QaisarSatti\HelloWorld\etc\frontend\

<?xml version="1.0"?>
<!--
/**
* Hello World
   *
   * @category    QaisarSatti
   * @package     QaisarSatti_HelloWorld
   * @author      Muhammad Qaisar Satti
   * @Email       [email protected]
   *
*/
-->
     <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
        <router id="standard">
            <route id="helloworld" frontName="helloworld">
                <module name="QaisarSatti_HelloWorld" />
            </route>
        </router>
    </config>

Create frontend controller

Create Index.php in following directory

QaisarSatti\HelloWorld\Controller\Index\

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

namespace QaisarSatti\HelloWorld\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action

{

    public function execute()
    {  
       
        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }

}

Create layout file

Create helloworld_index_index.xml in following directory

QaisarSatti\HelloWorld\etc\frontend\

<?xml version="1.0"?>
<!--
/**
* Hello World
   *
   * @category    QaisarSatti
   * @package     QaisarSatti_HelloWorld
   * @author      Muhammad Qaisar Satti
   * @Email       [email protected]
   *
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="content">
                <block class="QaisarSatti\HelloWorld\Block\HelloWorld" name="HellosWorld" template="QaisarSatti_HelloWorld::HelloWorld.phtml"></block>
            </referenceContainer>
        </body>
    </page>

Create frontend block

Create HelloWorld.php in following directory

QaisarSatti\HelloWorld\Block\

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


namespace QaisarSatti\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{
      protected $_coreRegistry = null;
    protected $_collectionFactory;
    protected $_productsFactory;
    protected $_helloworldFactory;
   public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \QaisarSatti\HelloWorld\Model\ResourceModel\HelloWorld\CollectionFactory $helloworldFactory,
       array $data = []
   ) {
 
       $this->_coreRegistry = $registry;
       $this->_helloworldFactory = $helloworldFactory;
       parent::__construct($context, $data);
   }
   public function getHelloCollection()
        {
          $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
           //get values of current limit
          $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 5;

          $helloCollection = $this->_helloworldFactory->create();
          $helloCollection->setPageSize($pageSize);
          $helloCollection->setCurPage($page);
          return $helloCollection;
        }
   public function _prepareLayout()
   {
   
       parent::_prepareLayout();
       $this->pageConfig->getTitle()->set(__('Sample Post'));

       if ($this->getHelloCollection()) {
            $pager = $this->getLayout()->createBlock('Magento\Theme\Block\Html\Pager','qaisarsatti.blog.pager')->setAvailableLimit(array(5=>5,10=>10,15=>15,20=>20));
            $pager->setShowPerPage(true);
            $pager->setCollection($this->getHelloCollection());
            $this->setChild('pager', $pager);
            $this->getHelloCollection()->load();
        }
        return $this;
   }
   public function getPagerHtml(){
        return $this->getChildHtml('pager');
    }


}

Create frontend phtml

Create HelloWorld.phtml in following directory

QaisarSatti\HelloWorld\view\frontend\templates\

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

$blogCollection = $block->getHelloCollection();
foreach ($blogCollection as $blog) {

    echo $blog->getTitle().'<br />';
    echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$blog->getContent().'<br />';
}

 if ($block->getPagerHtml()): ?>
<div class="order-products-toolbar toolbar bottom">
<?php echo $block->getPagerHtml(); ?>
</div>
<?php endif ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Pages:1234