0

I created an event observer for when a customer subscribes to a newsletter. The event is working as expected and is being triggered when a customer subscribes within the account area or when creating a new account and ticking the box.

However, I have a problem with getting the customer ID after the registration process. When the customer subscribes in the account area, the customer ID is being returned fine. When the customer subscribes during the registration process, the ID is empty.

Snippets of my code:

events.xml:

   <event name="newsletter_subscriber_save_before">
       <observer name="fuelcare_subscribernotification_observer_notify" instance="Fuelcare\SubscriberNotification\Observer\Notify" />
   </event>

Observer NotifyAdmin.php:

<?php
namespace Fuelcare\SubscriberNotification\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface as Logger;
use Fuelcare\SubscriberNotification\Helper\Email;
use \Magento\Framework\Registry;

class NotifyAdmin implements ObserverInterface
{
    protected $_logger;
    private $helperEmail;
    protected $registry;

    public function __construct(
        Logger $logger,
        Email $helperEmail,
        Registry $registry
    ) {
        $this->_logger = $logger;
        $this->helperEmail = $helperEmail;
        $this->registry = $registry;
    }

    public function execute(EventObserver $observer)
    {
        try {
            if (!$this->registry->registry('check_subscription_status')){
                $this->registry->register('check_subscription_status', 'Executed');
                return $this->helperEmail->buildEmail();
            }
        } catch (\Exception $e) {
            $this->logger->debug($e->getMessage());
        }
    }
}

Helper Email.php:

public function buildEmail()
    {
        $id = $this->customerSession->getId();
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/logger.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info($id1);
   }

Like mentioned before, the above code returns the customer ID when saving the subscription in the customer account area once the account was already created, however, it returns nothing when subscribing to the newsletter during the registration process. Any ideas?

1 Answer 1

1

You can use the customer_save_before event to get values / posted data in the registration form and can perform your checks.

of if you want Customer Id after registration, then you can use customer_save_after event and can get Customer id using customer object as:

$customer = $observer->getEvent()->getCustomer();

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.