# Using Pre-Engagement Form Data and Context (Webchat 2.0)

> \[!WARNING]
>
> Webchat 2.0 is no longer supported. It uses Flex UI 1.x.x's [legacy messaging](/docs/flex/developer/messaging), which has reached end-of-life.
>
> If you are using Webchat 2.0, [migrate to Webchat 3.x.x](/docs/flex/developer/conversations/webchat/migrate).
>
> If you are starting out with Webchat, build with [Webchat 3.x.x](/docs/flex/developer/conversations/webchat) instead.

When using chat as a communications channel for your contact center, you can configure a pre-engagement form to gather relevant user information (such as name and email) before the start of a chat. Alternatively, you can gather relevant ***context*** from the data you already have, such as a user's login name or [HTTP referer](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer). You can use pre-engagement form data and context for routing the task to the right agent or displaying relevant user information to the agent.

## Before you begin

To initiate a chat, a user's `friendlyName` *must* be set. The `friendlyName` attribute is set to "Anonymous" in the `context` object of your default Webchat configuration. The `friendlyName` value is displayed to the agent in the Flex UI. When set in both the Webchat context object and a pre-engagement form, the pre-engagement form value overrides the context object value.

## Configuring a pre-engagement form

The pre-engagement form is disabled by default. To require details from your customers before they engage with your agents, enable the pre-engagement form by setting the `startEngagementOnInit` attribute to `false` in your [Configuration object](/docs/flex/developer/messaging/webchat/configuration).

```js title="Enable Pre-Engagement Form"
const defaultConfiguration: Config = {
    disableLocalStorage: false,
    available: true,
    colorTheme: {
        baseName: "BlueMediumTheme"
    },
    componentProps: {
        MessagingCanvas: {
            avatarCallback: (identity: string) => SessionActions.getAgentAvatar(identity),
            showTrayOnInactive: true
        },
        MessageCanvasTray: {
            onButtonClick: () => Actions.invokeAction("RestartEngagement")
        },
        PreEngagementCanvas: {
            // ...
        }
    },

    tokenServerUrl: "https://iam.twilio.com/v1/Accounts/{accountSid}/Tokens",
    flexWebChannelsUrl: "https://flex-api.twilio.com/v1/WebChannels",
    context: {
        friendlyName: "Anonymous"
    },
    startEngagementOnInit: false,
    preEngagementConfig: {
        // ...
    }
};
```

```js title="Enable Pre-Engagement Context"
// !mark(26:30)

// WebchatConfig.js

const defaultConfiguration: Config = {
    disableLocalStorage: false,
    available: true,
    colorTheme: {
        baseName: "BlueMediumTheme"
    },
    componentProps: {
        MessagingCanvas: {
            avatarCallback: (identity: string) => SessionActions.getAgentAvatar(identity),
            showTrayOnInactive: true
        },
        MessageCanvasTray: {
            onButtonClick: () => Actions.invokeAction("RestartEngagement")
        },
        PreEngagementCanvas: {
            // ...
        }
    },

    tokenServerUrl: "https://iam.twilio.com/v1/Accounts/{accountSid}/Tokens",
    flexWebChannelsUrl: "https://flex-api.twilio.com/v1/WebChannels",
    context: {
        friendlyName: "Anonymous"
    },
    startEngagementOnInit: false,
    preEngagementConfig: {
        // ...
    }
};
```

