How To Add Custom Field In Newsletter Subscription In Magento 2

Hello Everyone,

In this blog, we will learn about how to Add Custom Field in Newsletter Subscription in Magento 2.

By default the Newsletter subscription option contains only one field i.e. email id, we add another field here.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Add Custom Field in Newsletter Subscription in Magento 2.

STEPS FOR ADD CUSTOM FIELD IN NEWSLETTER SUBSCRIPTION IN MAGENTO 2

Step 1: Create db_schema.xml file

app/code/Vendor/Extension/etc/db_schema.xml

<?xml version="1.0"?>

<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">

    <table name="newsletter_subscriber" resource="default" engine="innodb" comment="Newsletter Subscriber">

        <column xsi:type="varchar" name="custom_message_field" nullable="false" comment="Custom Message Field"/>

    </table>

</schema>

Step 2: Create default.xml file

app/code/Vendor/Extension/view/frontend/layout/default.xml

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <body>

        <referenceBlock name="form.subscribe" template="Vendor_Extension::customemail.phtml" />

    </body>

</page>

Step 3: Create custom email.phtml file

app/code/Vendor/Extension/view/frontend/templates/customemail.phtml

<div class="block newsletter">

    <div class="title"><strong><?= $block->escapeHtml(__('Newsletter')) ?></strong></div>

    <div class="content">

        <form class="form subscribe"

              novalidate

              action="<?= $block->escapeUrl($block->getFormActionUrl()) ?>"

              method="post"

              data-mage-init='{"validation": {"errorClass": "mage-error"}}'

              id="newsletter-validate-detail">

            <div class="field newsletter">

                <div class="control">

                    <label for="newsletter">

                        <span class="label">

                            <?= $block->escapeHtml(__('Sign Up for Our Newsletter:')) ?>

                        </span>

                        <input name="email" type="email" id="newsletter"

                               placeholder="<?= $block->escapeHtml(__('Enter your email address')) ?>"

                               data-mage-init='{"mage/trim-input":{}}'

                               data-validate="{required:true, 'validate-email':true}"

                        />

                    </label>

                </div>

            </div>

            <div class="field newsletter">

                <div class="control">

                    <label for="custom field">

                        <span class="label">

                            <?= $block->escapeHtml(__('Enter Your Message:')) ?>

                        </span>

                        <input name="custommessagefield" type="text" id="custommessagefield"

                               placeholder="<?= $block->escapeHtml(__('Enter Your Message')) ?>"

                               data-mage-init='{"mage/trim-input":{}}'

                               data-validate="{required:true}"

                        />

                    </label>

                </div>

            </div>

            <div class="actions">

                <button class="action subscribe primary"

                        title="<?= $block->escapeHtmlAttr(__('Subscribe')) ?>"

                        type="submit"

                        aria-label="Subscribe">

                    <span><?= $block->escapeHtml(__('Subscribe')) ?></span>

                </button>

            </div>

        </form>

    </div>

</div>

<script type="text/x-magento-init">

    {

        "*": {

            "Magento_Customer/js/block-submit-on-send": {

                "formId": "newsletter-validate-detail"

            }

        }

    }

</script>

Step 4: Create di.xml file

app/code/Vendor/Extension/etc/di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">

    <type name="Magento\Newsletter\Model\SubscriptionManager">

        <plugin name="Newsletter_Subscriber_Custom_Email_Field" type="Vendor\Extension\Plugin\Newsletter\SubscriptionManager"/>

    </type>

</config>

Step 5: Create SubscriptionManager.php file

app/code/Vendor/Extension/Plugin/Newsletter/SubscriptionManager.php

<?php

namespace Vendor\Extension\Plugin\Newsletter;

use Magento\Framework\App\Request\Http;

use Magento\Newsletter\Model\SubscriberFactory;

use Magento\Store\Model\StoreManagerInterface;

class SubscriptionManager

{

    protected $request;

    protected $subscriberFactory;

    protected $storeManager;

    public function __construct(

        Http $request, 

        SubscriberFactory 

        $subscriberFactory, 

        StoreManagerInterface $store Manager

    )

    {

        $this->request = $request;

        $this->subscriberFactory = $subscriberFactory;

        $this->storeManager = $storeManager;

    }

    public function aroundSubscribe(

        \Magento\Newsletter\Model\SubscriptionManager $subject, 

        callable $proceed, 

        $email, 

        $storeId

    )

    {

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

            $result = $proceed($email, $storeId);

            $customfield = $this->request->getPost('customfield');

            $websiteId = (int)$this->storeManager->getStore($storeId)->getWebsiteId();

            $subscriber = $this->subscriberFactory->create()->loadBySubscriberEmail($email, $websiteId);

            if ($subscriber->getId()) {

                $subscriber->setCustomfield($customfield);

                $subscriber->save();

            }

        }

        return $result;

    }

}

Step 6: Create newsletter_subscriber_block.xml file

app/code/Vendor/Extension/view/adminhtml/layout/newsletter_subscriber_block.xml

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <body>

        <referenceBlock name="adminhtml.newslettrer.subscriber.grid.columnSet">

            <block class="Magento\Backend\Block\Widget\Grid\Column" name="adminhtml.newslettrer.subscriber.grid.columnSet.custom_message_field" as="custom_message_field">

                <arguments>

                    <argument name="header" xsi:type="string" translate="true">Custom Message Field</argument>

                    <argument name="index" xsi:type="string">custom_message_field</argument>

                </arguments>

            </block>

        </referenceBlock>

    </body>

</page>

Step 7: Finally run the below commands

$ php bin/magento setup:upgrade
$ php bin/magento cache:clean
$ php bin/magento cache:flush

Step 8: Output:

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Add Custom Field in Newsletter Subscription in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *