6

I want to add 3 new fields in news letter popup for that i have written custom module. i am overriding Subscriber model and New Action Controller. But not able to call subscribe method of subscriber model. and also getting error :

PHP Fatal error: Uncaught TypeError: Argument 1 passed to Navin\Subscribe\Controller\Subscribe\NewAction::__construct() must be an instance of Navin\Subscribe\Model\Subscriber, instance of Magento\Framework\App\Action\Context given, called in /var/www/html/jansport/var/generation/Navin/Subscribe/Controller/Subscribe/NewAction/Interceptor.php on line 14 and defined in /var/www/html/jansport/app/code/Navin/Subscribe/Controller/Subscribe/NewAction.php:33\nStack trace:\n#0 /var/www/html/jansport/var/generation/Navin/Subscribe/Controller/Subscribe/NewAction/Interceptor.php(14): Navin\Subscribe\Controller\Subscribe\NewAction->__construct(Object(Magento\Framework\App\Action\Context), Object(Magento\Newsletter\Model\SubscriberFactory), Object(Magento\Customer\Model\Session\Interceptor), Object(Magento\Store\Model\StoreManager), Object(Magento\Customer\Model\Url), Object(Magento\Customer\Model\AccountManagement\Interceptor))\n#1 /var/www/html/jansport/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(93): Navin\Subscribe in /var/www/html/jansport/app/code/Navin/Subscribe/Controller/Subscribe/NewAction.php on line 33

My code is: di.xml

<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\NewAction" type="Navin\Subscribe\Controller\Subscribe\NewAction" />
    <preference for="Magento\Newsletter\Model\Subscriber" type="Navin\Subscribe\Model\Subscriber" />
</config>

NewAction.php Controller


    namespace Navin\Subscribe\Controller\Subscribe;

    //use Navin\Subscribe\Model\SubscriberFactory;

    class NewAction extends \Magento\Newsletter\Controller\Subscriber\NewAction {

        /**
         * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
         */
        protected $subscriberFactory;

        public function __construct(
        \Navin\Subscribe\Model\Subscriber $subscriberFactory
        ) {
            $this->subscriberFactory = $subscriberFactory;
        }

        public function execute() {

            //echo 'test come here';exit;
            $post = $this->getRequest()->getPostValue();
            //var_dump($post);exit;

            if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
                $email = (string) $this->getRequest()->getPost('email');
                $subscriber_name = (string) $this->getRequest()->getPost('subscriber_name');
                $subscriber_date_of_birth = (string) $this->getRequest()->getPost('subscriber_dateofbirth');
                $subscriber_country_code = (string) $this->getRequest()->getPost('subscriber_countrycode');
                $requestCatalog = (string) $this->getRequest()->getPost('requestCatalog');

                try {
                    $this->validateEmailFormat($email);
                    $this->validateGuestSubscription();
                    $this->validateEmailAvailable($email);

                    $status = $this->subscriberFactory->subscribe($email, $subscriber_name, $subscriber_date_of_birth, $subscriber_country_code);
                    if ($status == \Magento\Newsletter\Model\Subscriber::STATUS_NOT_ACTIVE) {
                        $this->messageManager->addSuccess(__('The confirmation request has been sent.'));
                    } else {

                        $this->messageManager->addSuccess(__('Thank you for your subscription.'));
                    }
                } catch (\Magento\Framework\Exception\LocalizedException $e) {
                    $this->messageManager->addException(
                            $e, __('There was a problem with the subscription: %1', $e->getMessage())
                    );
                } catch (\Exception $e) {

                    $this->messageManager->addException($e, __('Something went wrong with the subscription.'));
                }
            }

            $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl());
        }

    }

Subscriber.php Model

namespace Navin\Subscribe\Model;

class Subscriber extends Magento\Newsletter\Model\Subscriber {

    /**
     * Initialize resource model
     *
     * @return void
     */

