constructors.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package forms
  2. import (
  3. "net/http"
  4. "strconv"
  5. )
  6. /* strFromPtr converts string pointer to a string */
  7. func strFromPtr(str *string) (s string) {
  8. if str != nil {
  9. s = *str
  10. }
  11. return
  12. }
  13. /* Generate new CharField field with type text */
  14. func NewCharField(name string, value *string) *FormField {
  15. return &FormField{
  16. Name: name,
  17. Value: strFromPtr(value),
  18. Kind: "text",
  19. }
  20. }
  21. /* Generate new integer type field */
  22. func NewIntField(name string, value int) *FormField {
  23. field := FormField{
  24. Name: name,
  25. Value: strconv.Itoa(value),
  26. Kind: "text",
  27. }
  28. field.AddValidator(ValidInt)
  29. return &field
  30. }
  31. /* Generate new password field */
  32. func NewPasswordField(name string) *FormField {
  33. return &FormField{
  34. Name: name,
  35. Kind: "password",
  36. }
  37. }
  38. /* Generate a new checkbox field */
  39. func NewCheckboxField(name string, checked bool) *FormField {
  40. return &FormField{
  41. Name: name,
  42. Checked: checked,
  43. Kind: "checkbox",
  44. }
  45. }
  46. /* Generate new select field */
  47. func NewSelectField(name string, items []string, value string) *FormField {
  48. return &FormField{
  49. Name: name,
  50. Select: items,
  51. Value: value,
  52. Kind: "select",
  53. }
  54. }
  55. /* Generate a new CSRF field */
  56. func NewCsrfField(w http.ResponseWriter, r *http.Request, secure bool) *FormField {
  57. return &FormField{
  58. Name: csrfFieldName,
  59. Value: csrfToken(w, r, secure),
  60. Kind: "hidden",
  61. Sticky: true,
  62. Validators: ValidatorsList{
  63. ValidCSRF(r),
  64. },
  65. }
  66. }
  67. /* Generate a new hidden text field */
  68. func NewHiddenField(name string, value *string) *FormField {
  69. return &FormField{
  70. Name: name,
  71. Value: strFromPtr(value),
  72. Kind: "hidden",
  73. }
  74. }