예제 #1
0
파일: controller.go 프로젝트: NeoChow/qor
func (s *Sorting) ConfigureQorResource(res *admin.Resource) {
	Admin := res.GetAdmin()
	res.UseTheme("sorting")

	if res.Config.Permission == nil {
		res.Config.Permission = roles.NewPermission()
	}

	for _, gopath := range strings.Split(os.Getenv("GOPATH"), ":") {
		admin.RegisterViewPath(path.Join(gopath, "src/github.com/qor/qor/sorting/views"))
	}

	role := res.Config.Permission.Role
	if _, ok := role.Get("sorting_mode"); !ok {
		role.Register("sorting_mode", func(req *http.Request, currentUser qor.CurrentUser) bool {
			return req.URL.Query().Get("sorting") != ""
		})
	}

	if res.GetMeta("Position") == nil {
		res.Meta(&admin.Meta{
			Name: "Position",
			Valuer: func(value interface{}, ctx *qor.Context) interface{} {
				db := ctx.GetDB()
				var count int
				var pos = value.(sortingInterface).GetPosition()

				if _, ok := modelValue(value).(sortingDescInterface); ok {
					if total, ok := db.Get("sorting_total_count"); ok {
						count = total.(int)
					} else {
						var result = res.NewStruct()
						db.New().Order("position DESC", true).First(result)
						count = result.(sortingInterface).GetPosition()
						db.InstantSet("sorting_total_count", count)
					}
					pos = count - pos + 1
				}

				primaryKey := ctx.GetDB().NewScope(value).PrimaryKeyValue()
				url := path.Join(ctx.Request.URL.Path, fmt.Sprintf("%v", primaryKey), "sorting/update_position")
				return template.HTML(fmt.Sprintf("<input type=\"number\" class=\"qor-sorting__position\" value=\"%v\" data-sorting-url=\"%v\" data-position=\"%v\">", pos, url, pos))
			},
			Permission: roles.Allow(roles.Read, "sorting_mode"),
		})
	}

	var attrs []string
	for _, attr := range res.IndexAttrs() {
		if attr != "Position" {
			attrs = append(attrs, attr)
		}
	}
	res.IndexAttrs(append(attrs, "Position")...)

	router := Admin.GetRouter()
	router.Post(fmt.Sprintf("^/%v/\\d+/sorting/update_position$", res.ToParam()), updatePosition)
}