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}");
1
  • Are you seeing any errors? Is your debug message getting triggered? Commented Aug 17, 2016 at 19:29

2 Answers 2

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.

11
  • 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
    Commented Aug 19, 2016 at 9: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. Commented Aug 19, 2016 at 9:27
  • I removed all files under var/* and tried again. It works now. Thanks!
    – TFS
    Commented Aug 19, 2016 at 9:35
  • Thanks it worked like charm in my end! been looking for this one. Keep sharing :) Commented Sep 18, 2017 at 6: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 Commented Sep 18, 2017 at 14:35
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->redirectFactory = $redirectFactory;
        $this->customerRepositoryInterface = $customerRepositoryInterface;
    }

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

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

        return $result;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.