What We Do

We'll Help You Get There.
The Zynovo team combines cutting-edge technology, creative design and industry expertise to implement some of the most advanced and profitable ecommerce sites on the web today.
The Zynovo team consists of highly motivated group of individuals committed to client success. We are a group of leaders who encourage originality and creativity, and a place where ingenuity is appreciated and respected. We excel at customizing open source technologies to fit our client needs – whether that be in web development, design, customization or integration. We provide professional and prompt service and provide each client with eCommerce advice and site recommendations. Our expertise is always available to our clients, allowing them to make their eCommerce decisions with ease and certainty.

info@zynovo.com

(424) 835-0442

Top

Tracking Customer Emails in Magento 2

With the frontend changes introduced in Magento 2 and removal of prototype library it becomes crucial to be up to speed with frontend architecture. Magento development documentation, also known as @MagentoDevDocs, gives frontend developers an introduction into frontend development. Majority of pages describe backend part and only few are dedicated to a frontend where JavaScript examples are shown.
In this article we are going to review ways of getting customer’s email. It might be useful for different types of marketing emails. As example abandoned shopping cart or abandoned product page email. In case customer decides to leave a website without a purchase, merchant may send special offer with friendly reminder about interesting products.
There are different forms presented at Magento 2 frontend. These forms collects user’s personal details including email information. Furthermore email is used to identify the user in a system.

 

Overview

Majority of customer forms are implemented using jQuery Widgets and phtml templates. jQuery Widgets are probably one of the best techniques introduced in Magento 2 to provide dynamic interaction with a customer. You may find various Widgets usage in such features as Calendar, Accordion, Datepicker etc. Benefit of using jQuery Widgets is really worth understanding how it works. For our email tracking we are going to use jQuery Widget.
More information about Magento jQuery Widgets library you may find here.

 

Widget Initialization

One of Magento 2 technical goals is to eliminate inline JavaScript usage in templates. That is why Magento team introduced JavaScript initialization via templates which will asynchronously load all JavaScript files.
In order to initialize JavaScript component the “text/x-magento-init” type should be used. Here is an example of JavaScript initialization via template:


{
      "body": {
         "myWidgetName": {}
      }
}

This declaration will load “myWidgetName” component into a client’s browser. However, in order to tell Magento JavaScript file name the requirejs-config.js file should link component name and file location as shown below:


var config = {
   map: {
       '*': {
           myWidgetName: 'Custom_Module/js/widget',
       }
   }
};

The ‘Custom_Module/js/widget’ will resolve to app/code/Custom/Module/view/web/js/widget.js file. Note that “.js” file suffix is not present in the requirejs-config.js file. Once component name resolved with file path, widget will be loaded asynchronously via RequireJS dependency manager.

 

Email jQuery Widget

For our email tracking widget we are going to create jQuery Widget. This widget is going to be loaded on all Magento 2 frontend pages. In this way email tracking widget will be able to listen changes on Forms and store email value for further processing. In this tutorial we will skip integration with 3rd party providers.
Let’s have a look at the initial EmailTracking widget. It is going to be located in the /app/code/Custom/Email/view/frontend/web/js/tracking.js file.


define(["jquery", "jquery/ui"], function($) {
       'use strict';

       $.widget('mage.emailTracking, {
           options: {},
           _create: function() {}
       });

       return $.mage.emailTracking;   
});

The RequireJS library define() function allows to define a module with 2 dependencies: jquery and jquery/ui. jQuery UI is used to define a emailTracking Widget in the mage namespace.
The options object holds configuration data passed during Widget initialization. We will be using this object to pass form identifier and email input field identifier later. The _create function is triggered every time mage.emailTracking Widget object is created.

 

Newsletter Form

The Magento\Newsletter module provides newsletter subscription functionality for a store. It allows to collect user’s email, configure newsletter template and schedule newsletter email to subscribed users.
It is known practice to use 3rd party email providers which give much more flexibility of managing email campaigns than out of box Magento 2 newsletter.
For the emailTracking Widget we are going to reuse Subscribe to a newsletter form. The following is a Newsletter form located bottom right at the Luma theme.
Magento2-Newsletter-Form
By using source code via Chrome browser panel we may observe code of the Subscribe form. Alternatively, form is located in the magento/module-newsletter/view/frontend/templates/subscribe.phtml template.
We have to get css class of the form and email input field and add it as emailTracking Widget options as shown below.


options: {
   formId: '.subscribe',
   inputId: 'input[name=email]'
},

Next step is to assign to the submit form event. Every time user clicks “Subscribe” button the emailTracking widget triggers form validation. Customer’s email may be used once form is successfully validated.


_create: function() {
   var self = this;

   $(this.options.formId).live('submit', function(event) {
       var form = $(event.target);

       form.validation();

       if (form.valid()) {
           var email = form.find(self.options.inputId).val();
           console.log('User email is:' + email);
       }
   });
}

Once user enters correct email and submits form the emailTracking Widget will execute event and “User email is: test@example.com” message will appear in a browser’s console.
Here is complete emailTracking Widget implementation:


define(["jquery", "jquery/ui"], function($) {
   'use strict';

   $.widget('mage.emailTracking', {
       options: {
           formId: '.subscribe',
           inputId: 'input[name=email]'
       },

       _create: function() {
           var self = this;

           $(this.options.formId).live('submit', function(event) {
               var form = $(event.target);

               form.validation();

               if (form.valid()) {
                   var email = form.find(self.options.inputId).val();
                   console.log('User email is:' + email);
               }
           });
       }
   });

   return $.mage.emailTracking;
});

The Custom/Email/view/frontend/requirejs-config.js file should have emailTracking mapping.


var config = {
   map: {
       '*': {
           emailTracking: 'Custom_Email/js/tracking
       }
   }
};

Once it is done we may reference widget name in the Custom/Email/view/frontend/templates/tracking.phtml template for further initialization.


{
   "body": {
      "emailTracking": {}
   }
}

In order to include this template it has to be part of newsletter_head_components reference block which in the Custom/Email/view/frontend/layout/default.xml layout file.


<?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="newsletter_head_components">
           <block class="Magento\Framework\View\Element\Template" name="email.tracking" template="Custom_email::tracking.phtml" />
       </referenceBlock>
   </body>
</page>

Summary

In this tutorial we have implemented the Email Tracking jQuery Widget which listens submission of the Newsletter form. Once user submits his or her email the Widget will automatically validate form and provide email for further usage. Furthermore, this Email Tracking Widget allows to extend functionality and send email to a 3rd party marketing provider.

Max Pronko

Max is an expert in building eCommerce solutions on Magento 2. He is a well known member of Magento Community. Max shares his experience and best practices on his Magento 2 Blog (https://www.maxpronko.com). Currently, Max is holding position of Chief Technical Officer at The Irish Store and Gifts Direct companies.