form.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. """Form components."""
  2. from __future__ import annotations
  3. from reflex.components.chakra import ChakraComponent
  4. from reflex.components.component import Component
  5. from reflex.components.el.elements.forms import Form as HTMLForm
  6. from reflex.vars import Var
  7. class Form(ChakraComponent, HTMLForm):
  8. """A form component."""
  9. tag = "Box"
  10. # What the form renders to.
  11. as_: Var[str] = "form" # type: ignore
  12. class FormControl(ChakraComponent):
  13. """Provide context to form components."""
  14. tag = "FormControl"
  15. # If true, the form control will be disabled.
  16. is_disabled: Var[bool]
  17. # If true, the form control will be invalid.
  18. is_invalid: Var[bool]
  19. # If true, the form control will be readonly
  20. is_read_only: Var[bool]
  21. # If true, the form control will be required.
  22. is_required: Var[bool]
  23. # The label text used to inform users as to what information is requested for a text field.
  24. label: Var[str]
  25. @classmethod
  26. def create(
  27. cls,
  28. *children,
  29. label=None,
  30. input=None,
  31. help_text=None,
  32. error_message=None,
  33. **props,
  34. ) -> Component:
  35. """Create a form control component.
  36. Args:
  37. *children: The children of the form control.
  38. label: The label of the form control.
  39. input: The input of the form control.
  40. help_text: The help text of the form control.
  41. error_message: The error message of the form control.
  42. **props: The properties of the form control.
  43. Raises:
  44. AttributeError: raise an error if missing required kwargs.
  45. Returns:
  46. The form control component.
  47. """
  48. if len(children) == 0:
  49. children = []
  50. if label:
  51. children.append(FormLabel.create(*label))
  52. if not input:
  53. raise AttributeError("input keyword argument is required")
  54. children.append(input)
  55. if help_text:
  56. children.append(FormHelperText.create(*help_text))
  57. if error_message:
  58. children.append(FormErrorMessage.create(*error_message))
  59. return super().create(*children, **props)
  60. class FormHelperText(ChakraComponent):
  61. """A form helper text component."""
  62. tag = "FormHelperText"
  63. class FormLabel(ChakraComponent):
  64. """A form label component."""
  65. tag = "FormLabel"
  66. # Link
  67. html_for: Var[str]
  68. class FormErrorMessage(ChakraComponent):
  69. """A form error message component."""
  70. tag = "FormErrorMessage"