Magento 2 Controller Response Types – Page, JSON, ROW, Redirect, Forward

Controller is a class located in the module Controller folder, responsible for a specific URL or group of URLs. Magento uses a front-controller architecture to process all the requests and responses. Magento 2 Controller consists of one or more files located in the Controller folder of the module. These files contain classes with actions, each includes an execute() method. 

There are two main types of controllers: frontend and backend. Their workflows are generally similar, but the admin controller differs slightly. In the admin controller, a permission-checking method invokes the form key.

For every action we have one controller class, It includes files with the execute() method. The execute method is called when the router matches the controller action class and is responsible for returning a response to the front controller. All controllers are extending the \Magento\Framework\App\Action\Action class which has a dispatch method that will call the execute method in the controller. 

How controller work?

It receives a request from the end-user (browser or command line), for example, http://example.com/route_name/controller/action

  • route_name is a unique name that is set in routes.xml.
  • The controller is the folder inside the Controller folder.
  • action is a class with an executed method to process requests.

How to create a Magento 2 Controller?

To Create Controller in Magento 2:

Step 1: Create routes.xml file

Step 2: Create a controller file

Step 3: Create a controller Layout file

Step 4: Create a controller Block file

Step 5: Create a controller template file

Step 6: Run all magento commands and launch url in the browser.

Types of Controller Response in Magento 2 

Magento 2 now introduces the Framework result object for handling requests that handle non-page results such as JSON, redirects, and other non-HTML returns.

Generally, in the Magento2 controller’s execute() function, there are instances where we need to return the JSON format data or even raw text data. The Controller in Magento 2 can return several response types depending on the purpose of the result.

 There are five Controller Response Types in Magento

  •  Page
  • JSON 
  • ROW 
  • Redirect 
  • Forward

Responses Types

(01) Page: This returns HTML loaded from a layout handle.

Class: \Magento\Framework\View\Result\Page

A. Create Controller File.

File Path: app/code/DCKAP/ControllerResponseTypes/Controller/Index/Resultpage.php

<?php

	namespace DCKAP\ControllerResponseTypes\Controller\Index;

	use Magento\Framework\App\Action\Action;
	use Magento\Framework\App\Action\Context;
	use Magento\Framework\App\RequestInterface;
	use Magento\Framework\View\Result\PageFactory;

	class Resultpage extends Action
	{
	/**
	 * The PageFactory to render with.
	 *
	 * @var PageFactory
	 */
protected $_resultsPageFactory;

	/**
	 * Set the Context and Result Page Factory from DI.
	 * @param Context     $context
	 * @param PageFactory $resultPageFactory
	 */
	public function __construct(
	    Context $context,
	    PageFactory $resultPageFactory
	) {
	    $this->_resultsPageFactory = $resultPageFactory;
	    parent::__construct($context);
	}

	/**
	 * Show the Controller Response Types Page Result.
	 *
	 * @return \Magento\Framework\View\Result\Page
	 */
	public function execute() {
	    return $this->_resultsPageFactory->create();
	}
	}

B. Create a Block file.

File Path: app/code/DCKAP/ControllerResponseTypes/Block/ControllerResponseTypes.php

<?php

	namespace DCKAP\ControllerResponseTypes\Block;

	class ControllerResponseTypes extends \Magento\Framework\View\Element\Template
	{        
	public function __construct(
	    \Magento\Backend\Block\Template\Context $context,        
	    array $data = []
	)
	{        
	    parent::__construct($context, $data);
	}
public function getHelloWorld()
	{
	    return 'Hello World';
	}

	public function getPageResonse()
	{
	   return "Controller Response Page Result";
	}

	}

C. Create a Layout file.

File Path: app/code/DCKAP/ControllerResponseTypes/view/frontend/layout/controllerresponsetypes_index_resultpage.xml

<?xml version="1.0"?>
	<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
	    <head>
	        <title>
	            DCKAP Controller Response Types (Page Result)
	        </title>
	    </head>
	    <body>
	        <referenceContainer name="content">
	            <block class="DCKAP\ControllerResponseTypes\Block\ControllerResponseTypes" name="pageresult_response" template="DCKAP_ControllerResponseTypes::result_page.phtml" />
	        </referenceContainer>
	    </body>
	</page>

D. Create a PHTML file.

File Path: app/code/DCKAP/ControllerResponseTypes/view/frontend/templates/result_page.phtml

<h2>
	    <?php echo $block->getPageResonse(); ?>
	</h2>

Run the magento commands and launch the below url.

URL: www.example.com/controllerresponsetypes/index/resultpage

(02) JSON: this returns a response in JSON format. It can be used in API or AJAX requests.

Class: \Magento\Framework\Controller\Result\Json

A. Create Controller file.

File Path: app/code/DCKAP/ControllerResponseTypes/Controller/Index/Resultjson.php

