:::: MENU ::::
Posts tagged with: php

Magento 2 overriding or rewriting model

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 Magento 2 overriding rewriting model. In start we are overriding core Product model. We are jut checking our rewriting model is working or not. You can modify the model 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 Model

Magento 2 Models play an even bigger role, as they typically contain the “Business Logic” that’s often relegated to the Controller or Helper methods in other PHP MVC frameworks. Now we start to overriding or rewriting core Product model. The model we are overriding is Product Model.
Step 1.

Create a di.xml file in a following directory QaisarSatti/HelloWorld/etc/

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Model\Product" type="QaisarSatti\HelloWorld\Model\Rewrite\Catalog\Product" />
</config>

Step 2
The step2 to overriding or rewriting Magento2 model is to create a Product.php helper file in the following directory QaisarSatti/HelloWorld/Model/Rewrite/Catalog

<?php
/**
* Catalog Product Rewrite Model
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
*
*/

namespace QaisarSatti\HelloWorld\Model\Rewrite\Catalog;
class Product extends \Magento\Catalog\Model\Product
{
public function __construct()
{
echo "Overrding/ Rewrite Working"; die();
}
}

As following code you can rewrite or override any Magento 2 model using the same method.

Author: Qaisar Satti
Category: Magento 2
Last Modified: May 22, 2018


Magento 2 overriding or Rewriting helper

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 Magento 2 overriding or Rewriting helper. In start we are overriding core Product helper. We are jut checking our rewrite is working or not. You can modify the helper as you want 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 Helper

sometimes, you may want to add new classes or override different functions in your Magento 2 module. Therefore, Magento 2 came up with the Helpers that are the right entity to fulfill your needs. A Helper in Magento 2 is an object that contains practical methods.Now we start to overriding or rewriting core Product helper. The helper we are overriding is Product helper.
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\Helper\Product" type="QaisarSatti\HelloWorld\Helper\Rewrite\Product" />
</config>

Step 2
The step2 to overriding or rewriting Magento2 Helper is to create a Product.php helper file in the following directory QaisarSatti/HelloWorld/Helper/Rewrite/

<?php
/**
* Catalog Product overridingHelper
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Qaisar Satti
*
*/

namespace QaisarSatti\HelloWorld\Helper\Rewrite;
class Product extends \Magento\Catalog\Helper\Product
{
   public function __construct()
   {
     echo "Our Rewrite Working"; die();
   }
}

As following code you can rewrite or override any Magento 2 helper using the same method.

Author: Qaisar Satti
Category: Magento 2
Last Modified: December 20, 2017


Magento 2 get latest order collection

Today we learn how to get latest order collection. You can simply add the setOrder entity_id to DESC or use created_at to DESC to your order collection. If you want to add limit simply add setpagesize

setPageSize(yournumberhere);

