Newer Version Available

This content describes an older version of this product. View Latest

Custom Pre-Chat Component Sample Using Aura

The following code sample contains examples of the component, controller, and helper code for a custom pre-chat component using Aura.

This component:

  • Uses Aura to create the pre-chat fields and start a chat.
  • Uses an initialize function that fetches the pre-chat fields from setup and dynamically creates the pre-chat field components using $A.createComponents.
  • Creates an array when the user clicks the Start Chat button. The array contains pre-chat field information to pass to the startChat method on the prechatAPI component.

Component Code

1<aura:component implements="lightningsnapin:prechatUI" description="Sample custom prechat component for Snapins. Implemented using Aura.">
2    <!-- You must implement "lightningsnapin:prechatUI" for this component to appear in the "Prechat Component" customization dropdown in the Snapins setup. -->
3
4    <!-- Prechat field components to render. -->
5    <aura:attribute name="prechatFieldComponents" type="List" description="An array of objects representing the prechat fields specified in prechat setup."/>
6    
7    <!-- Handler for when this component is initialized. -->
8    <aura:handler name="init" value="{!this}" action="{!c.onInit}" />
9
10    <!-- For Aura performance. -->
11    <aura:locator target="startButton" description="Prechat form submit button."/>
12    
13    <!-- Contains methods for getting prechat fields, starting a chat, and validating fields. -->
14    <lightningsnapin:prechatAPI aura:id="prechatAPI"/>
15    
16    <h2>Prechat form.</h2>
17    <div class="prechatUI">
18        <div class="prechatContent">
19            <ul class="fieldsList">
20                <!-- Look in the controller's onInit function. This component dynamically creates the prechat field components. -->
21                {!v.prechatFieldComponents}
22            </ul>
23        </div>
24        <div class="startButtonWrapper">
25            <ui:button aura:id="startButton" class="startButton" label="{!$Label.LiveAgentPrechat.StartChat}" press="{!c.handleStartButtonClick}"/>
26        </div>
27    </div>
28
29</aura:component>

Controller Code

1({
2    /**
3     * On initialization of this component, set the prechatFields attribute and render prechat fields.
4     * 
5     * @param cmp - The component for this state.
6     * @param evt - The Aura event.
7     * @param hlp - The helper for this state.
8     */
9	onInit: function(cmp, evt, hlp) {
10        // Get prechat fields defined in setup using the prechatAPI component.
11		var prechatFields = cmp.find("prechatAPI").getPrechatFields();
12        // Get prechat field types and attributes to be rendered.
13        var prechatFieldComponentsArray = hlp.getPrechatFieldAttributesArray(prechatFields);
14        
15        // Make asynchronous Aura call to create prechat field components.
16        $A.createComponents(
17            prechatFieldComponentsArray,
18            function(components, status, errorMessage) {
19                if(status === "SUCCESS") {
20                    cmp.set("v.prechatFieldComponents", components);
21                }
22            }
23        );
24    },
25    
26    /**
27     * Event which fires when start button is clicked in prechat.
28     * 
29     * @param cmp - The component for this state.
30     * @param evt - The Aura event.
31     * @param hlp - The helper for this state.
32     */
33    handleStartButtonClick: function(cmp, evt, hlp) {
34        hlp.onStartButtonClick(cmp);
35    }
36});

Helper Code

1({
2    /**
3     * Event which fires the function to start a chat request (by accessing the chat API component).
4     * 
5     * @param cmp - The component for this state.
6     */
7    onStartButtonClick: function(cmp) {
8        var prechatFieldComponents = cmp.find("prechatField");
9        var apiNamesMap = this.createAPINamesMap(cmp.find("prechatAPI").getPrechatFields());
10        var fields;
11
12        // Make an array of field objects for the library.
13        fields = this.createFieldsArray(apiNamesMap, prechatFieldComponents);
14        
15        // If the prechat fields pass validation, start a chat.
16        if(cmp.find("prechatAPI").validateFields(fields).valid) {
17            cmp.find("prechatAPI").startChat(fields);
18        } else {
19            console.warn("Prechat fields did not pass validation!");
20        }
21    },
22
23    /**
24     * Create an array of field objects to start a chat from an array of prechat fields.
25     * 
26     * @param fields - Array of prechat field Objects.
27     * @returns An array of field objects.
28     */
29    createFieldsArray: function(apiNames, fieldCmps) {
30        if(fieldCmps.length) {
31            return fieldCmps.map(function(fieldCmp) {
32                return {
33                    label: fieldCmp.get("v.label"),
34                    value: fieldCmp.get("v.value"),
35                    name: apiNames[fieldCmp.get("v.label")]
36                };
37            }.bind(this));
38        } else {
39            return [];
40        }
41    },
42
43    /**
44     * Create map of field label to field API name from the pre-chat fields array.
45     * 
46     * @param fields - Array of prechat field Objects.
47     * @returns An array of field objects.
48     */
49    createAPINamesMap: function(fields) {
50        var values = {};
51
52        fields.forEach(function(field) {
53            values[field.label] = field.name;
54        });
55        
56        return values;
57    },
58    
59    /**
60     * Create an array in the format $A.createComponents expects.
61     * 
62     * Example:
63     * [["componentType", {attributeName: "attributeValue", ...}]]
64     * 
65     * @param prechatFields - Array of prechat field Objects.
66     * @returns Array that can be passed to $A.createComponents
67     */
68    getPrechatFieldAttributesArray: function(prechatFields) {
69        // $A.createComponents first parameter is an array of arrays. Each array contains the type of component being created, and an Object defining the attributes.
70        var prechatFieldsInfoArray = [];
71
72        // For each field, prepare the type and attributes to pass to $A.createComponents.
73        prechatFields.forEach(function(field) {
74            var componentName = (field.type === "inputSplitName") ? "inputText" : field.type;
75            var componentInfoArray = ["ui:" + componentName];
76            var attributes = {
77                "aura:id": "prechatField",
78                required: field.required,
79                label: field.label,
80                disabled: field.readOnly,
81                maxlength: field.maxLength,
82                class: field.className,
83                value: field.value
84            };
85            
86            // Special handling for options for an input:select (picklist) component.
87            if(field.type === "inputSelect" && field.picklistOptions) attributes.options = field.picklistOptions;
88            
89            // Append the attributes Object containing the required attributes to render this prechat field.
90            componentInfoArray.push(attributes);
91            
92            // Append this componentInfoArray to the fieldAttributesArray.
93            prechatFieldsInfoArray.push(componentInfoArray);
94        });
95
96        return prechatFieldsInfoArray;
97    }
98});