<?php

	namespace DCKAP\ControllerResponseTypes\Controller\Index;

	use Magento\Framework\App\Action\Action;
	use Magento\Framework\App\Action\Context;
	use Magento\Framework\App\RequestInterface;
	use Magento\Framework\View\Result\PageFactory;

	class Resultjson extends Action
	{
	    /**
	     * The PageFactory to render with.
	     *
	     * @var PageFactory
	     */
	    protected $_resultsPageFactory;

	    /**
	     * Set the Context and Result Page Factory from DI.
	     * @param Context     $context
	     * @param PageFactory $resultPageFactory
	     */
public function __construct(
	        Context $context,
	        PageFactory $resultPageFactory
	    ) {
	        $this->_resultsPageFactory = $resultPageFactory;
	        parent::__construct($context);
	    }

	    /**
	     * Show the Controller Response Types JSON Result.
	     *
	     * @return \Magento\Framework\View\Result\Page
	     */
	    public function execute() {
	        return $this->_resultsPageFactory->create();
	    }
	}	

Create a new Controller file for JSON response.

File Path: app/code/DCKAP/ControllerResponseTypes/Controller/Index/Responsejson.php

<?php

	namespace DCKAP\ControllerResponseTypes\Controller\Index;

	use Magento\Framework\App\Action\Action;
	use Magento\Framework\App\Action\Context;

	class Responsejson extends Action
	{
	    /**
	     * The JsonResultFactory to render with.
	     *
	     * @var jsonResultFactory
	     */
	    protected $jsonResultFactory;

	    /**
	     * Set the Context and Result Page Factory from DI.
	     * @param Context     $context
	     * @param JsonResultFactory $jsonResultFactory
  */
	    public function __construct(
	        Context $context,
	        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory
	    ) {
	        $this->jsonResultFactory = $jsonResultFactory;
	        parent::__construct($context);
	    }

	    /**
	     * Show the Controller Response Types JSON Result.
	     *
	     * @return \Magento\Framework\Controller\Result\Json
	     */

	    public function execute()
	    {
	        $result = $this->jsonResultFactory->create();
	        $data = [
	            'foo'  => 'bar',
	            'success' => true
	        ];
	        $result->setData($data);
	        return $result;        
	    }
	    
	}

B. Create a Layout file.

File Path: app/code/DCKAP/ControllerResponseTypes/view/frontend/layout/controllerresponsetypes_index_resultjson.xml

<?xml version="1.0"?>
	<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
	    <head>
	        <title>
	            DCKAP Controller Response Types
	        </title>
	    </head>
	    <body>
	    </body>
	</page>

Create a Layout file for JSON response.

File Path: app/code/DCKAP/ControllerResponseTypes/view/frontend/layout/controllerresponsetypes_index_responsejson.xml

C. Create a PHTML file

File Path: app/code/DCKAP/ControllerResponseTypes/view/frontend/templates/result_json.phtml

<button class="result_json">Get JSON Result</button>
	<script type="text/javascript">
		require(['jquery', 'jquery/ui'], function($){
			$(document).on('click','.result_json',function (){
	            $.ajax({
	                context: '#ajaxresponse1',
    url: '<?= $this->getBaseUrl();?>controllerresponsetypes/index/responsejson',
	                type: "GET",
	            }).done(function (response) {
	                alert(response.success);
	            });	
			});
		});
	</script>

Run the magento commands and launch the below url.

URL: www.example.com/controllerresponsetypes/index/resultjson

(03) Raw: this returns whatever you want to be returned.

Class: \Magento\Framework\Controller\Result\Raw

A. Create Controller file.

File Path: app/code/DCKAP/ControllerResponseTypes/Controller/Index/Resultraw.php

