Customize the Pre-Chat Page UI with Lightning Components

Add Snap-ins Chat to your website so customers can quickly get answers to their questions by chatting with an agent while browsing your site. Snap-ins Chat uses a Live Agent deployment that you can quickly configure. Then, simply add the chat code to the web pages where you want the chat snap-in to be available. When agents chat with customers via Snap-ins Chat, the agents use Live Agent in their console. In this post, we will see how to create a pre-chat form by using the lightning components. You can able to Customize the fields, layout, buttons, images, validation, or any other part of the user interface for pre-chat using a custom Lightning component by using Pre chat API. I  am assuming that you have live agent deployments is available to use the snap-ins

prerequisites

To set up Snap-ins Chat, your org must meet these prerequisites:

  • Lightning Experience must be enabled to set up snap-ins
  • Service Cloud License
  • Live Agent License
  • Live Agent must be enabled in your Org
  • A Live Agent chat button and a Live Agent deployment must be set up and available in your Org
  • A Salesforce Community (preferable) or a Salesforce Site must be set up on your org and available for guest user access.

Create a Snap-Ins Deployment

we need to create a Snap-in deployment for each snap-in that you’re using on your website. In this example, the Snap-ins Chat setup uses a Salesforce Community. From Setup, find Snap-ins and click New Deployment and enter details as shown below In the Site Endpoint menu, select a Salesforce community or Salesforce Site where you want to host the snap-ins.

After saving the snap-ins deployment, you need to enable the live agent setting. Go to the snap-ins which you configured and select view. In the Snap-ins configuration page, go to the Live Agent settings section and click Start.

  1. In the Live Agent Deployment menu, select the Live Agent configuration that you want to use with the chat snap-in from the dropdown list.
  2. In the Live Agent Button menu, select the Live Agent chat button or automated invitation that you want to use with the chat snap-in from the dropdown list.
  3. Select Show queue position if you want to display the customer’s place in line while they wait for a support agent. Make sure that the Live Agent chat button you selected has Enable Queue selected in your Live Agent chat button settings.
  4. Click Save.

To set up the pre-chat form

From the snap-in deployment, you can able to add the pre-chat form that will be able to the user before the chat starts.

  1. In the Pre-chat section, move the radio button to Active.
  2. Click Edit.
  3. Select the use case for the pre-chat form.
After saving the pre-chat form go and override the pre-chat form with the below code. 
PreChatCmp.cmp
Here is the lightning component that we will use to override the pre-chat form.
<aura:component implements="lightningsnapin:prechatUI" description="Sample custom pre-chat component for Snap-ins. Implemented using Aura.">
    <!-- You must implement "lightningsnapin:prechatUI" for this component to appear in the "Pre-chat Component" customization dropdown in the Snap-ins setup -->
    
    <!-- Pre-chat field components to render -->
    <aura:attribute name="prechatFieldComponents" type="List" description="An array of objects representing the pre-chat fields specified in pre-chat setup."/>
    
    <!-- Handler for when this component is initialized -->
    <aura:handler name="init" value="{!this}" action="{!c.onInit}" />
    
    <!-- For Aura performance -->
    <aura:locator target="startButton" description="Pre-chat form submit button."/>
    
    <!-- Contains methods for getting pre-chat fields, starting a chat, and validating fields -->
    <lightningsnapin:prechatAPI aura:id="prechatAPI"/>
    
    <h2>Prechat form</h2>
    <div class="prechatUI">
        <div class="prechatContent">
            <ul class="fieldsList">
                <!-- Look in the controller's onInit function. This component dynamically creates the pre-chat field components -->
                {!v.prechatFieldComponents}
            </ul>
        </div>
        <div class="startButtonWrapper">
            <ui:button aura:id="startButton" class="startButton" label="{!$Label.LiveAgentPrechat.StartChat}" press="{!c.handleStartButtonClick}"/>
        </div>
    </div>
    
</aura:component>

Controller.js

