Form¶
A form collects answers. Choices show on the panel as buttons, dropdowns, and On/Off toggles, and text, numbers, and dates go into a modal behind an Edit button. Submit checks every field and hands you the values.
from cascadeui import FormField, FormLayoutView, min_length
class SignUp(FormLayoutView):
def __init__(self, **kwargs):
super().__init__(
title="Sign up",
fields=[ # (1)!
FormField(id="name", label="Name", required=True, validators=[min_length(2)]),
FormField(id="age", label="Age", type="integer", min_value=13, max_value=120),
FormField(
id="role",
label="Role",
type="select",
required=True,
options=[
{"label": "Player", "value": "player"},
{"label": "Coach", "value": "coach"},
],
),
FormField(id="news", label="Newsletter", type="boolean", default=False),
],
**kwargs,
)
async def on_submit(self, interaction, values): # (2)!
await self.respond(interaction, f"Welcome, {values['name']}!")
- Each field is a
FormFieldor a plain dict with the same keys. - Runs once every field passes.
valuesmaps each field'sidto its answer, such as{"name": "Ada", "age": 36, "role": "coach", "news": False}. When it returns, the form closes.
The panel is one card: Name and Age beside an Edit button, Role as a row of buttons with the pick
highlighted, an On/Off toggle for Newsletter, and Submit. Send it like any view:
await SignUp(interaction=interaction).send().
Fields¶
The type decides the control and what the field holds:
type |
The person answers with | values holds |
|---|---|---|
"text" (the default) |
the Edit button's modal | the text |
"integer" |
the Edit button's modal | an int |
"float" |
the Edit button's modal | a float |
"date" |
the Edit button's modal, as YYYY-MM-DD |
the date as "YYYY-MM-DD" text |
"boolean" |
an On/Off toggle | True or False |
"select" |
a row of buttons, or a dropdown (see below) | the picked option's value |
"multi_select" |
a dropdown that takes several | a list of values |
A select with five options or fewer, none with a description and each label short enough for a button,
is a row of buttons with the pick highlighted. Any other is a dropdown, and so is every select on a form
whose buttons would take more than a message's
40 components. Clicking the picked option again
clears an optional select, as Discord's own dropdown does. A boolean with no answer yet shows its toggle
off with "Not set" under the label, and its first click turns it on.
A form that passes 40 components even with dropdowns draws a denser card: each dropdown under its label, each
boolean as one button that shows its answer (Mod log: On) and flips it, three to a row, and each group's
Edit button beside Submit. When even the labels do not fit, each dropdown is named in its group's answers
above it instead. A form too big for that raises when it is built, naming it,
and so does a set_class_attribute() that would make it too big, before the setting lands. What a card takes
depends on the fields, never on answers or errors, so a form that builds keeps its card.
The form shows a picked option by its label, and values holds its value. An answer longer than 100
characters shows its start and an ellipsis, as does an error that quotes it, while values and the Edit
dialog keep it whole.
A field takes these keys:
| Key | What it does |
|---|---|
id |
Required. The key the answer is stored under. Each field needs its own. |
label |
The name the form shows. A dict field without one shows its id, and a FormField requires it. |
type |
One of the types above. |
required |
The field must have an answer before Submit passes. Marked with *. |
default |
The answer the field starts with (see below). |
placeholder |
The hint in an empty dropdown or modal input. |
options |
For select and multi_select: a list of {"label": ..., "value": ...}. value defaults to the label, and description adds a second line. |
max_values |
For multi_select: how many options can be picked. Defaults to all of them. |
validators |
Checks run on the answer at Submit (see Checking Answers). |
min_length / max_length |
For the modal fields: how much the person may type. |
min_value / max_value |
For integer and float: the range a typed number must fall in. |
style |
For the modal fields: discord.TextStyle.short (one line, the default) or discord.TextStyle.paragraph. |
group |
A heading the field is shown under (see Groups). |
secret |
Shows the answer as dots in the form and in the default Submit reply, for a password or a token. |
A default must be an answer the person could have given: an option's value for a select, a list of
them for a multi_select (one value becomes a one-item list), True or False for a boolean, and for
a modal field, text the field accepts. A typed default is stored the way typed input is, so "7" on an
integer field becomes 7. A default that fits shows as filled and counts for required.
The form checks its fields when it is built, so a mistake raises there and never in front of the person:
- two fields with the same
id, an unknowntype, aselectoption with no textlabel, or two options of one field with the samevalue - a
defaultthe field could never hold, such as"abc"on anintegerfield - more than five modal fields (
text,integer,float, anddate) behind one Edit button, which is all one Discord modal holds, or two of them with the same label. AFormLayoutViewgives each group an Edit button of its own, and aFormViewhas one for the whole form - anything the modal would refuse when opened, such as a
placeholderover 100 characters or amin_lengthabovemax_length
Typed fields with FormField and FormSchema
FormField takes the same keys as the dict, and your editor completes them. A wrong type raises
where the FormField is written rather than when the form is built. A FormSchema groups the
fields in a class of their own, passed as schema= in place of fields= (passing both raises
ValueError):
from cascadeui import FormField, FormLayoutView, FormSchema
class ProfileSchema(FormSchema):
def get_fields(self):
return [
FormField(id="name", label="Your name", required=True),
FormField(id="age", label="Your age", type="integer", min_value=0),
]
form = FormLayoutView(schema=ProfileSchema(), interaction=interaction)
Text, Numbers, and Dates¶
Discord shows text inputs only in a modal, so a group's text, integer, float, and date fields show
their answers beside one Edit button, which opens them in one modal. The modal is titled with the group's
name, or for fields with no group Edit Fields, Edit Text Fields when every one of them is text, or
Edit Name when Name is the only one. The modal opens holding the current answers, as the
person typed them: 0042 typed into an integer field is stored as 42 and reopens as 0042. A value
set from code whose text does not fit the field's min_length and max_length opens with the box empty,
since Discord refuses a modal whose prefilled text breaks them.
When the person submits the modal, each answer is read as its type: "36" becomes 36 on an integer
field. An answer that does not read, such as "abc" for an age or 200 past max_value, shows its error
under the field, and the field keeps its last good answer in values. What the person typed stays on
screen and in the modal, so they fix it rather than type it again.
An answer that reads is stored even when a validator then refuses it, with the validator's message under the field. Every mistake in one submit shows at once, the ones a type check finds beside the ones a validator finds.
A secret field hides its answer only in the form: Discord's modal has no hidden input, so the person sees
what they type, and the modal shows it again when they reopen it.
Answers in the Modal¶
Set fields_in_modal = True and every field is answered in the modal. The card lists the answers with one
Edit and one Submit button, and the modal, titled with the form's title, holds an input per field:
type |
The modal shows |
|---|---|
text, integer, float, date |
a text box |
select |
a radio group of 2 to 10 options, else a dropdown |
multi_select |
a checkbox group of up to 10 options, else a dropdown |
boolean |
a Yes/No choice |
A boolean left blank stays Not set, as it does on the card, so on_submit() sees the same answers
with fields_in_modal on or off. A required one cannot be submitted blank.
Every change takes two clicks, Edit and the modal's Submit, where the card's own buttons take one, so it
suits a short form filled in once. Discord's modal holds five inputs and caps each label at 45 characters,
so a form with more fields, a longer label, two fields sharing a label, or a select with no options or more
than 25 raises ValueError when it is built. set_class_attribute("fields_in_modal", True)
turns it on for one form and checks the form the same way.
Checking Answers¶
Submit reads every field. A required field with no answer, an answer that did not read, and a validator
that refuses each keep the form open, with each field's message under it and a line under the title naming the
required fields still empty. on_submit() runs only when nothing is left.
A validator takes the answer, the field, and all the answers, and returns a ValidationResult.
min_length, max_length, regex, choices, min_value, and max_value build the common ones (see
Validation).
A check that spans fields belongs in on_submit(). Setting an error there keeps the form open with the
message shown, and the next Submit checks again:
async def on_submit(self, interaction, values):
if values["start"] > values["end"]:
await self.set_form_error("The start date must come before the end date.")
return
...
set_form_error(message)shows a message under the form's title.Noneclears it.set_field_error(field_id, *messages)shows messages under one field. No messages clear it. Anidthe form does not have raisesValueError, since its message would show nowhere.
Changing a field clears its own message and the line under the title. The other fields' messages stay until they change or the next Submit.
A second click on Submit while the first one runs is dropped, so a check runs once for each Submit the person meant.
Groups¶
Fields with the same group show together under that heading, in the order they are declared, the typed
answers first and the picks after them. A field without a group shows where it is declared, without a
heading. Keep a group's fields together: a group split by another field shows twice.
fields = [
{"id": "name", "label": "Name", "group": "Identity"},
{"id": "pronouns", "label": "Pronouns", "type": "select", "options": [...], "group": "Identity"},
{"id": "email", "label": "Email", "group": "Contact"},
]
A FormLayoutView heads each group in its card, and each group's
typed answers get an Edit button of their own, so its modal holds only that group's fields. A
FormView gives each group a field of its embed.
When Submit Passes¶
on_submit(interaction, values) runs once Submit finds no errors. Save the answers, reply, or move on:
async def on_submit(self, interaction, values):
await save_profile(interaction.user.id, values)
await self.respond(interaction, "Saved.")
When it returns, the form closes the way its exit_policy says
(by default its controls are disabled, and a FormView loses them, see
What a Closed Panel Looks Like). It stays open when on_submit() set an error, and it is left alone
when on_submit() already closed it or navigated to another screen. The default on_submit() replies
"Submitted." with the answers in the form's own lines, a secret field's as dots.
When a Field Changes¶
on_field_changed(field_name, old, new) runs after a pick, a toggle, or a modal submit changes a field,
and only when the answer is different. old is None for a field that had no answer. It runs before the
form redraws, so a change it makes to self.values shows at once:
async def on_field_changed(self, field_name, old, new):
if field_name == "class" and new == "mage":
self.values["weapon"] = "Staff"
An exception it raises is logged, and the form redraws anyway. An override that cannot take
(field_name, old, new) is refused when its class is defined, since every call to it would fail.
Answers survive navigation: a form that pushes to another screen and comes back with Back still holds what was entered. Its error messages do not come back with it, since the next Submit checks again.
Customizing¶
| Attribute | Default | What it does |
|---|---|---|
text_edit_button_label |
None |
The Edit button's label, and the modal's title. None reads Edit and titles the modal as above. At most 45 characters, the most a modal title takes. |
text_edit_button_emoji |
✏️ | The Edit button's emoji. |
text_edit_button_style |
ButtonStyle.secondary |
The Edit button's style. |
text_edit_modal_auto_defer_delay |
2.5 |
Seconds before the modal's submit is acknowledged for you. Raise it for a slow validator, below 3.0. |
fields_in_modal |
False |
Every field is answered in the modal. |
auto_exit_button |
False |
Adds an Exit button beside Submit. |
build_extra_items() adds controls of your own. The form calls it when built and keeps what it adds
through every redraw:
from discord.ui import ActionRow
from cascadeui import FormLayoutView, LinkButton
class SignUp(FormLayoutView):
def build_extra_items(self):
self.add_item(ActionRow(LinkButton(label="Rules", url="https://example.com/rules")))
V1 and V2¶
FormView is the same form on a StatefulView. The answers show in an embed titled with title, one
embed field per field, or one per group, which goes on in a second field past Discord's 1,024 characters. The embed turns red and carries the form-level message when
Submit finds errors.
Its controls fit Discord's five rows: each select field (a dropdown) or boolean field (a Yes and a
No button) takes a row of its own, and the Edit (reading the modal's title), Submit, and, with
auto_exit_button, Exit buttons take the rows after, sharing the last row once all five are used. With
fields_in_modal it shows only those buttons, and Edit reads Edit unless text_edit_button_label names
it. A field or button that does not fit
raises ValueError when the form is built, naming it, and so does a set_class_attribute() that would leave
one, or a build_extra_items() item, without a row, before the setting lands. A FormLayoutView holds more: it is limited only by
a message's 40 components, drawing its denser
card before it gets there, and only a form past even that raises.
Related¶
- Validation: the validators and how to write your own.
- Modals and Inputs: a modal of your own, outside a form.
FormLayoutViewandFormView: every parameter.