The Best Creative Minds – Zynovo

Magento is our forte!

Zynovo is a full-service digital commerce agency, focused on end-to-end implementations of the most flexible enterprise-class commerce platform to help online merchants fulfill their business and e-commerce goals in a way that is both economical and efficient. We provide strategic planning, design, development and post-launch maintenance.

Mon – Fri: 09:00 am – 06:00 pm
Contact +1 (424) 835-0442
Follow

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 Magento 2 frontend development. Majority of pages describe backend part and only few are dedicated to a Magento 2 frontend where JavaScript examples are shown.

In this article we are going to review ways of getting customer’s emails in Magento 2. 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. Magento 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 email tracking in Magento 2 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 we are going to create Magento 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 email tracking 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.

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 Widget Magento jQuery 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.

One of the leading Magento developers, Max Pronko has built his career by being proactive software developer with Magento Commerce core team.

After successful eCommerce launch for one of the leading American automaker, Max quickly became a Magento Architect for Magento Community and Enterprise Edition releases. Now, he runs technology vision as Chief Technical Officer in The Irish Store and Gifts Direct. Along the way, Max became a well-known member of the Magento Community, sharing his knowledge with developers via conferences, blogs and videos. You can read more about him at https://www.maxpronko.com.