forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
representation.go
71 lines (62 loc) · 1.47 KB
/
representation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package uadmin
import (
"fmt"
"reflect"
"strings"
)
// GetID !
func GetID(m reflect.Value) uint {
if m.Kind() == reflect.Ptr {
return uint(m.Elem().FieldByName("ID").Uint())
}
return uint(m.FieldByName("ID").Uint())
}
// GetString returns string representation on an instance of
// a model
func GetString(a interface{}) string {
str, ok := a.(fmt.Stringer)
if ok {
return str.String()
}
t := reflect.TypeOf(a)
v := reflect.ValueOf(a)
if t.Kind() != reflect.Ptr && t.Kind() == reflect.Struct {
v = reflect.Indirect(reflect.New(t))
v.Set(reflect.ValueOf(a))
sp := v.Addr().Interface()
str, ok := sp.(fmt.Stringer)
if ok {
return str.String()
}
if _, ok := t.FieldByName("Name"); ok {
return v.FieldByName("Name").String()
}
} else if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct {
// Check if nil
if v.IsNil() {
return ""
}
if _, ok := t.Elem().FieldByName("Name"); ok {
return v.Elem().FieldByName("Name").String()
}
}
return fmt.Sprint(a)
}
// getChoices return a list of choices
func getChoices(ModelName string) []Choice {
choices := []Choice{
{" - ", 0, false},
}
m, ok := NewModelArray(strings.ToLower(ModelName), true)
// If no model exists, return an empty choices list
if !ok {
return choices
}
// Get all choices
All(m.Addr().Interface())
for i := 0; i < m.Len(); i++ {
id := GetID(m.Index(i))
choices = append(choices, Choice{fmt.Sprint(m.Index(i).Interface()), uint(id), false})
}
return choices
}