Question

I have a promotional popup on home page, asking to subscribe a newsletter. Also I want to save gender and Interested Categories of that User. How I can save these additional Information to 'newsletter_subscriber' table.

I have referred this link: Magento 2 : How to add additional fields to newsletter

So Fields are added to table and admin grid, but it doesn't save gender and category data to table.

Can anyone help me? Thanks in advance.

please check SS. enter image description here

enter image description here

Adding Some code here,

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

        $subject->setGender($gender);
        $subject->setInterestedCategory($category);


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

    return $result;
}
Was it helpful?

Solution

finally, I found the answer to add additional data to news letter.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Newsletter\Model\Subscriber">
    <plugin name="vendor_module_newsletter_model_subscriber" type="vendor\module\Plugin\Newsletter\Subscriber" sortOrder="1"/>
</type>

and a plugin file

public function aroundSubscribe(\Magento\Newsletter\Model\Subscriber $subject, \Closure $proceed, $email) {

    if ($this->request->isPost() && $this->request->getPost('gender')) {
        $gender = $this->request->getPost('gender');
        $category = $this->request->getPost('category');

        $subject->setGender($gender);
        $subject->setInterestedCategory($category);

        $result = $proceed($email);

        try {
            $subject->save();

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

mistake was $result = $proceed($email); line has to write after saving additional data.

hope will work !!

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top