storeManager = $storeManager; $this->formKeyValidator = $formKeyValidator; $this->customerRepository = $customerRepository; $this->subscriberFactory = $subscriberFactory; parent::__construct($context, $customerSession); } /** * Save newsletter subscription preference action * * @return void|null */ public function execute() { if (!$this->formKeyValidator->validate($this->getRequest())) { return $this->_redirect('customer/account/'); } $customerId = $this->_customerSession->getCustomerId(); if ($customerId === null) { $this->messageManager->addError(__('Something went wrong while saving your subscription.')); } else { try { $customer = $this->customerRepository->getById($customerId); $storeId = $this->storeManager->getStore()->getId(); $customer->setStoreId($storeId); $isSubscribedState = $customer->getExtensionAttributes() ->getIsSubscribed(); $isSubscribedParam = (boolean)$this->getRequest() ->getParam('is_subscribed', false); if ($isSubscribedParam !== $isSubscribedState) { // No need to validate customer and customer address while saving subscription preferences $this->setIgnoreValidationFlag($customer); $this->customerRepository->save($customer); if ($isSubscribedParam) { $subscribeModel = $this->subscriberFactory->create() ->subscribeCustomerById($customerId); $subscribeStatus = $subscribeModel->getStatus(); if ($subscribeStatus == Subscriber::STATUS_SUBSCRIBED) { $this->messageManager->addSuccess(__('We have saved your subscription.')); } else { $this->messageManager->addSuccess(__('A confirmation request has been sent.')); } } else { $this->subscriberFactory->create() ->unsubscribeCustomerById($customerId); $this->messageManager->addSuccess(__('We have removed your newsletter subscription.')); } } else { $this->messageManager->addSuccess(__('We have updated your subscription.')); } } catch (\Exception $e) { $this->messageManager->addError(__('Something went wrong while saving your subscription.')); } } $this->_redirect('customer/account/'); } /** * Set ignore_validation_flag to skip unnecessary address and customer validation * * @param Customer $customer * @return void */ private function setIgnoreValidationFlag($customer) { $customer->setData('ignore_validation_flag', true); } }