Basics
Defining a simple form
Forms are defined as lists of widgets. Each widget represents an input field or a display element.
To create a form, define your pages as lists of widgets and use the run
function to execute the form.
from abstra.forms import NumberInput, TextInput, run
# Define personal details page
personal_details = [
TextInput("First Name"),
NumberInput("Age")
]
# Define company details page
company_details = [
TextInput("Company"),
TextInput("Job Title")
]
# Run the form with the defined pages
state = run([personal_details, company_details])
# Access the form results
print(state)
# Result:
# {'First Name': 'John', 'Age': 30, 'Company': 'Abstra', 'Job Title': 'Manager'}
In this example, the form consists of two pages: one for personal details and another for company details. The run
function processes the form and returns a state
dictionary containing the user's inputs.
Using Keys for Better Code Readability
To improve code readability and avoid relying on long labels, you can use the key
parameter in input widgets. This allows you to reference the input values using shorter, more meaningful keys.
from abstra.forms import NumberInput, TextInput, run
# Define personal details page with keys
personal_details = [
TextInput("Hello, what is your name?", key="name"),
NumberInput("And how old are you?", key="age")
]
# Define company details page with keys
company_details = [
TextInput("What is the name of your company?", key="company_name"),
TextInput("What is your job title in the company?", key="job_title")
]
# Run the form and access results using keys
state = run([personal_details, company_details])
job_title = state["job_title"] # Accessing the job title using the key
By using keys, you can make your code cleaner and easier to maintain.