|
| 1 | +""" |
| 2 | +Custom field types example for codeforms. |
| 3 | +
|
| 4 | +Demonstrates how to create and register custom field types, |
| 5 | +use them in forms, and perform JSON roundtrip serialization. |
| 6 | +""" |
| 7 | + |
| 8 | +import json |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +from pydantic import field_validator |
| 12 | + |
| 13 | +from codeforms import ( |
| 14 | + Form, |
| 15 | + FormFieldBase, |
| 16 | + FieldGroup, |
| 17 | + TextField, |
| 18 | + EmailField, |
| 19 | + register_field_type, |
| 20 | + get_registered_field_types, |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +# --------------------------------------------------------------------------- |
| 25 | +# 1. Define custom field types |
| 26 | +# --------------------------------------------------------------------------- |
| 27 | + |
| 28 | +class PhoneField(FormFieldBase): |
| 29 | + """A phone number field with an optional country code.""" |
| 30 | + field_type: str = "phone" |
| 31 | + country_code: str = "+1" |
| 32 | + placeholder: Optional[str] = "e.g. +1-555-0100" |
| 33 | + |
| 34 | + |
| 35 | +class RatingField(FormFieldBase): |
| 36 | + """A numeric rating field with configurable range.""" |
| 37 | + field_type: str = "rating" |
| 38 | + min_rating: int = 1 |
| 39 | + max_rating: int = 5 |
| 40 | + |
| 41 | + @field_validator("max_rating") |
| 42 | + @classmethod |
| 43 | + def max_above_min(cls, v, info): |
| 44 | + min_r = info.data.get("min_rating", 1) |
| 45 | + if v <= min_r: |
| 46 | + raise ValueError("max_rating must be greater than min_rating") |
| 47 | + return v |
| 48 | + |
| 49 | + |
| 50 | +class ColorField(FormFieldBase): |
| 51 | + """A colour picker field.""" |
| 52 | + field_type: str = "color" |
| 53 | + color_format: str = "hex" # hex | rgb | hsl |
| 54 | + |
| 55 | + |
| 56 | +# --------------------------------------------------------------------------- |
| 57 | +# 2. Register them |
| 58 | +# --------------------------------------------------------------------------- |
| 59 | + |
| 60 | +register_field_type(PhoneField) |
| 61 | +register_field_type(RatingField) |
| 62 | +register_field_type(ColorField) |
| 63 | + |
| 64 | + |
| 65 | +def show_registered_types(): |
| 66 | + """Print all registered field types.""" |
| 67 | + print("=" * 60) |
| 68 | + print("Registered field types") |
| 69 | + print("=" * 60) |
| 70 | + for key, classes in sorted(get_registered_field_types().items()): |
| 71 | + names = ", ".join(c.__name__ for c in classes) |
| 72 | + print(f" {key:12s} → {names}") |
| 73 | + print() |
| 74 | + |
| 75 | + |
| 76 | +def create_form_with_custom_fields(): |
| 77 | + """Build a form that mixes built-in and custom field types.""" |
| 78 | + print("=" * 60) |
| 79 | + print("Form with custom fields") |
| 80 | + print("=" * 60) |
| 81 | + |
| 82 | + form = Form( |
| 83 | + name="event_feedback", |
| 84 | + content=[ |
| 85 | + FieldGroup( |
| 86 | + title="Contact", |
| 87 | + fields=[ |
| 88 | + TextField(name="name", label="Full name", required=True), |
| 89 | + EmailField(name="email", label="Email"), |
| 90 | + PhoneField(name="phone", label="Phone", country_code="+54"), |
| 91 | + ], |
| 92 | + ), |
| 93 | + FieldGroup( |
| 94 | + title="Feedback", |
| 95 | + fields=[ |
| 96 | + RatingField( |
| 97 | + name="overall_rating", |
| 98 | + label="Overall rating", |
| 99 | + max_rating=10, |
| 100 | + ), |
| 101 | + ColorField( |
| 102 | + name="fav_color", |
| 103 | + label="Favourite colour", |
| 104 | + color_format="rgb", |
| 105 | + ), |
| 106 | + ], |
| 107 | + ), |
| 108 | + ], |
| 109 | + ) |
| 110 | + |
| 111 | + print(f"Form: {form.name}") |
| 112 | + print(f"Total fields: {len(form.fields)}") |
| 113 | + for f in form.fields: |
| 114 | + print(f" - {f.name} ({f.field_type_value})") |
| 115 | + print() |
| 116 | + return form |
| 117 | + |
| 118 | + |
| 119 | +def json_roundtrip(form: Form): |
| 120 | + """Serialize a form to JSON and back, preserving custom field data.""" |
| 121 | + print("=" * 60) |
| 122 | + print("JSON roundtrip") |
| 123 | + print("=" * 60) |
| 124 | + |
| 125 | + json_str = form.to_json() |
| 126 | + print("Serialized JSON (pretty):") |
| 127 | + print(json.dumps(json.loads(json_str), indent=2)) |
| 128 | + print() |
| 129 | + |
| 130 | + restored = Form.loads(json_str) |
| 131 | + print("Restored form fields:") |
| 132 | + for f in restored.fields: |
| 133 | + extra = "" |
| 134 | + if isinstance(f, PhoneField): |
| 135 | + extra = f" (country_code={f.country_code})" |
| 136 | + elif isinstance(f, RatingField): |
| 137 | + extra = f" (max_rating={f.max_rating})" |
| 138 | + elif isinstance(f, ColorField): |
| 139 | + extra = f" (color_format={f.color_format})" |
| 140 | + print(f" - {f.name}: {type(f).__name__}{extra}") |
| 141 | + print() |
| 142 | + |
| 143 | + |
| 144 | +def validate_custom_form(form: Form): |
| 145 | + """Validate user data against a form with custom fields.""" |
| 146 | + print("=" * 60) |
| 147 | + print("Data validation") |
| 148 | + print("=" * 60) |
| 149 | + |
| 150 | + data = { |
| 151 | + "name": "Juan", |
| 152 | + "email": "juan@example.com", |
| 153 | + "phone": "+54-11-5555-0100", |
| 154 | + "overall_rating": "8", |
| 155 | + "fav_color": "#3498db", |
| 156 | + } |
| 157 | + result = form.validate_data(data) |
| 158 | + print(f"Input: {data}") |
| 159 | + print(f"Result: success={result['success']}") |
| 160 | + if result.get("errors"): |
| 161 | + print(f"Errors: {result['errors']}") |
| 162 | + print() |
| 163 | + |
| 164 | + |
| 165 | +def export_html(form: Form): |
| 166 | + """Export the form to plain HTML.""" |
| 167 | + print("=" * 60) |
| 168 | + print("HTML export") |
| 169 | + print("=" * 60) |
| 170 | + export = form.export("html") |
| 171 | + print(export["output"][:500], "...") |
| 172 | + print() |
| 173 | + |
| 174 | + |
| 175 | +# --------------------------------------------------------------------------- |
| 176 | +# Run all examples |
| 177 | +# --------------------------------------------------------------------------- |
| 178 | + |
| 179 | +if __name__ == "__main__": |
| 180 | + show_registered_types() |
| 181 | + form = create_form_with_custom_fields() |
| 182 | + json_roundtrip(form) |
| 183 | + validate_custom_form(form) |
| 184 | + export_html(form) |
0 commit comments