Create a Custom Pre-Chat Form Using LWC

In Spring ’24 and earlier, Enhanced Web Chat doesn’t have Lightning Locker turned on, but we recommend you build Lightning Locker compatible code for custom-built Lightning Web Components (LWC).

Note

By using a custom pre-chat component, you can customize the user interface for the pre-chat form. These steps show you how to create a custom pre-chat form using LWC. The pre-chat form we use in the example shows the pre-chat fields configured in Embedded Service Deployments in Setup. See Customize Pre-Chat for Enhanced Chat.

  1. Create an LWC bundle. See Salesforce Trailhead: Build Lightning Web Components.

    Let’s call our example bundle customPreChatForm.

  2. In the customPreChatForm.js-meta.xml configuration file of your LWC, specify the lightningSnapin__MessagingPreChat target.

    You add this target to the configuration file so you can see the LWC in your Enhanced Web Chat experience. In other words, adding this target makes the LWC available for selection in Custom UI Components in Embedded Service Deployments in Setup. See Customize your UI with Lightning Web Components.

    customPreChatForm.js-meta.xml
    1<?xml version="1.0" encoding="UTF-8"?>
    2<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    3  <apiVersion>59.0</apiVersion>
    4  <isExposed>true</isExposed>
    5  <targets>
    6    <target>lightningSnapin__MessagingPreChat</target>
    7  </targets>
    8</LightningComponentBundle>
  3. In the customPreChatForm.html file, iterate over the fields object to render the pre-chat fields in the UI.

    The fields object is configured in the customPreChatForm.js file. This HTML code creates a custom pre-chat component similar to the default one.

    customPreChatForm.html
    1<template>
    2    <template class="slds-m-around_medium" for:each={fields} for:item="field">
    3        <c-custom-pre-chat-form-field key={field.name}
    4                                    field-info={field}>
    5        </c-custom-pre-chat-form-field>
    6    </template>
    7    <lightning-button label={startConversationLabel}
    8                    title={startConversationLabel}
    9                    onclick={onStartConversationClick}
    10                    class="slds-m-left_x-small"
    11                    disabled={isSubmitButtonDisabled}>
    12    </lightning-button>
    13</template>
  4. In the customPreChatForm.js file, specify the dispatchEvent function.

    This function takes a CustomEvent object with two fields. The first field is the event name preChatSubmit, and the second one is a JSON payload with the form field values. The prechatsubmit event sends the pre-chat fields configured in Embedded Service Deployments in Setup to the chat request.

    customPreChatForm.js
    1import { track, api, LightningElement } from "lwc";
    2
    3export default class CustomPreChatForm extends LightningElement {
    4    /**
    5    * Deployment configuration data.
    6    * @type {Object}
    7    */
    8    @api configuration = {};
    9
    10    startConversationLabel;
    11
    12    isSubmitButtonDisabled = false;
    13
    14    get prechatForm() {
    15        const forms = this.configuration.forms || [];
    16        return forms.find(form => form.formType === "PreChat") || {};
    17    }
    18
    19    get prechatFormFields() {
    20        return this.prechatForm.formFields || [];
    21    }
    22
    23    /**
    24    * Returns pre-chat form fields sorted by their display order.
    25    * @type {Object[]}
    26    */
    27    get fields() {
    28        let fields =  JSON.parse(JSON.stringify(this.prechatFormFields));
    29        this.addChoiceListValues(fields);
    30        return fields.sort((fieldA, fieldB) => fieldA.order - fieldB.order);
    31    }
    32
    33    connectedCallback() {
    34        this.startConversationLabel = "Start Conversation";
    35    }
    36
    37    /**
    38    * Adds values to choiceList (dropdown) fields.
    39    */
    40    addChoiceListValues(fields) {
    41        for (let field of fields) {
    42            if (field.type === "ChoiceList") {
    43                const valueList = this.configuration.choiceListConfig.choiceList.find(list => list.choiceListId === field.choiceListId) || {};
    44                field.choiceListValues = valueList.choiceListValues || [];
    45            }
    46        }
    47    }
    48
    49    /**
    50    * Iterates over and validates each form field. Returns true if all the fields are valid.
    51    * @type {boolean}
    52    */
    53    isValid() {
    54        let isFormValid = true;
    55        this.template.querySelectorAll("c-custom-pre-chat-form-field").forEach(formField => {
    56            if (!formField.reportValidity()) {
    57                isFormValid = false;
    58            }
    59        });
    60        return isFormValid;
    61    }
    62
    63    /**
    64    * Gathers and submits pre-chat data to the app on start-conversation-button click.
    65    * @type {boolean}
    66    */
    67    onStartConversationClick() {
    68        const prechatData = {};
    69        if (this.isValid()) {
    70            this.template.querySelectorAll("c-custom-pre-chat-form-field").forEach(formField => {
    71                prechatData[formField.name] = String(formField.value);
    72            });
    73
    74            this.isSubmitButtonDisabled = true;
    75
    76            this.dispatchEvent(new CustomEvent(
    77                "prechatsubmit",
    78                {
    79                    detail: { value: prechatData }
    80                }
    81            ));
    82        }
    83    }
    84}

    If you want to use the standard pre-chat fields, here’s what the dispatch function looks like.

    Custom pre-chat LWC event
    1this.dispatchEvent(
    2new CustomEvent("prechatsubmit", {
    3    detail: {
    4    value: {
    5        _firstName: "bob",
    6        _lastname: "jones",
    7        _email: "bob.jones@gmail.com",
    8    },
    9    },
    10}),
    11);
  5. In the customPreChatForm.css file, customize the UI style.

    The UI style in this code is similar to the default experience.

    customPreChatForm.css
    1:host {
    2    display: flex;
    3    flex-direction: column;
    4    flex: 1 1 auto;
    5    overflow: hidden;
    6    background: #FFFFFF;
    7    padding: 2em;
    8}
    9
    10lightning-button {
    11    padding-top: 2em;
    12    text-align: center;
    13}
  6. Create another LWC bundle called customPreChatFormField to define the fields.

  7. In the customPreChatFormField.html file, specify how to render the fields in the UI.

    This example uses the lightning-combobox component to render choiceList (dropdown) fields and the lightning-input component to render other field types.

    customPreChatFormField.html
    1<template>
    2    <template lwc:if={isTypeChoiceList}>
    3        <lightning-combobox key={fieldInfo.name}
    4                            label={fieldInfo.labels.display}
    5                            options={choiceListOptions}
    6                            value={choiceListDefaultValue}
    7                            required={fieldInfo.required}>
    8        </lightning-combobox>
    9    </template>
    10    <template lwc:else>
    11        <lightning-input key={fieldInfo.name}
    12                        type={type}
    13                        label={fieldInfo.labels.display}
    14                        max-length={fieldInfo.maxLength}
    15                        required={fieldInfo.required}>
    16        </lightning-input>
    17    </template>
    18</template>
  8. In the customPreChatFormField.js file, define the fields, including dropdown fields.

    customPreChatFormField.js
    1import { track, api, LightningElement } from "lwc";
    2
    3export default class CustomPreChatFormField extends LightningElement {
    4    choiceListDefaultValue;
    5
    6    /**
    7    * Form field data.
    8    * @type {Object}
    9    */
    10    @api fieldInfo = {};
    11
    12    @api
    13    get name() {
    14        return this.fieldInfo.name;
    15    }
    16
    17    @api
    18    get value() {
    19        const lightningCmp = this.isTypeChoiceList ? this.template.querySelector("lightning-combobox") : this.template.querySelector("lightning-input");
    20        return this.isTypeCheckbox ? lightningCmp.checked : lightningCmp.value;
    21    }
    22
    23    @api
    24    reportValidity() {
    25        const lightningCmp = this.isTypeChoiceList ? this.template.querySelector("lightning-combobox") : this.template.querySelector("lightning-input");
    26        return lightningCmp.reportValidity();
    27    }
    28
    29    get type() {
    30        switch (this.fieldInfo.type) {
    31            case "Phone":
    32                return "tel";
    33            case "Text":
    34            case "Email":
    35            case "Number":
    36            case "Checkbox":
    37            case "ChoiceList":
    38                return this.fieldInfo.type.toLowerCase();
    39            default:
    40                return "text";
    41        }
    42    }
    43
    44    get isTypeCheckbox() {
    45        return this.type === "Checkbox".toLowerCase();
    46    }
    47
    48    get isTypeChoiceList() {
    49        return this.type === "ChoiceList".toLowerCase();
    50    }
    51
    52    /**
    53    * Formats choiceList options and sets the default value.
    54    * @type {Array}
    55    */
    56    get choiceListOptions() {
    57        let choiceListOptions = [];
    58        const choiceListValues = [...this.fieldInfo.choiceListValues];
    59        choiceListValues.sort((valueA, valueB) => valueA.order - valueB.order);
    60        for (const listValue of choiceListValues) {
    61            if (listValue.isDefaultValue) {
    62                this.choiceListDefaultValue = listValue.choiceListValueName;
    63            }
    64            choiceListOptions.push({ label: listValue.label, value: listValue.choiceListValueName });
    65        }
    66        return choiceListOptions;
    67    }
    68}
  9. The customPreChatFormField LWC bundle requires a customPreChatFormField.js-meta.xml configuration file but without a target.

    customPreChatFormField.js-meta.xml
    1<?xml version="1.0" encoding="UTF-8"?>
    2<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    3  <apiVersion>59.0</apiVersion>
    4  <isExposed>true</isExposed>
    5  <targets>
    6  </targets>
    7</LightningComponentBundle>
  10. Deploy the LWC to your org. See Salesforce Developer Guide: Introducing Lightning Web Components.

  11. Add the LWC to your Embedded Service Deployment. See Salesforce Help: Customize Your UI with Lightning Web Components. To get custom LWC configuration details, see Salesforce Developer Guide: Get Custom Lightning Web Components Configuration Details