from typing import Any, Dict, List, Union
def create_nested_form(form_name: str, fields: Dict[str, Any]) -> Dict[str, Any]:
"""
Creates a nested web form structure.
Args:
form_name: The name of the form.
fields: A dictionary representing the form fields. Keys are field names,
values are dictionaries describing the field properties (type, label, etc.).
Returns:
A dictionary representing the nested form structure.
"""
form = {
"name": form_name,
"fields": []
}
for field_name, field_properties in fields.items():
field = {
"name": field_name,
"type": field_properties.get("type", "text"), # Default to text
"label": field_properties.get("label", field_name),
"properties": field_properties.get("properties", {}),
"nested_form": field_properties.get("nested_form") # Allows nesting
}
form["fields"].append(field)
return form
def render_form(form: Dict[str, Any], indent: int = 0) -> str:
"""
Renders the form structure to a string for debugging.
Args:
form: The form structure dictionary.
indent: The indentation level.
Returns:
A string representing the rendered form.
"""
indent_str = " " * indent
output = f"{indent_str}Form: {form['name']}\n"
for field in form["fields"]:
output += f"{indent_str}{field['name']} ({field['label']}) - Type: {field['type']}\n"
if "nested_form" in field:
output += render_form(field["nested_form"], indent + 1) # Recursive call for nested forms
return output
if __name__ == '__main__':
# Example usage:
fields = {
"personal_info": {
"type": "form",
"label": "Personal Information",
"properties": {},
"nested_form": {
"name": "address",
"label": "Address",
"type": "form",
"properties": {},
"nested_form": None
}
},
"name": {"type": "text", "label": "Name"},
"email": {"type": "email", "label": "Email"},
"age": {"type": "number", "label": "Age"}
}
nested_form = create_nested_form("User Form", fields)
print(render_form(nested_form))
Add your comment