Magento - Redirect Customer from Observer Method
tl;dr: Correct observer code at the bottom.
A note before I answer: Make sure that the observer is being triggered; step through your code or use die('here');
. As written, your example method does not have the correct prototype to receive event observer data (missing an argument).
Using an event observer for redirect logic is totally appropriate in this context, as evinced by the core team explicitly passing the request and response objects in to the observer. Your attempt is good, but I think that you have conditions and configuration which cause execution to flow to Mage_Checkout_CartController::_goBack()
, specifically to the line
$this->_redirect('checkout/cart');
So we need to revise our approach. Now, you could prevent any request/response logic from processing after your event observer by manipulating the response and calling the Front Controller's sendResponse()
method as demonstrated below (nb: don't do this!):
public function moduleMethod($observer) //note I added a param
{
/* @var $response1 Mage_Core_Controller_Response_Http */
$response1 = $observer->getResponse(); // observers have event args
$url = 'http://www.example.com/';
$response1->setRedirect($url);
/* SHOULDN'T DO THIS */
Mage::app()->getFrontController()->sendResponse();
}
This should work, but I think it mixes up areas of concern by triggering output from an ethereal system component (EDA). Let's see if there's something in the command-control structure which we can use...
Just after the checkout_cart_add_product_complete
event execution comes to the cart controller's _goBack() method. The problem with this method name is that it does more than its name implies:
/**
* Set back redirect url to response
*
* @return Mage_Checkout_CartController
*/
protected function _goBack()
{
$returnUrl = $this->getRequest()->getParam('return_url');
if ($returnUrl) {
// clear layout messages in case of external url redirect
if ($this->_isUrlInternal($returnUrl)) {
$this->_getSession()->getMessages(true);
}
$this->getResponse()->setRedirect($returnUrl);
}
//...
}
It looks like we can just set a return_url
param on the request object and accomplish what we need.
public function moduleMethod(Varien_Event_Observer $observer)
{
$observer->getRequest()->setParam('return_url','http://www.google.com/');
}
I've tested this, and it should do the trick!
Magento 2.0 How to redirect in observer
This's how it can be done:
public function execute(\Magento\Framework\Event\Observer $observer)
{
# check if user is logged in
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if(!$customerSession->isLoggedIn())
{
$request = $objectManager->get('Magento\Framework\App\Request\Http');
//get instance for URL interface
/** @var \Magento\Framework\UrlInterface $urlInterface */
$urlInterface = $objectManager->get('Magento\Framework\UrlInterface');
// URL to redirect to
$url = $urlInterface->getUrl('customer/account/login');
if(strpos($request->getPathInfo(), '/customer/account/') !== 0)
{
# redirect to /customer/account/login
$observer->getControllerAction()
->getResponse()
->setRedirect($url);
}
}
}
that's it. Now it'll redirect to customer login page. I've tested this with event controller_action_predispatch
Magento2: redirect from Observer
Here i am writing some code for cart page redirecting.
In your module create a events.xml file
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_checkout_cart_index">
<observer name="my_predispatch_checkout_cart" instance="Namespace\Module\Observer\PredispatchCheckoutCart"/>
</event>
</config>
In your observer file yourmodule\Observer\PredispatchCheckoutCart.php
<?php
namespace Namespace\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
class PredispatchCheckoutCart implements ObserverInterface{
protected $_objectManager;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Checkout\Helper\Cart $_cartHelper
) {
$this->_objectManager = $objectManager;
$this->_cartHelper = $_cartHelper;
}
public function execute(\Magento\Framework\Event\Observer $observer){
//redirect to cart
$redirectUrl = $this->_cartHelper->getCartUrl();
$observer->getControllerAction()->getResponse()->setRedirect($redirectUrl);
}
}
How to redirect customer to assigned Magento website after system auto-login
In order to make this work, you must register an event in your /app/code/local/Extension/Module/etc/config.xml like this:
<customer_session_init>
<observers>
<sessioninit_handler>
<type>singleton</type>
<class>Extension_Module_Model_Observer</class>
<method>on_customer_session_init</method>
</sessioninit_handler>
</observers>
</customer_session_init>
Then create an Observer method in /app/code/local/Extension/Module/Model/Observer.php like so:
/*
** on customer session init, checks for current website id and redirects if no-match
*/
public function on_customer_session_init(Varien_Event_Observer $observer){
$customer = $observer->customer_session->getCustomer();
$customer_website_id = $customer->getWebsiteId();
$current_website_id = Mage::app()->getWebsite()->getId();
if ($customer_website_id != $current_website_id){
$website = Mage::app()->getWebsite($customer_website_id);
$request = $this->_getRequest();
$response = $this->_getResponse();
$url = $website->getDefaultStore()->getBaseUrl().substr($request->getRequestString(), 1);
$response->setRedirect($url);
}
return $this;
}
Related Topics
Wordpress Plugin -> Call to Undefined Function Wp_Get_Current_User()
What Does the Dot-Slash Do to PHP Include Calls
Forcing Access to _Php_Incomplete_Class Object Properties
How to Stop PHP Imagick Auto-Rotating Images Based on Exif 'Orientation' Data
How to Maintain Session in Curl in PHP
Single Session Login in Laravel
How to Set Session Timeout in Laravel
PHP Pdo Insert Batch Multiple Rows with Placeholders
PHP Soap Client for Uk Mail Webservice API
Chart.Js - Getting Data from Database Using MySQL and PHP
PHP Array VS [ ] in Method and Variable Declaration
How to Fetch All the Row of the Result in PHP MySQL
Require_Once () or Die() Not Working