so_logo.png

Integrate DOTS Global Address Complete into Lightning Component (frontend call)

September 2023
Salesforce.com_logo.svg
Print Friendly, PDF & Email
Introduction

In this post we will be highlighting the different steps required to get the DOTS Global Address Complete service up and running in a sales force lightning component. Lightning components are a quick and easy way to customize your Salesforce experience. They allow developers to create custom layouts and functionality for their users.  DOTS Global Address Complete is a perfect pairing for lightning components; it provides some heavy lifting in finding the intended address that a user enters without having to type out all the fields. Additionally the DOTS Global Address Complete service provides validation for US addresses so you can get extra insight on the mailability of a user entered address. To follow along with this tutorial you will need the following

  1. Basic familiarity with Apex classes, JS, HTML, and Salesforce lightning components
  2. A DOTS Global Address Complete License key. Sign up for a free trial here!
  3. Developer Access in Salesforce

What is Salesforce and why does it matter?

Salesforce is a massively popular cloud-based CRM solution. Salesforce is also extremely extensible which makes it a great pairing with Service Objects products. Additionally, DOTS Global Address Complete can help speed up filling address information. For example, if you have someone taking customer addresses over the phone, having DOTS AC fill in an address as a user types can help speed up data input.

Table of Contents:

Step 1: Add the Service Objects Endpoint to the Salesforce CSP Trusted Site List

The first step will be to add the Service Objects DOTS AC endpoint. This will ensure the lightning component can successfully call the Address Complete service. To do this select the “Setup” option under settings icon in the right hand corner.

In the search bar, search the text “CSP” and then select “CSP Trusted Sites”. On the resulting page select the “New Trusted Site” button. On the resulting page fill in the following information:

Then click “Save”

 

Note: If you are using a trial key, the Trusted Site URL should be trial.serviceobjects.com but if you are using a production key, the URL should be sws.serviceobjects.com. You can simply add both URLs at this point for the ease of integration when you transition from a trial to a production key.

Step 2: Creating the Lightning Component

For this step, head to the developer console. This can be accessed through the same settings menu that was used to add the CSP in the previous step.

From here, select File, New, and then Lightning Component. Give your lightning component a proper name and select ok.

Congrats! You’ve created a lightning component. Well sort of, lets add some code to the component so that we can being calling the service.

Step 3: Adding the Input Form with Aura Components

For this step, we’ll add some basic input fields and aura components that we’ll use to search for suggestions based on the users input, display suggestions to the user, and automatically fill in once a user has selected an address.  Feel free to copy the code below.

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:lightningQuickAction" access="global" >
    <!-- Define all the inputs that we want the service to populate -->
    <aura:attribute name="AddressOneIN" type="string" default=""/>
    <aura:attribute name="AddressTwoIN" type="string" default=""/>
    <aura:attribute name="AddressThreeIN" type="string" default=""/>
    <aura:attribute name="UnitIN" type="string" default=""/>
    <aura:attribute name="LocalityIN" type="string" default=""/>
    <aura:attribute name="AdministrativeAreaIN" type="string" default=""/>
    <aura:attribute name="PostalCodeIN" type="string" default=""/>
    <aura:attribute name="CountryIN" type="string" default=""/>
    <aura:attribute name="LabelIN" type="string" default=""/>
    
    <!-- This will be the list of suggestions that the service will return to the user -->
    <aura:attribute name="Suggestions" type="List" default="[]"/>
    <c:Utils aura:id="utils" />
    
    <!-- lightning input for the address1 field, it will call the getSuggestions function in the controller when a user begins typing  -->
    <lightning:input label="Address One" name="AddressOne" aura:id="AddressOne" value="{!v.AddressOneIN}" onchange="{!c.getSuggestions}" />
    
    <!-- This iteration will display all the suggestions to the user once the user begins typing -->
    <aura:if isTrue="{!v.Suggestions.length > 0}">
        <div class="suggestions">
            <ul>
                <aura:iteration items="{!v.Suggestions}" var="Suggestion">
                    <li class="slds-listbox__item">
                        <!-- If the AddressType is equal to BuildingNumber, then this will call a function that displays all the apartment/suite numbers for an address -->
                        <aura:if isTrue="{!Suggestion.AddressType=='BuildingNumber'}">
                            <a onclick="{!c.getUnits}" data-placeid="{!Suggestion.Id}">{!Suggestion.Prediction} - {!Suggestion.Extra}</a>
                            <!-- If a standard address is selected, it will call the getDetails method which will perform the autofil function. -->
                            <aura:set attribute="else">
                                <a onclick="{!c.getDetails}" data-placeid="{!Suggestion.Id}">{!Suggestion.Prediction} - {!Suggestion.Extra}</a>
                            </aura:set>
                        </aura:if>
                    </li>
                </aura:iteration>
            </ul> 
        </div>
    </aura:if>
    
    <!-- These are the rest of the inputs that the DOTS Global Address Complete service will fill in the appropriate values -->
    <lightning:input label="Address Two" name="AddressTwo" aura:id="AddressTwo" value="{!v.AddressTwoIN}"/>
    <lightning:input label="Address Three" name="AddressThree" aura:id="AddressThree" value="{!v.AddressThreeIN}" />
    <lightning:input label="Unit" name="Unit" aura:id="Unit" value="{!v.UnitIN}"/>
    <lightning:input label="Locality" name="Locality" aura:id="Locality" value="{!v.LocalityIN}"/>
    <lightning:input label="Administrative Area" name="AdministrativeArea" aura:id="AdministrativeArea" value="{!v.AdministrativeAreaIN}" />
    <lightning:input label="Postal Code" name="PostalCode" aura:id="PostalCode" value="{!v.PostalCodeIN}" />
    <lightning:input label="Country" name="Country" aura:id="Country" value="{!v.CountryIN}" />   
