model-builder-extensions.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package e21_presents
  2. import (
  3. "fmt"
  4. "github.com/qor5/admin/presets"
  5. "github.com/qor5/admin/presets/actions"
  6. . "github.com/qor5/ui/vuetify"
  7. "github.com/qor5/web"
  8. h "github.com/theplant/htmlgo"
  9. "gorm.io/gorm"
  10. )
  11. // @snippet_begin(PresetsModelBuilderExtensionsSample)
  12. func PresetsModelBuilderExtensions(b *presets.Builder) (
  13. mb *presets.ModelBuilder,
  14. db *gorm.DB,
  15. ) {
  16. mb, db = PresetsHelloWorld(b)
  17. b.URIPrefix(PresetsModelBuilderExtensionsPath)
  18. mb.LayoutConfig(&presets.LayoutConfig{SearchBoxInvisible: true})
  19. eb := mb.Editing("Actions", "Name").ActionsFunc(func(obj interface{}, ctx *web.EventContext) h.HTMLComponent {
  20. return h.Components(
  21. VSpacer(),
  22. VBtn("Action 1"),
  23. VBtn("Action 2"),
  24. VBtn("Update").
  25. Color("primary").
  26. Attr("@click", web.POST().
  27. EventFunc(actions.Update).
  28. Queries(ctx.Queries()).
  29. URL(mb.Info().ListingHref()).
  30. Go()),
  31. )
  32. })
  33. eb.Field("Actions").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  34. cust := obj.(*Customer)
  35. return VBtn("Change Name").Attr("@click",
  36. web.POST().
  37. EventFunc("changeName").
  38. Query(presets.ParamID, fmt.Sprint(cust.ID)).
  39. Go(),
  40. )
  41. })
  42. eb.ValidateFunc(func(obj interface{}, ctx *web.EventContext) (err web.ValidationErrors) {
  43. cust := obj.(*Customer)
  44. if len(cust.Name) < 5 {
  45. err.GlobalError("Name must be longer than 5")
  46. }
  47. return
  48. })
  49. mb.RegisterEventFunc("changeName", changeNameEventFunc(mb))
  50. return
  51. }
  52. func changeNameEventFunc(mb *presets.ModelBuilder) web.EventFunc {
  53. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  54. eb := mb.Editing()
  55. obj := mb.NewModel()
  56. id := ctx.R.FormValue(presets.ParamID)
  57. obj, err = eb.Fetcher(obj, id, ctx)
  58. obj.(*Customer).Name = "Darwin"
  59. err = eb.Saver(obj, id, ctx)
  60. presets.ShowMessage(&r, "Nicely updated", "")
  61. eb.UpdateOverlayContent(ctx, &r, obj, "Good work", err)
  62. return
  63. }
  64. }
  65. const PresetsModelBuilderExtensionsPath = "/samples/presets-model-builder-extensions"
  66. // @snippet_end