1. from typing import Any, Dict, List, Union
  2. def create_nested_form(form_name: str, fields: Dict[str, Any]) -> Dict[str, Any]:
  3. """
  4. Creates a nested web form structure.
  5. Args:
  6. form_name: The name of the form.
  7. fields: A dictionary representing the form fields. Keys are field names,
  8. values are dictionaries describing the field properties (type, label, etc.).
  9. Returns:
  10. A dictionary representing the nested form structure.
  11. """
  12. form = {
  13. "name": form_name,
  14. "fields": []
  15. }
  16. for field_name, field_properties in fields.items():
  17. field = {
  18. "name": field_name,
  19. "type": field_properties.get("type", "text"), # Default to text
  20. "label": field_properties.get("label", field_name),
  21. "properties": field_properties.get("properties", {}),
  22. "nested_form": field_properties.get("nested_form") # Allows nesting
  23. }
  24. form["fields"].append(field)
  25. return form
  26. def render_form(form: Dict[str, Any], indent: int = 0) -> str:
  27. """
  28. Renders the form structure to a string for debugging.
  29. Args:
  30. form: The form structure dictionary.
  31. indent: The indentation level.
  32. Returns:
  33. A string representing the rendered form.
  34. """
  35. indent_str = " " * indent
  36. output = f"{indent_str}Form: {form['name']}\n"
  37. for field in form["fields"]:
  38. output += f"{indent_str}{field['name']} ({field['label']}) - Type: {field['type']}\n"
  39. if "nested_form" in field:
  40. output += render_form(field["nested_form"], indent + 1) # Recursive call for nested forms
  41. return output
  42. if __name__ == '__main__':
  43. # Example usage:
  44. fields = {
  45. "personal_info": {
  46. "type": "form",
  47. "label": "Personal Information",
  48. "properties": {},
  49. "nested_form": {
  50. "name": "address",
  51. "label": "Address",
  52. "type": "form",
  53. "properties": {},
  54. "nested_form": None
  55. }
  56. },
  57. "name": {"type": "text", "label": "Name"},
  58. "email": {"type": "email", "label": "Email"},
  59. "age": {"type": "number", "label": "Age"}
  60. }
  61. nested_form = create_nested_form("User Form", fields)
  62. print(render_form(nested_form))

Add your comment