({
    /**
     * On initialization of this component, set the prechatFields attribute and render pre-chat fields.
     * 
     * @param cmp - The component for this state.
     * @param evt - The Aura event.
     * @param hlp - The helper for this state.
     */
	onInit: function(cmp, evt, hlp) {
        // Get pre-chat fields defined in setup using the prechatAPI component
		var prechatFields = cmp.find("prechatAPI").getPrechatFields();
        // Get pre-chat field types and attributes to be rendered
        var prechatFieldComponentsArray = hlp.getPrechatFieldAttributesArray(prechatFields);
        
        // Make asynchronous Aura call to create pre-chat field components
        $A.createComponents(
            prechatFieldComponentsArray,
            function(components, status, errorMessage) {
                if(status === "SUCCESS") {
                    cmp.set("v.prechatFieldComponents", components);
                }
            }
        );
    },
    
    /**
     * Event which fires when start button is clicked in pre-chat
     * 
     * @param cmp - The component for this state.
     * @param evt - The Aura event.
     * @param hlp - The helper for this state.
     */
    handleStartButtonClick: function(cmp, evt, hlp) {
        hlp.onStartButtonClick(cmp);
    }
});

helper.js

({
    /**
	 * Map of pre-chat field label to pre-chat field name (can be found in Setup)
	 */
    fieldLabelToName: {
        "First Name": "FirstName",
        "Last Name": "LastName",
        "Email": "Email",
        "Subject": "Subject",
        "Type": "Type",
        "Priority": "Priority"
    },
    
    /**
	 * Event which fires the function to start a chat request (by accessing the chat API component)
	 *
	 * @param cmp - The component for this state.
	 */
    onStartButtonClick: function(cmp) {
        var prechatFieldComponents = cmp.find("prechatField");
        var fields;
        
        // Make an array of field objects for the library
        fields = this.createFieldsArray(prechatFieldComponents);
        
        // If the pre-chat fields pass validation, start a chat
        if(cmp.find("prechatAPI").validateFields(fields).valid) {
            cmp.find("prechatAPI").startChat(fields);
        } else {
            console.warn("Prechat fields did not pass validation!");
        }
    },
    
    /**
	 * Create an array of field objects to start a chat from an array of pre-chat fields
	 * 
	 * @param fields - Array of pre-chat field Objects.
	 * @returns An array of field objects.
	 */
    createFieldsArray: function(fields) {
        if(fields.length) {
            return fields.map(function(fieldCmp) {
                return {
                    label: fieldCmp.get("v.label"),
                    value: fieldCmp.get("v.value"),
                    name: this.fieldLabelToName[fieldCmp.get("v.label")]
                };
            }.bind(this));
        } else {
            return [];
        }
    },
    
    /**
     * Create an array in the format $A.createComponents expects
     * 
     * Example:
     * [["componentType", {attributeName: "attributeValue", ...}]]
     * 
	 * @param prechatFields - Array of pre-chat field Objects.
	 * @returns Array that can be passed to $A.createComponents
     */
    getPrechatFieldAttributesArray: function(prechatFields) {
        // $A.createComponents first parameter is an array of arrays. Each array contains the type of component being created, and an Object defining the attributes.
        var prechatFieldsInfoArray = [];
        
        // For each field, prepare the type and attributes to pass to $A.createComponents
        prechatFields.forEach(function(field) {
            var componentName = (field.type === "inputSplitName") ? "inputText" : field.type;
            var componentInfoArray = ["ui:" + componentName];
            var attributes = {
                "aura:id": "prechatField",
                required: field.required,
                label: field.label,
                disabled: field.readOnly,
                maxlength: field.maxLength,
                class: field.className,
                value: field.value
            };
            
            // Special handling for options for an input:select (picklist) component
            if(field.type === "inputSelect" && field.picklistOptions) attributes.options = field.picklistOptions;
            
            // Append the attributes Object containing the required attributes to render this pre-chat field
            componentInfoArray.push(attributes);
            
            // Append this componentInfoArray to the fieldAttributesArray
            prechatFieldsInfoArray.push(componentInfoArray);
        });
        
        return prechatFieldsInfoArray;
    }
});

Now override the Pre Chat component with this lightning component. 

Adding Your Snap-In to a Website

Now go to the community builder and add the out of box lightning component Snap-ins to the builder as show below.

Here we are configuring the Snap-ins Chat deployment and configure as shown below.

Add Your Website to the CORS Whitelist

Add the URLs of the web pages where you intend to add the snap-in to the CORS whitelist in your Org. The web page where you add the snap-in is the page that customers use to access chat.

Testing 

You can able to see the Pre chat form from the community as shown below. Before going to snap-ins, make sure at least one agent in on live agent with available status.

Once the user submits the form it’s going to create a case as shown below and the agent will able to chat with the user.