Magento 2 Forward and Redirect

In this example, we focus on forward and redirect. Source code can be download from bottom link.

Project structure

+ [app] 
   + [code]
        + [Tutorial]  <--  namespace
            + [Chapter2]  <-- module
                + [Block]
                    + ThankYouMessage.php
                + [etc]
                    + [frontend]
                         + routes.xml
                    + module.xml
                + registration.php
                + [Controller]
                    + [Purchase]
                       +  Complete.php
                       +  Message.php
                + [view]
                    + [frontend]
                    + [layout]
                         + thankyou_purchase_message.xml
                    + [templates]
                         + thankyou.phtml

 

Controller

When Purchase controller get called it handled the Complete action request and forward along the parameters to Message action.

<?php

namespace Tutorial\Chapter2\Controller\Purchase;

class Complete extends \Magento\Framework\App\Action\Action {

	protected $resultPageFactory;

	public function __construct(\Magento\Framework\App\Action\Context $context,
                              \Magento\Framework\View\Result\PageFactory $resultPageFactory)
  {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
  }

	/**
	 * Sets the content of the response
	 */
  public function execute() {

    $parameters =array('product'=>'Power Bank','tranxId'=>'TRX-1234');

    $this->_forward('Message','Purchase','thankyou',  $parameters );

  }

}

 

Block

<?php
namespace Tutorial\Chapter2\Block;

class ThankYouMessage extends \Magento\Framework\View\Element\Template
{
    public function getThankYouMessage()
    {
        $product = $this->getRequest()->getParam('product');
        $tranxId = $this->getRequest()->getParam('tranxId');

        $message = 'Thank you for your purchase! <br/>' .
                   'Product: ' . $product . ' <br/> ' .
                   'Transaction ID:' . $tranxId;

        return $message;

    }
}

 

Layout

<?xml version="1.0" ?>
<page layout="1column" 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="Tutorial\Chapter2\Block\ThankYouMessage" name="thankyou" template="thankyou.phtml" />
        </referenceContainer>
    </body>
</page>

 

Templates

<h1><?php echo $this->getThankYouMessage(); ?></h1>

 

Result

http://localhost:8080/magento/thankyou/purchase/complete

screen-shot-2016-12-16-at-1-25-48-am

 

Download

Source code

Magento 2 Forward and Redirect

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.