1

I am facing issue with newsletter. it suppose to subscribe user in newsletter and send them email which seems not working

execute method is not even calling. on direct accessing the url or using subscribe button

Please take a look & share your thoughts why its not working.

Thankyou

I click a button on frontend it send post request to

$this->getUrl('newsletter/subscriber/new', ['_secure' => true]);

Default.xml

<referenceContainer name="after.body.start">
        <block class="Rokanthemes\Themeoption\Block\Newsletterpopup" name="newsletter_popup" template="newsletterpopup.phtml" after="-"/>
    </referenceContainer>

phtml file

<?php if($block->getConfig('enable') > 0){ ?>
     <!--style>
            #newsletter_pop_up{max-height: 100%;}
            #newsletter_pop_up #recaptcha1 {padding-top: 5px;}
     </style-->
<div id="newsletter_pop_up" class="newsletterpopup">
    <div href="javascript: void(0);" class="btn-close newletter_popup_close"><span></span></div>
    <div class="row border">
        <div class="col-md-12">
            <div class="content-popup"><?php echo $block->getConfig('content');?>
                <form class="form subscribe"
                    novalidate
                    action="<?= $block->escapeUrl($block->getFormActionUrl()) ?>"
                    method="post"
                    data-mage-init='{"validation": {"errorClass": "mage-error"}}'
                    id="newsletter-validate-detail">
                    <div class="field newsletter">
                        <div class="control">
                            <div class="discount-text">
                                <h1>SAVE 10% ON YOUR FIRST ORDER</h1>
                                <p>Subscribe Now & Get a Free Coupon Code. The Code will be emailed to your provided Email Address.</p>
                            </div>
                            <input type="text" name="username" id="news-user" placeholder="<?php /* @escapeNotVerified */ echo __('Enter your Your Name') ?>">
                            <input name="email" type="email" id="newsletter-popup"
                                        placeholder="<?php /* @escapeNotVerified */ echo __('Enter your email address') ?>"
                                        data-validate="{required:true, 'validate-email':true}"/>
                        </div>
                    </div>
                    <div class="actions">
                        <button class="action subscribe primary" title="<?php /* @escapeNotVerified */ echo __('Subscribe Now') ?>" type="submit">
                            <span><?php echo __('Subscribe Now'); ?></span>
                        </button>
                    </div>
                    <div class="subscribe-bottom">
                        <p>Not Valid With Any other Offer</p>
                        <!-- <input type="checkbox" id="newsletter_popup_dont_show_again">
                        <label for="newsletter_popup_dont_show_again"><?php //echo __("Do not show this popup again")?></label> -->
                    </div>
                </form> 
            </div>
        </div>
    </div>
</div>

Controller

<?php
        /**
         *
         * Copyright © Magento, Inc. All rights reserved.
         * See COPYING.txt for license details.
         */
        
        namespace Magento\Newsletter\Controller\Subscriber;
        
        use Magento\Customer\Api\AccountManagementInterface as CustomerAccountManagement;
        use Magento\Customer\Model\Session;
        use Magento\Customer\Model\Url as CustomerUrl;
        use Magento\Framework\App\Action\Context;
        use Magento\Framework\App\Action\HttpPostActionInterface;
        use Magento\Framework\App\Config\ScopeConfigInterface;
        use Magento\Framework\App\ObjectManager;
        use Magento\Framework\Exception\LocalizedException;
        use Magento\Framework\Phrase;
        use Magento\Framework\Validator\EmailAddress as EmailValidator;
        use Magento\Newsletter\Controller\Subscriber as SubscriberController;
        use Magento\Newsletter\Model\Subscriber;
        use Magento\Store\Model\ScopeInterface;
        use Magento\Store\Model\StoreManagerInterface;
        use Magento\Newsletter\Model\SubscriberFactory;
        
        /**
         * New newsletter subscription action
         *
         * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
         */
        class NewAction extends SubscriberController implements HttpPostActionInterface
        {
            /**
             * @var CustomerAccountManagement
             */
            protected $customerAccountManagement;
        
            /**
             * @var EmailValidator
             */
            private $emailValidator;
        
            /**
             * Initialize dependencies.
             *
             * @param Context $context
             * @param SubscriberFactory $subscriberFactory
             * @param Session $customerSession
             * @param StoreManagerInterface $storeManager
             * @param CustomerUrl $customerUrl
             * @param CustomerAccountManagement $customerAccountManagement
             * @param EmailValidator $emailValidator
             */
            public function __construct(
                Context $context,
                SubscriberFactory $subscriberFactory,
                Session $customerSession,
                StoreManagerInterface $storeManager,
                CustomerUrl $customerUrl,
                CustomerAccountManagement $customerAccountManagement,
                EmailValidator $emailValidator = null
            ) {
                $this->customerAccountManagement = $customerAccountManagement;
                $this->emailValidator = $emailValidator ?: ObjectManager::getInstance()->get(EmailValidator::class);
                parent::__construct(
                    $context,
                    $subscriberFactory,
                    $customerSession,
                    $storeManager,
                    $customerUrl
                );
            }
        
            /**
             * Validates that the email address isn't being used by a different account.
             *
             * @param string $email
             * @throws LocalizedException
             * @return void
             */
            protected function validateEmailAvailable($email)
            {
                $websiteId = $this->_storeManager->getStore()->getWebsiteId();
                if ($this->_customerSession->isLoggedIn()
                    && ($this->_customerSession->getCustomerDataObject()->getEmail() !== $email
                    && !$this->customerAccountManagement->isEmailAvailable($email, $websiteId))
                ) {
                    throw new LocalizedException(
                        __('This email address is already assigned to another user.')
                    );
                }
            }
        
            /**
             * Validates that if the current user is a guest, that they can subscribe to a newsletter.
             *
             * @throws LocalizedException
             * @return void
             */
            protected function validateGuestSubscription()
            {
                if ($this->_objectManager->get(ScopeConfigInterface::class)
                        ->getValue(
                            Subscriber::XML_PATH_ALLOW_GUEST_SUBSCRIBE_FLAG,
                            ScopeInterface::SCOPE_STORE
                        ) != 1
                    && !$this->_customerSession->isLoggedIn()
                ) {
                    throw new LocalizedException(
                        __(
                            'Sorry, but the administrator denied subscription for guests. Please <a href="%1">register</a>.',
                            $this->_customerUrl->getRegisterUrl()
                        )
                    );
                }
            }
        
            /**
             * Validates the format of the email address
             *
             * @param string $email
             * @throws LocalizedException
             * @return void
             */
            protected function validateEmailFormat($email)
            {
                if (!$this->emailValidator->isValid($email)) {
                    throw new LocalizedException(__('Please enter a valid email address.'));
                }
            }
        
            /**
             * New subscription action
             *
             * @return \Magento\Framework\Controller\Result\Redirect
             */
            public function execute()
            {
                $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
                $logger = new \Zend\Log\Logger();
                $logger->addWriter($writer);
                $logger->info('Your text message');
                if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
                    $email = (string)$this->getRequest()->getPost('email');
        
                    try {
                        $this->validateEmailFormat($email);
                        $this->validateGuestSubscription();
                        $this->validateEmailAvailable($email);
        
                        $subscriber = $this->_subscriberFactory->create()->loadByEmail($email);
                        if ($subscriber->getId()
                            && (int) $subscriber->getSubscriberStatus() === Subscriber::STATUS_SUBSCRIBED
                        ) {
                            throw new LocalizedException(
                                __('This email address is already subscribed.')
                            );
                        }
        
                        $status = (int) $this->_subscriberFactory->create()->subscribe($email);
                        $this->messageManager->addSuccessMessage($this->getSuccessMessage($status));
                    } catch (LocalizedException $e) {
                        $this->messageManager->addErrorMessage($e->getMessage());
                    } catch (\Exception $e) {
                        $this->messageManager->addExceptionMessage($e, __('Something went wrong with the subscription.'));
                    }
                }
                /** @var \Magento\Framework\Controller\Result\Redirect $redirect */
                $redirect = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT);
                $redirectUrl = $this->_redirect->getRedirectUrl();
                return $redirect->setUrl($redirectUrl);
            }
        
            /**
             * Get success message
             *
             * @param int $status
             * @return Phrase
             */
            private function getSuccessMessage(int $status): Phrase
            {
                if ($status === Subscriber::STATUS_NOT_ACTIVE) {
                    return __('The confirmation request has been sent.');
                }
        
                return __('Thank you for your subscription.');
            }
        }