</aura:component>

Here’s a couple things to note about the front end component

  • We define the attributes that will hold the address values from the service. On the lightning input tag for the address1 field. When this field changes, we’ll make it call our getSuggestions function which we will create in the next step.
  • The aura:iteration element that we created will quickly and easily display any suggestions we find once the service has them to show. Based on the AddressType of the predicted address, the component will call 1 of 2 functions in the component controller
    • If AddressType is equal to BuildingNumber, then a user’s click on this prediction will call the getUnits function that will return all the available units/suite numbers associated with an Address
    • If the AddressType is not equal to BuildingNumber, then the component will simply call the getDetails function which will ultimately populate the other input fields we have in our form with the parsed-out values from the DOTS Address Complete service.
  • In this example we don’t do anything with the filled in address and we have a few fields for the service to fill in: AddressOneIN, AddressTwoIN, AddressThreeIN, UnitIN, LocalityIN, AdministrativeAreaIN, PostalCodeIN, and CountryIN. This would be great time to review our documentation for the service to see which fields it would make sense to use in your particular application.
Step 4: Adding the Javascript to handle Component Events

Now that the visual part of our lightning component is in place, we’ll add the javascript that will handle the functions we defined in the previous step. Below is the component controller code and the helper code that we’ll use.

 

DOTSGlobalAddressCompleteControllerJS.js

({
    //NOTE: The below URLs are biased towards the USA with the query parameter '&bl=USA' other country codes can be added here or this query parameter can be removed to have 
    //the service suggest addresses from all available countries
    
    //This will return an array of suggested addresses for the user
    getSuggestions : function(component, event, helper) {
        var url = 'https://trial.serviceobjects.com/AC/Predict?id=YourLicenseKeyHere&q='+component.get('v.AddressOneIN')+'&bl=USA&al=&l=7&pl=en';
        helper.makeAjaxRequest(component, url, 'getSuggestions');
    },
    
    //Returns an array of all the available units at an address
    getUnits : function(component, event, helper) {
        var selectedItem = event.currentTarget;
        var placeid = selectedItem.dataset.placeid;
        var url = 'https://trial.serviceobjects.com/AC/Units?id=YourLicenseKeyHere&q=' + placeid + '&bs=USA&al=&l=7&pl=en';
        helper.makeAjaxRequest(component, url, 'getUnits');
    },
    
    //Returns the parsed out details of a users selected address
    getDetails : function(component, event, helper) {
        var selectedItem = event.currentTarget;
        var placeid = selectedItem.dataset.placeid;
        var url = 'https://trial.serviceobjects.com/AC/Select?id=YourLicenseKeyHere&q=' + placeid;
       helper.makeAjaxRequest(component, url, 'getDetails');
    }
})

DOTSAddressCompleteJSHelper.js

({
    //Makes the call to the JS Controller based on the method
    makeAjaxRequest : function(component, url, method) {
        var utils = component.find('utils');
        utils.callAjax("GET", url, true,
                        function(xmlhttp){
                            console.log('xmlhttp:', xmlhttp);
                            if (xmlhttp.status == 200) {
                                //This will return a list of suggestions based on a user input
                                if(method == 'getSuggestions')
                                {
                                    var resp = JSON.parse(xmlhttp.responseText);
                                    component.set('v.Suggestions',resp.Addresses); 
                                }
                                //This will return the list of unit numbers associated with an address.
                                if(method == 'getUnits')
                                {
                                    var resp = JSON.parse(xmlhttp.responseText);
                                    component.set('v.Suggestions',resp.Addresses); 
                                }
                                
                                //This will get all the parsed out pieces of information from a users selected address.
                                if(method == 'getDetails')
                                {
                                    var resp = JSON.parse(xmlhttp.responseText);
                                    component.set('v.AddressOneIN',resp.AddressInfos[0].Address1); 
                                    component.set('v.AddressTwoIN',resp.AddressInfos[0].Address2); 
                                    component.set('v.AddressThreeIN',resp.AddressInfos[0].Address3); 
                                    component.set('v.UnitIN',resp.AddressInfos[0].SubPremise); 
                                    component.set('v.LocalityIN',resp.AddressInfos[0].Locality); 
                                    component.set('v.AdministrativeAreaIN',resp.AddressInfos[0].AdminArea); 
                                    component.set('v.PostalCodeIN',resp.AddressInfos[0].PostalCode); 
                                    component.set('v.CountryIN',resp.AddressInfos[0].Country); 
                                    component.set('v.LabelIN',resp.AddressInfos[0].FormattedAddress); 
                                    component.set('v.Suggestions', []); 
                                }
                            }
                            else if (xmlhttp.status == 400) {
                                alert('There was an error 400');
                                alert(xmlhttp.responseText);
                            }else {
                                alert('There was an error not 400');
                                alert(xmlhttp.responseText);
                            }
                        }
                      );
    }
})

