Question

I have extended the core controller of Magento_Newsletter NewAction controller. My aim is to add a thank you page after a successful subscription. and I'm having a problem because I wan't it to redirect to a cms page. Just correct me if I'm wrong.

Thanks

Was it helpful?

Solution

You will need to override this controller below:

vendor/magento/module-newsletter/Controller/Subscriber/Confirm.php

To do that you will need to create your custom module with this configurations:

File app/code/YourCompany/YourModule/etc/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">    
    <preference for="Magento\Newsletter\Controller\Subscriber\Confirm" type="YourCompany\YourModule\Controller\Subscriber\Confirm" />
</config>

Let’s rewrite execute() function of class Magento\Newsletter\Controller\Subscriber\Confirm. We will just change the final redirect.

File app/code/YourCompany/YourModule/Controller/Subscriber/Confirm.php

<?php

namespace YourCompany\YourModule\Controller\Subscriber;

class Confirm extends \Magento\Newsletter\Controller\Subscriber
{
    /**
     * Subscription confirm action
     * @return void
     */
    public function execute()
    {
        $id = (int)$this->getRequest()->getParam('id');
        $code = (string)$this->getRequest()->getParam('code');

        if ($id && $code) {
            /** @var \Magento\Newsletter\Model\Subscriber $subscriber */
            $subscriber = $this->_subscriberFactory->create()->load($id);

            if ($subscriber->getId() && $subscriber->getCode()) {
                if ($subscriber->confirm($code)) {
                    // Success message
                    $this->messageManager->addSuccess(__('Your subscription has been confirmed.'));
                } else {
                    $this->messageManager->addError(__('This is an invalid subscription confirmation code.'));
                }
            } else {
                $this->messageManager->addError(__('This is an invalid subscription ID.'));
            }
        }
        $this->getResponse()->setRedirect($this->_storeManager->getStore()->getBaseUrl());
    }
}

You can change the line that I commented above like // Success message

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top