Skip to main content

Creating Form With Python

Dynamically Creating Forms Using Python (or Any Backend Code)

Introduction

This section of the documentation focuses on the process of dynamically creating forms using Python as the backend language. The principles outlined here can be applied to any backend language, as the fundamental concepts remain consistent across different technologies. The example provided demonstrates how to generate a dynamic form for a resort activities booking system using Python.

Overview

The dynamic creation of forms allows for flexible user input collection, tailored to the specific needs of the application. By generating forms on-the-fly based on user input or other contextual factors, you can provide a more personalized and relevant user experience. In this guide, we will walk through how to implement this in Python, though the logic can be adapted to other backend languages.

Step 1: Setting Up the Backend Endpoint (Not in ai12z but on your own server)

To dynamically generate forms, you'll need a backend endpoint that responds to requests with the form data model that can be consumed by the front-end. Here’s an example of how you can create your own microservice this can be achieved in Python using Flask:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/activities', methods=['POST'])
def activities():
"""
Create a new activity form based on user input.
"""
activity = parse_request_payload(request, "activity") or "yoga"
first_name = parse_request_payload(request, "firstName", "")
last_name = parse_request_payload(request, "lastName", "")
room_number = parse_request_payload(request, "roomNumber", "")

form_data = create_activity_form(activity, first_name, last_name, room_number)
return jsonify(form_data), 200

def parse_request_payload(request, key, default_value=None):
"""
Helper function to parse request payload.
"""
return request.json.get(key, default_value)

In this setup:

  • Endpoint: /activities
  • Method: POST
  • Input Parameters: activity, firstName, lastName, roomNumber
  • Response: JSON object containing the form structure.

Step 2: Generating the Form Data

The core logic for generating the form dynamically is encapsulated in the create_activity_form function. This function builds the form structure based on the activity selected by the user. Here’s how it’s implemented:

def create_activity_form(activity, first_name, last_name, room_number):
"""
Return form data according to the activity.
"""
form_data = {
"title": f"Sign up for {activity.capitalize()}",
"description": "",
"pages": [
{
"name": "page1",
"elements": [
{
"type": "text",
"name": "activity",
"visible": False,
"defaultValue": activity
},
{
"type": "text",
"name": "firstName",
"title": "First Name",
"defaultValue": first_name,
"isRequired": True,
"placeholder": "Enter your first name"
},
{
"type": "text",
"name": "lastName",
"defaultValue": last_name,
"title": "Last Name",
"isRequired": True,
"placeholder": "Enter your last name"
},
{
"type": "text",
"name": "roomNumber",
"title": "Room Number",
"defaultValue": room_number,
"isRequired": True
}
],
},
{
"name": "page2",
"elements": [
{
"type": "text",
"name": "email",
"title": "Email",
"isRequired": True,
"inputType": "email",
"placeholder": "Enter your email"
},
{
"type": "text",
"name": "mobilePhone",
"title": "Mobile Phone",
"isRequired": True,
"inputType": "tel",
"placeholder": "_ _ _ - _ _ _ - _ _ _ _"
}
],
},
{
"name": "page3",
"elements": [
{
"type": "text",
"name": "date",
"defaultValueExpression": "today()",
"isRequired": True,
"inputType": "date"
},
{
"type": "dropdown",
"name": "timeslotpicker",
"width": "36%",
"minWidth": "256px",
"titleLocation": "hidden",
"choicesByUrl": {
"url": f"{base_url}timeslot/{{date}}/{activity}",
"path": "timeslots",
"valueName": "timeslot",
"titleName": "timeslot"
},
"placeholder": "Select a time slot",
"allowClear": False,
}
],
}
],
"showQuestionNumbers": "off",
"questionErrorLocation": "bottom",
"completeText": "Sign up",
}

if activity.lower() == "golf":
form_data["pages"].append({
"name": "page4",
"elements": [
{
"type": "image",
"name": "ocean-view-image",
"width": "37%",
"minWidth": "200px",
"imageLink": "https://www.example.com/images/ocean-view.jpg",
"imageFit": "cover",
"imageHeight": "200",
"imageWidth": "200"
},
{
"type": "radiogroup",
"name": "rentGolfClub",
"title": "Club Car",
"choices": [
"Rent a Club Car Golf Cart 9 holes $20",
"Rent a Club Car Golf Cart 18 holes $35",
"Walking"
],
"defaultValue": "Walking"
}
]
})

return form_data

Step 3: Explanation of Dynamic Form Elements

  • Activity-specific Fields: The form structure changes based on the activity selected by the user. For example, if the user selects "golf," an additional page with golf-specific options is added to the form.

  • Date and Time Slot Picker: The form includes a date picker and a dropdown for selecting time slots. The time slots are dynamically fetched from a backend service using the choicesByUrl attribute, which allows the form to stay up-to-date with available time slots based on the selected date.

  • Conditional Logic: The form dynamically includes or excludes certain fields/pages depending on the context. For example, the golf-specific page is only added if "golf" is the selected activity.

Step 4: Integrating with Front-End

Once the backend generates the form structure, the front-end (e.g., using SurveyJS.io) can render the form dynamically. The form structure JSON is used to create a dynamic and interactive form for the user to fill out.

The front-end sends the filled-out form data back to the backend, where it can be processed accordingly.

How would this work:

  • The user would say "I would like to sign up for golf" or "I am John Smith, I would like to sign up for golf"

In ai12z Custom Agent you would set up an agent for activities, this will call the backend microservice that creates the Form the fields that are know like the firstName and lastName will be filled in. Activity Agent

  • The micoservice passes the json back as a Form model, since the custom Agent set the Handle Response as Form
  • The client will render the form model

Gofl Form

Conclusion

Dynamic form generation allows for a more personalized and context-aware user experience. By leveraging backend logic, you can create forms that adapt to the user's needs, making the data collection process more efficient and user-friendly. This documentation provided a Python example but emphasized that the approach is broadly applicable across different backend technologies.