0

I am new to magento 2 and i would like to add extra field to newsletter so i created a module with plugin to call aroundsubscribe method to save the new field data while subscription but i am unable to do so.

Plugin class is


namespace Microwebby\Micro\Module\Plugin\Newsletter;

use Magento\Framework\App\Request\Http;

class Subscriber {
  protected $request;

  public function __construct(

    Http $request
  ) {

    $this->request = $request;
  }

  public function aroundSubscribe($subject, \Closure $proceed, $email) {
    $result = $proceed($email);
     if ($this->request->isPost()) {
      $subscriber_country = $this->request->getPost('subscriber_country');

      $subject->setCSubscriber_country($subscriber_country);

      try {
        $subject->save();
      }catch (\Exception $e) {
        throw new \Exception($e->getMessage());
      }
    }

    return $result;
  }
}

In system.log i can see the trace


Microwebby\Micro\Module\Plugin\Newsletter\Subscriber->aroundSubscribe(Object(Magento\Newsletter\Model\Subscriber\Interceptor), Object(Closure), 'rashidtahir05@g...')

Anything else needed to help please mention so that i can provide you.

I want to add extra field to newsletter subscription form.

thanks

1 Answer 1

0

Try following way:

namespace Microwebby\Micro\Module\Plugin\Newsletter;

use Magento\Framework\App\Request\Http;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class Subscriber
{
    /**
     * @var Http
     */
    protected $request;

    /**
     * Core store config
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * Customer session
     *
     * @var \Magento\Customer\Model\Session
     */
    protected $customerSession;

    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerRepository;

    /**
     * Initialize dependencies.
     *
     * @param Http $request
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Customer\Model\Session $customerSession
     * @param CustomerRepositoryInterface $customerRepository
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        Http $request,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\Session $customerSession,
        CustomerRepositoryInterface $customerRepository
    )
    {
        $this->request = $request;
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
        $this->customerSession = $customerSession;
        $this->customerRepository = $customerRepository;
    }

    public function aroundSubscribe(
        \Magento\Newsletter\Model\Subscriber $subject,
        \Closure $proceed,
        $email
    )
    {
        if ($this->request->isPost()) {
            $subscriber_country = $this->request->getPost('subscriber_country');
            if($subscriber_country) {
                $subject->loadByEmail($email);

                if (!$subject->getId()) {
                    $subject->setSubscriberConfirmCode($subject->randomSequence());
                }

                $isConfirmNeed = $this->scopeConfig->getValue(
                    \Magento\Newsletter\Model\Subscriber::XML_PATH_CONFIRMATION_FLAG,
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                ) == 1 ? true : false;
                $isOwnSubscribes = false;

                $isSubscribeOwnEmail = $this->customerSession->isLoggedIn()
                    && $this->customerSession->getCustomerDataObject()->getEmail() == $email;

                if (!$subject->getId() || $subject->getStatus() == \Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED
                    || $subject->getStatus() == \Magento\Newsletter\Model\Subscriber::STATUS_NOT_ACTIVE
                ) {
                    if ($isConfirmNeed === true) {
                        // if user subscribes own login email - confirmation is not needed
                        $isOwnSubscribes = $isSubscribeOwnEmail;
                        if ($isOwnSubscribes == true) {
                            $subject->setStatus(\Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED);
                        } else {
                            $subject->setStatus(\Magento\Newsletter\Model\Subscriber::STATUS_NOT_ACTIVE);
                        }
                    } else {
                        $subject->setStatus(\Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED);
                    }
                    $subject->setSubscriberEmail($email);
                }

                if ($isSubscribeOwnEmail) {
                    try {
                        $customer = $this->customerRepository->getById($this->customerSession->getCustomerId());
                        $subject->setStoreId($customer->getStoreId());
                        $subject->setCustomerId($customer->getId());
                    } catch (NoSuchEntityException $e) {
                        $subject->setStoreId($this->storeManager->getStore()->getId());
                        $subject->setCustomerId(0);
                    }
                } else {
                    $subject->setStoreId($this->storeManager->getStore()->getId());
                    $subject->setCustomerId(0);
                }

                $subject->setStatusChanged(true);
                $subject->setSubscriberCountry($subscriber_country);
                try {
                    $subject->save();
                    if ($isConfirmNeed === true
                        && $isOwnSubscribes === false
                    ) {
                        $subject->sendConfirmationRequestEmail();
                    } else {
                        $subject->sendConfirmationSuccessEmail();
                    }
                    return $subject->getStatus();
                } catch (\Exception $e) {
                    throw new \Exception($e->getMessage());
                }
            }

        }

        return $proceed($email);
    }
}

Clear magento cache.

4
  • Still the same result its seems that aroundSubscribe is not called how to find this although system.log as i posted in first post showing about this.
    – pearl_123
    Commented Jan 14, 2017 at 4:37
  • Check updated answer.
    – Sohel Rana
    Commented Jan 14, 2017 at 6:43
  • @pearl_123 did you try last updated answer? It's work for you?
    – Sohel Rana
    Commented Jan 17, 2017 at 6:52
  • No it's not working getting error " Something went wrong with the subscription." and my custom fields are not stored in database Commented Feb 15, 2019 at 6:40

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.