<?php

	namespace DCKAP\ControllerResponseTypes\Controller\Index;

	use Magento\Framework\App\Action\Action;
	use Magento\Framework\App\Action\Context;
	use Magento\Framework\Controller\Result\RawFactory;

	class Resultraw extends Action
	{
	    /**
	     * Set the Context and Result Page Factory from DI.
	     * @param Context     $context
	     * @param RawResultFactory $rawResultFactory
	     */
	    public function __construct(
	        Context $context,
	        RawFactory $rawResultFactory
	    ) {
	        $this->rawResultFactory = $rawResultFactory;
	        parent::__construct($context);
   }

	    /**
	     * Show the Controller Response Types Raw Result.
	     *
	     * @return \Magento\Framework\Controller\Result\Raw
	     */
	    public function execute() {
	        $result = $this->rawResultFactory->create();
	        $result->setHeader('Content-Type', 'text/xml');
	        $result->setContents("<note>
	                                <to>Tove</to>
	                                <from>Jani</from>
	                                <heading>Reminder</heading>
	                                <body>Don't forget me this weekend!</body>
	                            </note>");
	        return $result;
	    }
	}

B. Create a Layout file.

File Path: app/code/DCKAP/ControllerResponseTypes/view/frontend/layout/controllerresponsetypes_index_resultraw.xml

<?xml version="1.0"?>
	<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
	    <head>
	        <title>
	            DCKAP Controller Response Types (Raw Result)
	        </title>
	    </head>
	</page>	

Run the magento commands and launch the below url.

URL: www.example.com/controllerresponsetypes/index/resultraw

(04) Forward: this internally forwards to another controller without changing the URL.

Class: \Magento\Framework\Controller\Result\Forward

A. Create a Controller file.

File Path: app/code/DCKAP/ControllerResponseTypes/Controller/Index/Resultforward.php

<?php

	namespace DCKAP\ControllerResponseTypes\Controller\Index;
	 
	use Magento\Framework\App\Action;
	use Magento\Framework\App\Action\Context;
	use Magento\Framework\App\ResponseInterface;
	use Magento\Framework\Controller\Result\Forward;
	use Magento\Framework\Controller\Result\ForwardFactory;
	use Magento\Framework\Controller\ResultInterface;
	 
	/**
	* Class Resultforward
	*
	* @package DCKAP\ControllerResponseTypes\Controller\Index
	*/
	class Resultforward extends Action\Action
	{
	 
	   /**
	    * @var ForwardFactory
	    */
	   protected $_resultForwardFactory;
	 
	   /**
	    * Page4 constructor.
	    * @param Context $context
	    * @param ForwardFactory $_resultForwardFactory
	    */
	   public function __construct(
	       Context $context,
	       ForwardFactory $_resultForwardFactory
	   ) {
    $this->_resultForwardFactory = $_resultForwardFactory;
	       parent::__construct($context);
	   }
	 
	   /**
	    *  Forward home page
	    *
	    * @return \Magento\Framework\Controller\Result\Forward
	    */
	   public function execute()
	   {
	       $resultForward = $this->_resultForwardFactory->create();
	       $resultForward->setController('index')
	           ->setModule('cms')
	           ->forward('index');
	       return $resultForward;
	   }
	}	

B. Create a Layout file.

File Path: app/code/DCKAP/ControllerResponseTypes/view/frontend/layout/controllerresponsetypes_index_resultforward.xml

<?xml version="1.0"?>
	<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
	    <head>
	        <title>
	            DCKAP Controller Response Types (Forward Result)
	        </title>
	    </head>
	</page>

Run the magento commands and launch the below url.

URL: www.example.com/controllerresponsetypes/index/resultforward

(05) Redirect: this represents a 301 or 302 redirect. It is used when a user needs to be redirected to a different URL.

Class: \Magento\Framework\Controller\Result\Redirect

A. Create a Controller file.

File Path: app/code/DCKAP/ControllerResponseTypes/Controller/Index/Resultredirect.php

<?php

	namespace DCKAP\ControllerResponseTypes\Controller\Index;

	use Magento\Framework\App\Action\Action;
	use Magento\Framework\App\Action\Context;
	use Magento\Framework\App\RequestInterface;
	use Magento\Framework\View\Result\PageFactory;
	use Magento\Store\Model\StoreManagerInterface;
	use Magento\Framework\Controller\Result\Redirect;

	/**
	* Class Resultredirect
	*
	* @package DCKAP\ControllerResponseTypes\Controller\Index
	*/
	class Resultredirect extends Action
	{
	     /**
	     * @var \Magento\Framework\Controller\Result\RedirectFactory
	     */
	    protected $resultRedirectFactory;

	    public $_storeManager;

	    public function __construct(
	        Context $context,
	        StoreManagerInterface $storeManager,
	        Redirect $resultRedirectFactory
	    ) {
	        $this->resultRedirectFactory = $resultRedirectFactory;
	        $this->_storeManager=$storeManager;
	        parent::__construct($context);
	        }

	        /**
	         * Show the Controller Response Types Redirect Result.
	         *
	         * @return (\Magento\Framework\Controller\Result\Redirect
	         */
	    public function execute()
	    {
	        $resultRedirect = $this->resultRedirectFactory->create();
	        $redirectLink = $this->_storeManager->getStore()->getBaseUrl().'customer/account/login'; 
	        $resultRedirect->setUrl($redirectLink);
	        return $resultRedirect;
	    }
	}

B. Create a Layout file.

File Path: app/code/DCKAP/ControllerResponseTypes/view/frontend/layout/controllerresponsetypes_index_resultredirect.xml

<?xml version="1.0"?>
	<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
	    <head>
	        <title>
	            DCKAP Controller Response Types (Redirect Result)
	        </title>
	    </head>
	</page>

Run the magento commands and launch the below url.

URL: www.example.com/controllerresponsetypes/index/resultredirect

Magento 2 Controller Response

This blog has provided insight into Magento 2 Controller Response Types. The above data helps you to enhance your understanding of how developers can utilize controllers based on customization requirements. With this knowledge, developers can better tailor their approaches to suit specific needs within Magento 2 development projects.

About The Author

Discover What You’re Missing

Get in touch with us for expert consultation