protected $_orderFactory;
public function __construct(

\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderFactory,

)
{

$this->_orderFactory = $orderFactory;

}
public function getLatestOrders() {
$orderCollection =$this->_orderFactory->create()->addFieldToSelect(array('*')); $orderCollection->setOrder('entity_id','DESC');
return $orderCollection;
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: May 24, 2018


Magento 2 add pagination on custom collection

Today, we’ll talk about how to get custom collection with magento 2 default pagination or use pager with custom collection.For any suggestions & question, please feel free to drop a comment.

First Step:

Get collection for pagination.

public function getNews() {
 //get values of current page
$page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
 //get values of current limit
$pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 1;
$newsCollection = $this->newscollectionFactory->create(); $newsCollection->addFieldToFilter('is_active',1); $newsCollection->setOrder('title','ASC'); $newsCollection->setPageSize($pageSize); $newsCollection->setCurPage($page);
return $newsCollection;
}

Second Step:
Now simply add the pagination to you collection

protected function _prepareLayout() {
parent::_prepareLayout();
$this->pageConfig->getTitle()->set(__('News'));
 if ($this->getNews()) {
$pager = $this->getLayout()->createBlock( 'Magento\Theme\Block\Html\Pager', 'qaisarsatti.news' )->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection( $this->getNews() );
$this->setChild('pager', $pager);
$this->getNews()->load();
}
return $this;
}

Third Step:
Now create a function to get the child block of pager.

public function getPagerHtml() {
return $this->getChildHtml('pager');
 }

Fourth Step:
in your phtml file add this code then pagination will be showing with limits.

<?php 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: December 29, 2017


Magento 2 get controller module action and router

Today, we’ll talk about how to get controller name, module name, action name and router name programmatically in Magento 2.For any suggestions & question, please feel free to drop a comment.

Controller name:
Controller is a class located in module Controller folder. Here is Controller file of module.

$this->getRequest()->getControllerName();

Module name:

$this->getRequest()->getModuleName();

Action name:
Action name is located in module Controller file. Here is Action Method controller.

$this->getRequest()->getActionName();

Router name:
Router are defined in module router.xml file. Here is Action Method controller.

$this->getRequest()->getRouteName();

Example:

If you test this code for home page it will give you following output.

Controller:index
Action:index
Route:cms
module:cms

You can use this code in both phtml and controller file.

Author: Qaisar Satti
Category: Magento 2
Last Modified: December 20, 2017


Override magento controller

Every Magento project requires a certain level of customization. This may involve adding a new element or overriding an existing one. Today, we’ll talk about how to override a magento controller. For any suggestions & question, please feel free to drop a comment.

First Step:

I am overriding the customer controller. First thing will create new module file.
The file location will me  will be

app/etc/modules/QaisarSatti_Customer.xml

<?xml version="1.0"?>
    <config>
     <modules>
          <QaisarSatti_Customer>
               <active>true</active>
               <codePool>local</codePool>
          </QaisarSatti_Customer>
      </modules>
    </config>

Second Step:

We will create module configuration file. So file location will be

app/code/local/QaisarSatti/Customer/etc/config.xml

<?xml version="1.0"?>
    <config>
        <modules>
            <QaisarSatti_Customer>
                <version>0.0.1</version>
            </QaisarSatti_Customer>
        </modules>
        <frontend>
            <routers>
                <customer>
                    <args>
                        <modules>
                            <QaisarSatti_Customer before="Mage_Customer">QaisarSatti_Customer</QaisarSatti_Customer>
                        </modules>
                    </args>
                </customer>
            </routers>
        </frontend>
    </config>

Third Step:

Now we will create the Our controller file.

app/code/local/QaisarSatti/Customer/controllers/AccountController.php

<?php

/**
* Overriding Customer account controller
*/

require_once Mage::getModuleDir('controllers', 'Mage_Customer') . DS . 'AccountController.php';

class QaisarSatti_Customer_AccountController extends Mage_Customer_AccountController {

public function ajaxAction() {  //if you want to create a custom method in customer controller
   echo 'Ajax cction is working!!';
}

public function loginAction() {
   echo 'Overring the Login Action is working';
}

}
Author: Qaisar Satti
Category: Magento
Last Modified: February 6, 2018


Magento 2 load product by id

There are three way to get product load in magento 2. First Object Manager second factory Method and third on is Api Repository.

Factory Method:

Best practice method always use this method.

namespace QaisarSatti\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{

  protected $_product;  


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

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function getLoadProduct()
    {
        $product_id=7;
        return $this->_productloader->create()->load($id);
    }

}

Api Repository:

This was introduce in Magento 2.1 by magento.

    namespace QaisarSatti\Module\Block;
    use Magento\Catalog\Api\ProductRepositoryInterface;
    class Product extends \Magento\Framework\View\Element\Template
     {
          protected $_productRepository;
       

          public function __construct(
         
            ProductRepositoryInterface $productRepository
          ) {
         

              $this->_productRepository = $productRepository;
          }
          public function getProduct()
          {
              $productId=7;
              return $product = $this->productRepository->getById($productId);
          }
      }

Object Manager:

No recommended method to use in magento2 but so magento use it so here it is just for knowledge.

$product_id=7;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
Author: Qaisar Satti
Category: Magento 2
Last Modified: December 20, 2017


Pages:1234