DOTSGlobalAddressCompleteJS.css

.suggestions.THIS {
    z-index:1 !important;
    font-size: 15px;
    background-color: white;
    margin-top: 0px !important;
    border-radius: 5px;
    position: absolute;
    border-width: thin;
    border-color: #a9a0a0;
    border-style: solid;
    padding-left: 12px;
    padding-right: 12px;
}

A couple things to note about the code above:

  • The three functions in the controller method will call the three different endpoints in the DOTS Global Address Complete service.
    • getSuggestions calls the “Predict” endpoint which will return an array of predictions based on the input sent to it. This endpoint can be biased towards a specific country with the query parameter “&bl=”. Right now, this is biased towards the US but please change it as you see fit.
    • getUnits returns all the available units at a specific address based on placeid which is returned for every address in the ‘Predict” endpoint.
    • getDetails will return the full parsed out information for the user selected address after calling the “Select” endpoint. Like the “Units” endpoint, this will take in the PlaceId that was returned in the list of addresses provided by the “Predict” endpoint.
    • The query parameter “&id=” will hold your API key. Fill this in with your API key!
  • The DOTSGlobalAddressCompleteJSHelper.js file will make the HTTP GET call to the service by making an Ajax request. Based on the method used, the helper will perform different actions:
    • If the getSuggestions method is called, it will set the “v.Suggestions” list to the list of addresses that were returned from the Predict endpoint.
    • If the getUnits method is called, it will also set the “v.Suggestions” component to the list of addresses that were returned from the “Units” endpoint.
    • Finally, if the method was getDetails, then the component will fill in all the parsed out values from the Predict endpoint into the respective input elements.

 

All our code is in place! Let’s add the lightning component to a page so we can see it in action.

 

Step 5: Adding the New Component to a Lightning App

To start head back to setup page and search Lightning App Builder in the search bar as shown below

On the resulting page either select “New” to create a new page or Edit on one of the existing pages. For examples sake, we will just add a component to the existing home page.  In the Lightning App editor you should now see the component we just created under the “Custom” section of the list of components.

To add this to a current page, simply drag and drop it to an open pane in the component section and then click save! If you are creating a new page you will have to activate the page first. Now we’re ready to test out our new component!

Step 6: Receiving Address Suggestions

Now it is time to see the service in action! Head over to the page or app where the new component was added. We will use the Service Objects office address as an example:

Notice the text “4 Addresses” next to the first suggestion. This tells us that there are 4 unit numbers at this address to choose from. If we select any of the non-apartment addresses, the values on the form should be automatically filled out:

Viola! You now have a working DOTS Global Address Complete demo in your salesforce instance.

Troubleshooting Tips and Tricks
  • The Browser inspector is your friend! If something isn’t working quite right, don’t be scared to step through the JS we created and see what’s going on behind the scenes.
  • This implementation calls the DOTS Global Address Complete service through the front end. This means that your API license key will be exposed to the user. Once a production key is purchased, we can lock down it’s usage by the domain making web service call.
  • Don’t forget to review our documentation for the service; this will help you get the most out of the response and determine which fields in the service would be beneficial for you to use.
  • If you have any questions or want suggestions on how to make use of the service, feel free to email support@serviceobjects.com and we would be happy to help you get the most of your Service Objects Subscription

Closing

While it may take a small bit of work to get DOTS Global Address Complete integrated into your Salesforce instance, it is most definitely worth it! This product is a great user-friendly time save when entering address information into a CRM and can help your salesforce users get the most out of the product. Get your free trial key today and start using it in your Salesforce instance!

Thanks for following along in our tutorial!

Salesforce CRM and Service Objects APIs are a great pairing to enrich and validate your customer and lead data. You can get started by downloading our sample code and signing up for a free trial key for the Global Address Complete service. For further assistance integrating any of our Customer Data Validation services with a Salesforce workflow rule, feel free to contact one of experts at support@serviceobjects.com.

LAST MODIFIED DATE

About Service Objects

Founded in 2001, Service Objects is the leading provider of contact validation solutions, validating online transactions in real-time, including contact name, address, phone, email, and device. Using Service Objects’ global validation and location web services, businesses can identify potentially fraudulent contact records, append additional contact information, and process transactions in a more efficient manner. Service Objects has validated nearly 5 billion contacts, and major brands such as American Express, Microsoft, and Amazon rely on Service Objects for their data validation needs.

For more information about Service Objects’ real-time web services, contact sales@serviceobjects.com or visit us online at serviceobjects.com.

Tel. (805) 963-1700
Toll. (800) 694-6269
serviceobjects.com
136 West Canon Perdido St, Ste D
Santa Barbara, CA 93101-8207