1

I am using below code for newsletter subscription.

$email = 'test@email.com';
$subscriberFactory = $objectManager- >get('\Magento\Newsletter\Model\SubscriberFactory');
$subscriberFactory->create()->subscribe($email);

It is working fine, how can i add first name and last name as well as type also? Is it possible that way?

0

By default, there is no field for saving the name (first name and last name) in the newsletter_subscriber table.

If you want to save these values, first you need to create a custom module and add the fields to hold first name and last name in the table.

Next, to save these values, you can either override Magento\Newsletter\Model\Subscriber or write a plugin for that.

I hope you know how to create a plugin.

Below is the sample code for the plugin:

<?php
namespace Stack\Newsletters\Plugin;

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) {

        if ($this->request->isPost() && $this->request->getPost('fname')) { 

            $fname = $this->request->getPost('fname');
            $lname = $this->request->getPost('lname');

            $subject->setFname($fname);
            $subject->setLname($lname);
            $result = $proceed($email);

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

I hope it can help you.

  • I have custom form with fname , lname and email fields, subscription is working fine with above code i mentioned in question, how can i add fname and lname is my issue, I think plugin is not required for me – jafar pinjar Sep 10 '18 at 7:58
  • Please check updated answer now. By your way, it is not possible to add firstname and lastname. You need to modify model function. – Mohit Kumar Arora Sep 10 '18 at 8:01
  • I think plugin is not required for me? Why i need to use plugin for it? I have created custom forms in several places like homepage, category page, pdp page etc, any of the form submits i need to subscribe with that data – jafar pinjar Sep 10 '18 at 8:06
  • If i create plugin, how it takes my form to submit? I have 3 forms in different pages – jafar pinjar Sep 10 '18 at 8:09
  • have you got my point? @mohit – jafar pinjar Sep 10 '18 at 11:28

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.