3

I write an observer to observe the customer_register_success event and run the following codes to do the redirect but failed. Can anyone help?

$url = $this->url->getUrl('/');
$observer->getControllerAction()->getResponse()->setRedirect($url);
$this->logger->debug("Redirect to: {$url}");
TFS
  • 4,319
  • 17
  • 46
  • 74

2 Answers2

22

I think the problem is that your redirect is occuring before the default redirect and hence has no effect. Here's a module that does the job:

Module directory structure:

|   registration.php
|   
+---etc
|   |   di.xml
|   |   module.xml
|   |   
|   \---frontend
|           events.xml
|           
+---Observer
|       Register.php
|       
\---Plugin
        Redirect.php

di.xml :

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Magento\Customer\Model\Account\Redirect">
        <plugin name="NewAcctRedirectPlug" type="Your\Module\Plugin\Redirect" disabled="false" sortOrder="1"/>
    </type>

</config>

events.xml:

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_register_success">
        <observer name="custom_redirect_register_success" instance="Your\Module\Observer\Register" disabled="false"/>
    </event>
</config>

Register.php:

<?php

namespace Your\Module\Observer;


use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Registry;

class Register implements ObserverInterface
{
    protected $coreRegistry;

    public function __construct(Registry $registry)
    {
        $this->coreRegistry = $registry;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $this->coreRegistry->register('is_new_account', true);
    }
}

Redirect.php:

<?php

namespace Your\Module\Plugin;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Registry;
use Magento\Framework\UrlInterface;

class Redirect
{
    protected $coreRegistry;

    protected $url;

    protected $resultFactory;

    public function __construct(Registry $registry, UrlInterface $url, ResultFactory $resultFactory)
    {
        $this->coreRegistry = $registry;
        $this->url = $url;
        $this->resultFactory = $resultFactory;
    }

    public function aroundGetRedirect ($subject, \Closure $proceed)
    {
        if ($this->coreRegistry->registry('is_new_account')) {
            /** @var \Magento\Framework\Controller\Result\Redirect $result */
            $result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
            $result->setUrl($this->url->getUrl('custom/path'));
            return $result;
        }

        return $proceed();
    }
}

It works by setting a flag in the core registry when the customer_register_success event occurs and then checks for that flag and returns an alternate redirect path when the redirect for a successful customer authentication is requested instead of the default 'My Account' page. Hope this helps.

Aaron Allen
  • 9,009
  • 2
  • 26
  • 36
  • It does not work and it display an error in the create account page: We can't save the customer.. But the account is actually created successfully and the welcome email is sent out successfully too. – TFS Aug 19 '16 at 09:20
  • You should check the var/log/system.log file to see what the error is. I tested the module and it works in 2.1, can't vouch for other versions. – Aaron Allen Aug 19 '16 at 09:27
  • I removed all files under var/* and tried again. It works now. Thanks! – TFS Aug 19 '16 at 09:35
  • Thanks it worked like charm in my end! been looking for this one. Keep sharing :) – MazeStricks Sep 18 '17 at 06:16
  • 1
    I have a question about this one. I'm having a problem with the website. If I log out the user it will give me an error. and if I go to the homepage it is not logged in, but if I visit on other pages of the site it is working fine. Thanks – MazeStricks Sep 18 '17 at 14:35
  • How to get customer details in aroundGetRedirect? – Hardik Jun 28 '18 at 09:34
  • Facing the same problem, Its not working in home page. The action does not goes to the Redirect.php it goes till Register.php: – fernandus Jan 02 '19 at 09:59
  • @AaronAllen observer is working fine but plugin is not working it is redirecting to my account page instead of custom page. – sumeet bajaj May 29 '19 at 15:05
  • @AaronAllen,Why we need observer as we are already plugin to override the core file?Please clarify it more. – akgola Sep 24 '19 at 13:15
  • Thanks, it works on Magento 2.3.5p1 ! I replaced 'custom/path' with 'checkout' – Thomas May 09 '20 at 00:12
  • It does not work and it display an error in the create account page: We can't save the customer.. in M 2.4.2 version. Any help for this version? – Vipul Jethva Aug 26 '21 at 07:16
0

Another solution could be using the after plugin.

app/code/Vendor/Module/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\Controller\Account\CreatePost">
        <plugin name="VendorCustomerCreatePost"
                type="Vendor\Module\Plugin\CustomerCreatePost"/>
    </type>
</config>

app/code/Vendor/Module/Plugin/CustomerCreatePost.php

<?php

namespace Vendor\Module\Plugin;

use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Controller\Account\CreatePost; use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\Result\RedirectFactory; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException;

class CustomerCreatePost { private RedirectFactory $redirectFactory; private CustomerRepositoryInterface $customerRepositoryInterface;

public function __construct(
    RedirectFactory $redirectFactory,
    CustomerRepositoryInterface $customerRepositoryInterface
)
{
    $this-&gt;redirectFactory = $redirectFactory;
    $this-&gt;customerRepositoryInterface = $customerRepositoryInterface;
}

/**
 * @param CreatePost $subject
 * @param Redirect $result
 * @return Redirect
 */
public function afterExecute(CreatePost $subject, Redirect $result): Redirect
{
    $request    = $subject-&gt;getRequest();
    $emailPost  = $request-&gt;getParam('email');
    try {
        $customer = $this-&gt;customerRepositoryInterface-&gt;get($emailPost);
        $customerId = $customer-&gt;getId();

        if($customerId){
            $url = 'https://example.com/custom-page-uri';
            return $this-&gt;redirectFactory-&gt;create()
                -&gt;setUrl($url);
        }
    } catch (NoSuchEntityException $e) {
    } catch (LocalizedException $e) {
    }

    return $result;
}

}

Milan Chandro
  • 681
  • 6
  • 17