# Forms

**Note**  
There is an in-depth tutorial [here](https://blog.rasa.com/building-contextual-assistants-with-rasa-formaction/) about how to use Rasa Forms for slot filling.

### [Configuration File](https://legacy-docs-v1.rasa.com/1.6.2/core/forms/#configuration-file)
### [Form Basics](https://legacy-docs-v1.rasa.com/1.6.2/core/forms/#form-basics)
### [Custom slot mappings](https://legacy-docs-v1.rasa.com/1.6.2/core/forms/#custom-slot-mappings)
### [Validating user input](https://legacy-docs-v1.rasa.com/1.6.2/core/forms/#validating-user-input)
### [Handling unhappy paths](https://legacy-docs-v1.rasa.com/1.6.2/core/forms/#handling-unhappy-paths)
### [The requested_slot slot](https://legacy-docs-v1.rasa.com/1.6.2/core/forms/#the-requested-slot-slot)
### [Handling conditional slot logic](https://legacy-docs-v1.rasa.com/1.6.2/core/forms/#handling-conditional-slot-logic)
### [Debugging](https://legacy-docs-v1.rasa.com/1.6.2/core/forms/#debugging)

One of the most common conversation patterns is to collect a few pieces of information from a user in order to do something (book a restaurant, call an API, search a database, etc.). This is also called **slot filling**.

If you need to collect multiple pieces of information in a row, we recommended that you create a `FormAction`. This is a single action which contains the logic to loop over the required slots and ask the user for this information. There is a full example using forms in the `examples/formbot` directory of Rasa Core.

When you define a form, you need to add it to your domain file. If your form’s name is `restaurant_form`, your domain would look like this:

```
forms:
  - restaurant_form
actions:
  ...
```

To use forms, you also need to include the `FormPolicy` in your policy configuration file. For example:

```
policies:
  - name: "FormPolicy"
```

---

Using a `FormAction`, you can describe _all_ of the happy paths with a single story. By “happy path”, we mean that whenever you ask a user for some information, they respond with the information you asked for.

If we take the example of the restaurant bot, this single story describes all of the happy paths.

```
## happy path
* request_restaurant
    - restaurant_form
    - form{"name": "restaurant_form"}
    - form{"name": null}
```

In this story the user intent is `request_restaurant`, which is followed by the form action `restaurant_form`. With `form{"name": "restaurant_form"}` the form is activated and with `form{"name": null}` the form is deactivated again.

---

The `FormAction` will only request slots which haven’t already been set. If a user starts the conversation with I’d like a vegetarian Chinese restaurant for 8 people, then they won’t be asked about the `cuisine` and `num_people` slots.

### Example of Form Action
Here is an example of what it looks like.
You need to define three methods:

- `name`: the name of this action
- `required_slots`: a list of slots that need to be filled for the `submit` method to work.
- `submit`: what to do at the end of the form, when all the slots have been filled.

```python
def name(self) -> Text:
    """Unique identifier of the form"""  
    return "restaurant_form"
```

```python
@staticmethod
def required_slots(tracker: Tracker) -> List[Text]:
    """A list of required slots that the form has to fill"""  
    return ["cuisine", "num_people", "outdoor_seating", "preferences", "feedback"]
```

```python
def submit(
    self,
    dispatcher: CollectingDispatcher,
    tracker: Tracker,
    domain: Dict[Text, Any],
) -> List[Dict]:
    """Define what the form has to do after all required slots are filled"""  
    # utter submit template
    dispatcher.utter_message(template="utter_submit")
    return []
```

Every time the form action gets called, it will ask the user for the next slot in `required_slots` which is not already set. It does this by looking for a template called `utter_ask_{slot_name}`, so you need to define these in your domain file for each required slot.

### Custom Slot Mappings Example
If you do not define slot mappings, slots will be only filled by entities with the same name as the slot that are picked up from the user input.

```python
def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:
    """A dictionary to map required slots to
        - an extracted entity
        - intent: value pairs
        - a whole message
        or a list of them, where a first match will be picked"""  
    return {
        "cuisine": self.from_entity(entity="cuisine", not_intent="chitchat"),
        "num_people": [
            self.from_entity(
                entity="num_people", intent=["inform", "request_restaurant"]
            ),
            self.from_entity(entity="number"),
        ],
        "outdoor_seating": [
            self.from_entity(entity="seating"),
            self.from_intent(intent="affirm", value=True),
            self.from_intent(intent="deny", value=False),
        ],
        "preferences": [
            self.from_intent(intent="deny", value="no additional preferences"),
            self.from_text(not_intent="affirm"),
        ],
        "feedback": [self.from_entity(entity="feedback"), self.from_text()],
    }
```

### Validating User Input Example
After extracting a slot value from user input, the form will try to validate the value of the slot.

```python
@staticmethod
def cuisine_db() -> List[Text]:
    """Database of supported cuisines"""  
    return [
        "caribbean",
        "chinese",
        "french",
        "greek",
        "indian",
        "italian",
        "mexican",
    ]
```

```python
def validate_cuisine(
    self,
    value: Text,
    dispatcher: CollectingDispatcher,
    tracker: Tracker,
    domain: Dict[Text, Any],
) -> Dict[Text, Any]:
    """Validate cuisine value."""

if value.lower() in self.cuisine_db():
        return {"cuisine": value}
    else:
        dispatcher.utter_message(template="utter_wrong_cuisine")
        return {"cuisine": None}
```

### Handling Unhappy Paths Example
Of course your users will not always respond with the information you ask of them.
```python
## chitchat
* request_restaurant
    - restaurant_form
    - form{"name": "restaurant_form"}
* chitchat
    - utter_chitchat
    - restaurant_form
    - form{"name": null}
```
