:::: MENU ::::
Posts tagged with: controller

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


Magento 2 add pagination custom collection

Today we talk about Magento 2 add pagination custom collection. 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: July 12, 2018


Magento 2 get controller module action and router

Today we talk about Magento 2 get controller module action and router.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: July 12, 2018


Override magento controller

Today, we’ll talk about how to override a magento controller.Every Magento project requires a certain level of customization. This may involve adding a new element or overriding an existing one. 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: July 12, 2018


Magento 2 load product by id

Tpday we talk about how in 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: July 12, 2018


Magento 2 create a module or extension

In start of learning Magento 2 every developer must need to learn how to create a simple module or extension. But before start it you must have initial knowledge of Php too. Here it is easy way to create the extension or module in magento 2. In this custom module we have to learn how to create router,controller,block,xml layout and phtml files. Combination of these file will make a simple Hello World module. That will listed in admin module list and show the output on fronteend So lets start the fun learning of magento 2. Before we start playing with magento 2 we must do these tasks disabled cache from admin panel or you can do it via command (php bin/magento cache:disable) and set the developer mode on by following command (php bin/magento deploy:mode:set developer).
Note: Check code folder in your app directory. If not have code folder then create it.

First Step:

First step is register your module with registration.php . The file location will be

app/code/QaisarSatti/HelloWorld/registration.php

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

\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'QaisarSatti_HelloWorld',
__DIR__
);

Second Step:

Create module.xml file. In this file you will define your module name and version. The file location will be

app/code/QaisarSatti/HelloWorld/etc/module.xml

<?xml version="1.0"?>
<!--/**
* Simple Hello World Module
*
* @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:Module/etc/module.xsd">
<module name="QaisarSatti_HelloWorld" schema_version="0.0.1" setup_version="0.0.1"/>
</config>

Third Step:

Create the block file.The file location will be

app/code/QaisarSatti/HelloWorld/Block/HelloWorld.php

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

namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
public function _prepareLayout()
{
parent::_prepareLayout();
$this->pageConfig->getTitle()->set(__('First Hello World Module'));
return $this;
}
}

Fourth Step:

Create the controller file.The file location will be

app/code/QaisarSatti/HelloWorld/Controller/Index/Index.php

<?php
/**
* Simple Hello World Module
*
* @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();
}
}

Fifth Step:

Create frontend router. Here you will declare your frontName make sure it is unique name.

app/code/QaisarSatti/HelloWorld/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--/**
* Simple Hello World Module
*
* @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>

Sixth Step:

Create frontend template file.

app/code/QaisarSatti/HelloWorld/view/frontend/templates/HelloWorld.phtml

<?php
/**
* Catalog Product Rewrite Helper
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email [email protected]
*
*/

echo 'Hello World';
?>

Seventh Step:

Add frontend layout handle for your router. First letter will be your frontName as you mention in your router.xml file (helloworld) then your folder name (index) then in the last your controller name (Index).

app/code/QaisarSatti/HelloWorld/view/frontend/layout/helloworld_index_index.xml

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

Now your simple hello world module is complete. You can do following step to activate this module.

php bin/magento module:enable QaisarSatti_HelloWorld

You can see the output of module front page by http::yoururl/helloworld

Github Links

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


Pages:12