    public function subscribe($email, $subscriber_name = '', $subscriber_date_of_birth = '', $subscriber_country_code = '') {

        $this->loadByEmail($email);

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

        $isConfirmNeed = $this->_scopeConfig->getValue(
                        self::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 (!$this->getId() || $this->getStatus() == self::STATUS_UNSUBSCRIBED || $this->getStatus() == self::STATUS_NOT_ACTIVE
        ) {
            if ($isConfirmNeed === true) {
                // if user subscribes own login email - confirmation is not needed
                $isOwnSubscribes = $isSubscribeOwnEmail;
                if ($isOwnSubscribes == true) {
                    $this->setStatus(self::STATUS_SUBSCRIBED);
                } else {
                    $this->setStatus(self::STATUS_NOT_ACTIVE);
                }
            } else {
                $this->setStatus(self::STATUS_SUBSCRIBED);
            }
            $this->setSubscriberEmail($email);
            $this->setSubscriberName($subscriber_name); //subscriber_name
            $this->setSubscriberDateofbirth($subscriber_date_of_birth); //date of birth
            $this->setSubscriberCountrycode($subscriber_country_code); //country code
        }

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

        $this->setStatusChanged(true);

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

}
2
  • Delete the pub/static files expext .htaccess and var/generation files and the deploy static content. See the result again. Dec 7, 2016 at 7:26
  • i have try this not working Dec 7, 2016 at 7:47

3 Answers 3

9

Finally i have resolve my issue . Only Need to override Subscriber. I am posting my entire code. may be it will helpful to someone. di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Newsletter\Model\Subscriber" type="Navin\Subscribe\Model\Subscriber" />
</config>

Subscriber.php Model Files

namespace Navin\Subscribe\Model;

class Subscriber extends \Magento\Newsletter\Model\Subscriber {

    /**
     * Initialize resource model
     *
     * @return void
     */

    public function subscribe($email, $subscriber_name = '', $subscriber_date_of_birth = '', $subscriber_country_code = '') {

        $this->loadByEmail($email);

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

        $isConfirmNeed = $this->_scopeConfig->getValue(
                        self::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 (!$this->getId() || $this->getStatus() == self::STATUS_UNSUBSCRIBED || $this->getStatus() == self::STATUS_NOT_ACTIVE
        ) {
            if ($isConfirmNeed === true) {
                // if user subscribes own login email - confirmation is not needed
                $isOwnSubscribes = $isSubscribeOwnEmail;
                if ($isOwnSubscribes == true) {
                    $this->setStatus(self::STATUS_SUBSCRIBED);
                } else {
                    $this->setStatus(self::STATUS_NOT_ACTIVE);
                }
            } else {
                $this->setStatus(self::STATUS_SUBSCRIBED);
            }

            $this->setSubscriberEmail($_POST['email']);

        }

        if(!empty($_POST['subscriber_name']) ){
                $this->setSubscriberName($_POST['subscriber_name']); //subscriber_name
                $this->setSubscriberDateofbirth($_POST['subscriber_dateofbirth']); //date of birth
                $this->setSubscriberCountrycode($_POST['subscriber_countrycode']); //country code
        }

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

        $this->setStatusChanged(true);

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

}
1
  • does this have email validation and return the status message. for example "'This email address is already assigned to another user.'" or "'Please enter a valid email address.'", etc? Aug 12, 2019 at 8:54
0

As the new controller extends the original controller, you need to extend its constructor instead of just overwriting it. Try using the code below for the constructor:

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Customer\Model\Url $customerUrl,
    \Magento\Customer\Api\AccountManagementInterface $customerAccountManagement,
    \Navin\Subscribe\Model\Subscriber $subscriberFactory
) {
    $this->customerAccountManagement = $customerAccountManagement;
    $this->subscriberFactory = $subscriberFactory;
    parent::__construct(
        $context,
        $subscriberFactory,
        $customerSession,
        $storeManager,
        $customerUrl
    );
}

And don't forget to clean 'var/generation' and 'var/di' folders after making the changes in the constructor.

1
  • 1
    Not Working Uncaught TypeError: Argument 2 passed to Magento\\Newsletter\\Controller\\Subscriber\\NewAction::__construct() must be an instance of Magento\\Newsletter\\Model\\SubscriberFactory, instance of Navin\\Subscribe\\Model\\Subscriber given Dec 7, 2016 at 10:30
0

I think, You missed Context Object, Try this below code.

add \Magento\Framework\App\Action\Context $context, to Constructor:

  namespace Navin\Subscribe\Controller\Subscribe;

      //use Navin\Subscribe\Model\SubscriberFactory;

      class NewAction extends \Magento\Newsletter\Controller\Subscriber\NewAction {

          /**
           * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
           */
          protected $subscriberFactory;

          public function __construct(
          \Magento\Framework\App\Action\Context $context,
          \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
          \Navin\Subscribe\Model\Subscriber $subscriber,
           array $data = array()

          ) {
              $this->subscriberFactory = $subscriberFactory;
              $this->subscriber = $subscriber;
              parent::__construct($context,
                        $subscriberFactory, 
                        $subscriber, 
                        $data);


          }

          public function execute() {

              //echo 'test come here';exit;
              $post = $this->getRequest()->getPostValue();
              //var_dump($post);exit;

              if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
                  $email = (string) $this->getRequest()->getPost('email');
                  $subscriber_name = (string) $this->getRequest()->getPost('subscriber_name');
                  $subscriber_date_of_birth = (string) $this->getRequest()->getPost('subscriber_dateofbirth');
                  $subscriber_country_code = (string) $this->getRequest()->getPost('subscriber_countrycode');
                  $requestCatalog = (string) $this->getRequest()->getPost('requestCatalog');

                  try {
                      $this->validateEmailFormat($email);
                      $this->validateGuestSubscription();
                      $this->validateEmailAvailable($email);

                      $status = $this->subscriberFactory->subscribe($email, $subscriber_name, $subscriber_date_of_birth, $subscriber_country_code);
                      if ($status == \Magento\Newsletter\Model\Subscriber::STATUS_NOT_ACTIVE) {
                          $this->messageManager->addSuccess(__('The confirmation request has been sent.'));
                      } else {

                          $this->messageManager->addSuccess(__('Thank you for your subscription.'));
                      }
                  } catch (\Magento\Framework\Exception\LocalizedException $e) {
                      $this->messageManager->addException(
                              $e, __('There was a problem with the subscription: %1', $e->getMessage())
                      );
                  } catch (\Exception $e) {

                      $this->messageManager->addException($e, __('Something went wrong with the subscription.'));
                  }
              }

              $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl());
          }

      }
5
  • i have try . not working Dec 7, 2016 at 10:28
  • @BhudiyaNavin, you got any error message. Dec 7, 2016 at 10:37
  • Uncaught TypeError: Argument 2 passed to Magento\\Newsletter\\Controller\\Subscriber\\NewAction::__co‌​nstruct() must be an instance of Magento\\Newsletter\\Model\\SubscriberFactory, instance of Navin\\Subscribe\\Model\\Subscriber Dec 8, 2016 at 4:21
  • @BhudiyaNavin I update my answer, try this then, tell me if you got any errors, Dec 8, 2016 at 4:34
  • Now i am getting this error: PHP Fatal error: Cannot redeclare Navin\\Subscribe\\Controller\\Subscribe\\NewAction::$subscriberFactory in /var/www/html/jansport/app/code/Navin/Subscribe/Controller/Subscribe/NewAction.php on line 27, referer: 45.33.122.66/jansport Dec 9, 2016 at 6:11

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.