Common isomorphic functionality in one kit.

basicform.go 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // The Isomorphic Go Project
  2. // Copyright (c) Wirecog, LLC. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license, which can be found in the LICENSE file.
  5. package isokit
  6. import "strings"
  7. type BasicForm struct {
  8. formParams *FormParams
  9. prefillFields []string
  10. fields map[string]string
  11. errors map[string]string
  12. }
  13. func (c *BasicForm) PrefillFields() []string {
  14. return c.prefillFields
  15. }
  16. func (c *BasicForm) Fields() map[string]string {
  17. return c.fields
  18. }
  19. func (c *BasicForm) Errors() map[string]string {
  20. return c.errors
  21. }
  22. func (c *BasicForm) FormParams() *FormParams {
  23. return c.formParams
  24. }
  25. func (c *BasicForm) SetPrefillFields(prefillFields []string) {
  26. c.prefillFields = prefillFields
  27. }
  28. func (c *BasicForm) SetFields(fields map[string]string) {
  29. c.fields = fields
  30. }
  31. func (c *BasicForm) GetFieldValue(key string) string {
  32. if _, ok := c.fields[key]; ok {
  33. return c.fields[key]
  34. } else {
  35. return ""
  36. }
  37. }
  38. func (c *BasicForm) SetErrors(errors map[string]string) {
  39. c.errors = errors
  40. }
  41. func (c *BasicForm) SetFormParams(formParams *FormParams) {
  42. c.formParams = formParams
  43. }
  44. func (c *BasicForm) SetError(key string, message string) {
  45. c.errors[key] = message
  46. }
  47. func (c *BasicForm) ClearErrors() {
  48. c.errors = make(map[string]string)
  49. }
  50. func (c *BasicForm) PopulateFields() {
  51. for _, fieldName := range c.prefillFields {
  52. c.fields[fieldName] = FormValue(c.FormParams(), fieldName)
  53. }
  54. }
  55. func (c *BasicForm) DisplayErrors() {
  56. if OperatingEnvironment() == WebBrowserEnvironment && c.formParams.FormElement != nil {
  57. errorSpans := c.formParams.FormElement.QuerySelectorAll(".formError")
  58. for _, v := range errorSpans {
  59. v.SetInnerHTML(c.errors[strings.Replace(v.GetAttribute("id"), "Error", "", -1)])
  60. }
  61. }
  62. }
  63. func (c *BasicForm) RegenerateErrors() {
  64. c.errors = make(map[string]string)
  65. if OperatingEnvironment() == WebBrowserEnvironment && c.formParams.FormElement != nil {
  66. errorSpans := c.formParams.FormElement.QuerySelectorAll(".formError")
  67. for _, v := range errorSpans {
  68. v.SetInnerHTML(c.errors[strings.Replace(v.GetAttribute("id"), "Error", "", -1)])
  69. }
  70. }
  71. }