customer_config.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package admin
  2. import (
  3. "github.com/qor5/admin/example/models"
  4. "github.com/qor5/admin/media"
  5. "github.com/qor5/admin/media/media_library"
  6. media_view "github.com/qor5/admin/media/views"
  7. "github.com/qor5/admin/presets"
  8. "github.com/qor5/admin/presets/gorm2op"
  9. "github.com/qor5/web"
  10. "gorm.io/gorm"
  11. )
  12. func configNestedFieldDemo(b *presets.Builder, db *gorm.DB) {
  13. cust := b.Model(&models.Customer{}).RightDrawerWidth("50%").
  14. Label("NestedFieldDemos").URIName("nested-field-demos")
  15. addFb := b.NewFieldsBuilder(presets.WRITE).Model(&models.Address{}).Only("Street", "HomeImage", "Phones")
  16. addFb.Field("HomeImage").WithContextValue(media_view.MediaBoxConfig, &media_library.MediaBoxConfig{
  17. AllowType: "image",
  18. Sizes: map[string]*media.Size{
  19. "thumb": {
  20. Width: 400,
  21. Height: 300,
  22. },
  23. "main": {
  24. Width: 800,
  25. Height: 500,
  26. },
  27. },
  28. })
  29. var phoneFb = b.NewFieldsBuilder(presets.WRITE).Model(&models.Phone{}).Only("Number")
  30. addFb.Field("Phones").Nested(phoneFb, &presets.DisplayFieldInSorter{Field: "Number"})
  31. ed := cust.Editing("Name", "Addresses", "MembershipCard")
  32. ed.Field("Addresses").Nested(addFb, &presets.DisplayFieldInSorter{Field: "Street"})
  33. cardFb := b.NewFieldsBuilder(presets.WRITE).Model(&models.MembershipCard{}).Only("Number", "ValidBefore")
  34. ed.Field("MembershipCard").Nested(cardFb)
  35. ed.FetchFunc(func(obj interface{}, id string, ctx *web.EventContext) (r interface{}, err error) {
  36. return gorm2op.DataOperator(db.Preload("Addresses.Phones").Preload("MembershipCard")).Fetch(obj, id, ctx)
  37. })
  38. ed.SaveFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  39. c := obj.(*models.Customer)
  40. err = db.Delete(&models.Phone{}, "address_id IN (select id from addresses where customer_id = ?)", c.ID).Error
  41. if err != nil {
  42. panic(err)
  43. }
  44. err = db.Delete(&models.Address{}, "customer_id = ?", c.ID).Error
  45. if err != nil {
  46. panic(err)
  47. }
  48. return gorm2op.DataOperator(db.Session(&gorm.Session{FullSaveAssociations: true})).Save(obj, id, ctx)
  49. })
  50. }