Within your Webchat configuration, you can define the `preEngagementConfig` object for the [PreEngagementCanvas component](https://assets.flex.twilio.com/releases/flex-webchat-ui/2.4.0/docs/PreEngagementCanvas.html).

The following example form shows a required input field for the username, an optional text area field for the user's question, and a submit button with the label "Ok Let's Go!"

### Example Pre-Engagement Form

![Form asking for name and question with submit button labeled 'OK Let's Go!'.](https://docs-resources.prod.twilio.com/9ec5d75955edcc14ff5703bddc05e758c3b3a1a2a6edf50346bfc94e26c9863b.png)

```js title="Webchat configuration with Pre-Engagement Form"
const defaultConfiguration: Config = {
    // ...
    preEngagementConfig: {

        description: "Please provide some information",
        fields: [
            {
                label: "What is your name?",
                type: "InputItem",
                attributes: {
                    name: "friendlyName",
                    type: "text",
                    required: true
                }
            },
            {
                label: "What is your question?",
                type: "TextareaItem",
                attributes: {
                    name: "question",
                    type: "text",
                    placeholder: "Type your question here",
                    required: false,
                    rows: 5
                }
            },
        ],
        submitLabel: "Ok Let's Go!"
    }
};
```

### Supported field types and validations

#### Field Types

* `InputItem`
* `SelectItem`
* `TextareaItem`

#### Field Validations

| Field Attribute | Description                                                                              |
| --------------- | ---------------------------------------------------------------------------------------- |
| `required`      | Validates whether a form field is required or optional. Can be set to `true` or `false`. |
| `email.value`   | Checks the validity of the value attribute for an email input item.                      |

The following example shows a `preEngagementConfig` object with all supported form field types and their properties and attributes.

```js title="Pre-Engagement Config Field Types"
preEngagementConfig: {

    description: "Please provide some information",
    fields: [
        {
            label: "What is your name?",
            type: "InputItem",
            attributes: {
                name: "friendlyName",
                type: "text",
                placeholder: "Enter your name",
                required: true,
                value: "Bob",
                readOnly: false
            }
        },
        {
            label: "What is your email?",
            type: "InputItem",
            attributes: {
                name: "email",
                type: "email",
                placeholder: "Enter your email",
                required: true,
                value: "Bob@bobson.com",
                readOnly: false
            }
        },
        {
            label: "My awesome dropdown",
            type: "SelectItem",
            attributes: {
                name: "My awesome dropdown",
                required: true,
                readOnly: false

            },
            options: [
            {
                value: "value1",
                label: "label1",
                selected: false
            },
            {
                value: "value2",
                label: "label2",
                selected: true
            }
            ]
        },
        {
            label: "What is your question?",
            type: "TextareaItem",
            attributes: {
                name: "question",
                type: "text",
                placeholder: "Type your question here",
                required: false,
                rows: 5,
                value: "My awesome question",
                readOnly: false
            }
        }
    ],
    footerLabel: "I am a footer",
    submitLabel: "Ok Let's Go!",
}
```

### Posting user questions as a chat message

You can use [WebChat actions](/docs/flex/developer/messaging/webchat/actions) to trigger your Flex Webchat Flow to automatically post user questions from a pre-engagement form to a chat window.

The following code sample shows how you can pass the question (if any) from the submitted `formData` and post it to chat using the [`StartEngagement` post-action event](/docs/flex/developer/messaging/webchat/actions).

```javascript
// post question from pre-engagement into chat

  FlexWebChat.Actions.on("afterStartEngagement", (payload) => {
              const { question } = payload.formData;
              if (!question) return;

              const { channelSid } = manager.store.getState().flex.session;
              manager.chatClient.getChannelBySid(channelSid)
                  .then(channel => {
                      channel.sendMessage(question);
                  });
          });

```

When posting an initial message on behalf of the customer, consider changing the introductory message or turning off the `predefinedMessage` [MessagingCanvas prop](https://assets.flex.twilio.com/releases/flex-webchat-ui/2.4.0/docs/MessagingCanvas.html).

```javascript

FlexWebChat.MessagingCanvas.defaultProps.predefinedMessage = false;
```

To learn more about using React Default Props to configure your Webchat components, see [Webchat Configuration: React default props API](/docs/flex/developer/messaging/webchat/configuration).

## Gathering and sending context

The following code sample shows how you can set the `context` object in your Webchat configuration:

```javascript
const defaultConfiguration: Config = {
    // ...
    context: {
        locationOrigin: window.location.origin,
        someContextProp: "ContextProp1",
    }
}

```

If context is set, the context prop will be saved as a chat channel attribute and can be accessed by the **Send to Flex** Studio widget.

## Accessing and using pre-engagement data and context

When enabled, pre-engagement form and context data are both automatically saved as [Programmable Chat channel attributes](/docs/chat/rest/channel-resource) (i.e., channel.attributes.pre\_engagement\_data ) when a chat is initiated.

Your form and context data can then be accessed in the [WebChat Studio Flow](https://www.twilio.com/console/studio/dashboard). Check out the Twilio Studio documentation to learn more about how [Studio uses variables](/docs/studio/user-guide#working-with-variables).You can also save pre-engagement and context data as chat channel attributes:

```javascript
// context set in the WebChat

    context: {
        friendlyName: "Anonymous",
        locationOrigin: "http://someOriginUrl.com",
        someContextProp: "ContextProp1",
    },

// pre-engagement config set in WebChat

preEngagementConfig: {

    description: "Please provide some information",
    fields: [
        {
            label: "What is your name?",
            type: "InputItem",
            attributes: {
                name: "friendlyName",
                type: "text",
                required: true
            }
        },
        {
            label: "What is your question?",
            type: "TextareaItem",
            attributes: {
                name: "question",
                type: "text",
                placeholder: "Type your question here",
                required: false,
                rows: 5
            }
        },
    ],
    submitLabel: "Ok Let's Go!"
}

// Chat channel attributes saved on chat initiation

"attributes": "{\"status\":\"ACTIVE\",\"long_lived\":false,\"pre_engagement_data\":{\"friendlyName\":\"Anonymous\",\"question\":\"Can you help me with my invoice?\",\"location\":\"http://localhost:8081/\",\"locationOrigin\":\"http://someOriginUrl.com\",\"someContextProp\":\"ContextProp1\"},\"from\":\"Bob\",\"channel_type\":\"web\"}"

```

### Pre-engagement and context data in Studio

An incoming message sent to the chat channel triggers the Webchat Flow for your Flex instance, which you can [customize within the Twilio Console](https://www.twilio.com/console/studio/flows).

In the Webchat Studio flow, you can:

* Trigger a bot conversation based on gathered pre-engagement data
* Use pre-engagement data for decisions in the flow, like when to send the conversation to an agent
* Add pre-engagement data to task attributes for routing decision or information display to an agent in Flex

Studio uses Liquid syntax to access the pre-engagement data in a Studio widget. For example, here's how you would access the `question` attribute from your pre-engagement form data:

```javascript

"{{trigger.message.ChannelAttributes.pre_engagement_data.question}}"
```

And here's how you would add the initial user question to your chat task attributes in the Send To Flex widget:

![Flex widget configuration with user question in chat attributes field.](https://docs-resources.prod.twilio.com/e208d9b8a332b45292cf43d5e06d05068f62a0730586508f4917bb89bd948bda.png)

```json
{"initial_question": "{{trigger.message.ChannelAttributes.pre_engagement_data.question}}"}
```

You may access your pre-engagement form and context data via the [Programmable Chat REST API](/docs/chat/rest).

## Next Steps

* [Inbound Messages with Flex WebChat UI](/docs/flex/developer/messaging/inbound-messages-webchat-ui)
* [Integrate a Custom Chat Client with Flex](/docs/flex/developer/messaging/integrate-custom-chat-client)
* [Check out the Twilio Studio User Guide](/docs/studio/user-guide)