7
  • any thoughts ?? Nov 27 '20 at 7:10
  • what you getting on direct controller hit ? Add your routes.xml in question.
    – Pawan
    Nov 27 '20 at 7:16
  • Hello Pawan i have updated question Nov 27 '20 at 7:18
  • I get nothing in response as page gets redirected to self with Status Code: 302. could you please help debugging it ? Nov 27 '20 at 7:18
  • any thoughts ?? Nov 27 '20 at 10:32
0

newsletter/subscriber/new does not hit because of Newsletter module is disabled from Magento admin.

Goto Admin navigate to Store -> Configuration -> Customers -> Newsletter -> General Options and here make Enabled = Yes to resolve the issue.

If you check vendor/magento/module-newsletter/etc/frontend/events.xml and here you can controller_action_predispatch_newsletter event fire an observer \Magento\Newsletter\Observer\PredispatchNewsletterObserver::execute where url going to Default no route instead of hitting \Magento\Newsletter\Controller\Subscriber\NewAction::execute.

Also note that new Action is implementing \Magento\Framework\App\Action\HttpPostActionInterface so only post request support for this url, If you are trying to access via GET then it wil be 404.

11
  • Hello Amit, thanks for the answer. i want to let you know that its Enabled from backend. I have a custom form that has form action as $this->getUrl('newsletter/subscriber/new', ['_secure' => true]); this calls the above controller but when i add log or use echo exit in it. i dont see any changes, That simply means execute method is not calling Nov 27 '20 at 9:57
  • Cany you please take a look at the file above & advise where i can debug ? Nov 27 '20 at 9:57
  • Are you using POST method? means <form action` should post?
    – Amit Bera
    Nov 27 '20 at 10:51
  • yes sir its a post method Nov 27 '20 at 10:55
  • i have updated & added called phtml code Nov 27 '20 at 10:56
-1

In Magento 2, the controller class does not need to add the "Action" suffix. You have defined the controller class as:

class NewAction

which should be like:

class New 

I hope it will help.

3
  • shall i change file name too ? Nov 27 '20 at 7:26
  • i am have removed redirection code from the execute method though its still redirect, how can i stop it ? Thankyou Nov 27 '20 at 7:29
  • Its not working Nov 27 '20 at 8:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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