How To Use Admin Plugin
The Admin plugin can help you to quickly generate a platform for database data table query, adding, deleting, and editing.

Quick Start

Following the steps:
    Generate a configuration file corresponding to the data table
    Set access routing
    Initialize and load in the engine
    Set access menu

Step 1. Generate configuration file

Suppose you have a data table users in your database, such as:
1
CREATE TABLE `users` (
2
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
3
`name` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
4
`gender` tinyint(4) DEFAULT NULL,
5
`city` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
6
`ip` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
7
`phone` varchar(10) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
8
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
9
`updated_at` timestamp NULL DEFAULT NULL,
10
PRIMARY KEY (`id`)
11
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Copied!
Use the command line tools - adm to help you quickly generate configuration files:
    install adm
1
go install github.com/GoAdminGroup/adm
Copied!
    generate
Execute the command in your project folder
1
adm generate
Copied!
Notice: use space to choose table, not enter
Fill in the information according to the prompts. After the run, a file users.go will be generated. This is the configuration file corresponding to the data table. How to configure it is described in detail later.

Step 2. Set access url

After the configuration file is generated, a routing configuration file tables.go will also be generated :
1
package main
2
3
import "github.com/GoAdminGroup/go-admin/plugins/admin/models"
4
5
// The key of Generators is the prefix of table info url.
6
// The corresponding value is the Form and Table data.
7
//
8
// http://{{config.DOMAIN}}:{{PORT}}/{{config.PREFIX}}/info/{{key}}
9
//
10
// example:
11
//
12
// "user" => http://localhost:9033/admin/info/user
13
//
14
var Generators = map[string]models.TableGenerator{
15
"user": GetUserTable,
16
}
Copied!
"user" is the corresponding access route prefix, GetUserTable is the table data generation method. The corresponding access routing address is: http://localhost:9033/admin/info/user

Step 3. Initialize and load in the engine

To initialize, you need to call the eng.AddGenerators method, and then pass the Generators above.
1
package main
2
3
import (
4
_ "github.com/GoAdminGroup/go-admin/adapter/gin" // Import the adapter, it must be imported. If it is not imported, you need to define it yourself.
5
_ "github.com/GoAdminGroup/themes/adminlte" // Import the theme
6
_ "github.com/GoAdminGroup/go-admin/modules/db/drivers/mysql" // Import the sql driver
7
8
"github.com/gin-gonic/gin"
9
"github.com/GoAdminGroup/go-admin/engine"
10
"github.com/GoAdminGroup/go-admin/plugins/admin"
11
"github.com/GoAdminGroup/go-admin/modules/config"
12
"github.com/GoAdminGroup/go-admin/modules/language"
13
)
14
15
func main() {
16
r := gin.Default()
17
eng := engine.Default()
18
cfg := config.Config{
19
Databases: config.DatabaseList{
20
"default": {
21
Host: "127.0.0.1",
22
Port: "3306",
23
User: "root",
24
Pwd: "root",
25
Name: "godmin",
26
MaxIdleCon: 50,
27
MaxOpenCon: 150,
28
Driver: config.DriverMysql,
29
},
30
},
31
UrlPrefix: "admin",
32
Store: config.Store{
33
Path: "./uploads",
34
Prefix: "uploads",
35
},
36
Language: language.CN,
37
}
38
39
// AddGenerator can also be used to load the Generator, like:
40
// eng.AddGenerator("user", GetUserTable)
41
42
eng.AddConfig(cfg).
43
AddGenerators(Generators). // 加载插件
44
Use(r)
45
46
r.Run(":9033")
47
}
Copied!

Step 4. Set access menu

After running, access the login URL, enter the menu management page, and then set the management menu of the data table to enter in the sidebar.
In the above example, the login URL is http://localhost:9033/admin/login
The menu management page is http://localhost:9033/admin/menu

Introduction of the business data table generation method

1
package datamodel
2
3
import (
4
"fmt"
5
"github.com/GoAdminGroup/go-admin/modules/db"
6
form2 "github.com/GoAdminGroup/go-admin/plugins/admin/modules/form"
7
"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
8
"github.com/GoAdminGroup/go-admin/template/types"
9
"github.com/GoAdminGroup/go-admin/template/types/form"
10
)
11
12
func GetUserTable(ctx *context.Context) (userTable table.Table) {
13
14
// config the table model.
15
userTable = table.NewDefaultTable(table.Config{
16
Driver: db.DriverMysql,
17
CanAdd: true,
18
Editable: true,
19
Deletable: true,
20
Exportable: true,
21
Connection: table.DefaultConnectionName,
22
PrimaryKey: table.PrimaryKey{
23
Type: db.Int,
24
Name: table.DefaultPrimaryKeyName,
25
},
26
})
27
28
info := userTable.GetInfo()
29
30
// set id sortable.
31
info.AddField("ID", "id", db.Int).FieldSortable(true)
32
info.AddField("Name", "name", db.Varchar)
33
34
// use FieldDisplay.
35
info.AddField("Gender", "gender", db.Tinyint).FieldDisplay(func(model types.FieldModel) interface{} {
36
if model.Value == "0" {
37
return "men"
38
}
39
if model.Value == "1" {
40
return "women"
41
}
42
return "unknown"
43
})
44
45
info.AddField("Phone", "phone", db.Varchar)
46
info.AddField("City", "city", db.Varchar)
47
info.AddField("CreatedAt", "created_at", db.Timestamp)
48
info.AddField("UpdatedAt", "updated_at", db.Timestamp)
49
50
// set the title and description of table page.
51
info.SetTable("users").SetTitle("Users").SetDescription("Users").
52
SetAction(template.HTML(`<a href="http://google.com"><i class="fa fa-google"></i></a>`)) // custom operation button
53
54
formList := userTable.GetForm()
55
56
// set id editable is false.
57
formList.AddField("ID", "id", db.Int, form.Default).FieldNotAllowEdit()
58
formList.AddField("Ip", "ip", db.Varchar, form.Text)
59
formList.AddField("Name", "name", db.Varchar, form.Text)
60
61
// use FieldOptions.
62
formList.AddField("Gender", "gender", db.Tinyint, form.Radio).
63
FieldOptions(types.FieldOptions{
64
{
65
Text: "male",
66
Value: "0",
67
}, {
68
Text: "female",
69
Value: "1",
70
},
71
}).FieldDefault("0")
72
formList.AddField("Phone", "phone", db.Varchar, form.Text)
73
formList.AddField("City", "city", db.Varchar, form.Text)
74
75
// add a custom field and use FieldPostFilterFn to do more things.
76
formList.AddField("Custom Field", "role", db.Varchar, form.Text).
77
FieldPostFilterFn(func(value types.PostFieldModel) interface{} {
78
fmt.Println("user custom field", value)
79
return ""
80
})
81
82
formList.AddField("UpdatedAt", "updated_at", db.Timestamp, form.Default).FieldNotAllowAdd(true)
83
formList.AddField("CreatedAt", "created_at", db.Timestamp, form.Default).FieldNotAllowAdd(true)
84
85
// use SetTabGroups to group a form into tabs.
86
formList.SetTabGroups(types.
87
NewTabGroups("id", "ip", "name", "gender", "city").
88
AddGroup("phone", "role", "created_at", "updated_at")).
89
SetTabHeaders("profile1", "profile2")
90
91
// set the title and description of form page.
92
formList.SetTable("users").SetTitle("Users").SetDescription("Users")
93
94
// use SetPostHook to add operation when form posted.
95
formList.SetPostHook(func(values form2.Values) {
96
fmt.Println("userTable.GetForm().PostHook", values)
97
})
98
99
return
100
}
Copied!
Initialized by calling models.NewDefaultTable(models.DefaultTableConfig) method to pass data table model configuration. The data table model is configured as:
1
type Config struct {
2
Driver string // database driver
3
Connection string // database connection name, defined in the global configuration
4
CanAdd bool // Can I add data
5
Editable bool // Can I edit
6
Deletable bool // Can I delete it
7
Exportable bool // Whether it can be exported
8
PrimaryKey PrimaryKey // primary key of the data table
9
}
10
11
type PrimaryKey struct {
12
Type db.DatabaseType // primary key type
13
Name string // primary key name
14
}
Copied!
The business data table generation method is a function that returns a type object of models.Table. The following is the definition of models.Table:
1
type Table interface {
2
GetInfo() *types.InfoPanel
3
GetDetail() *types.InfoPanel
4
GetDetailFromInfo() *types.InfoPanel
5
GetForm() *types.FormPanel
6
7
GetCanAdd() bool
8
GetEditable() bool
9
GetDeletable() bool
10
GetExportable() bool
11
12
GetPrimaryKey() PrimaryKey
13
14
GetData(params parameter.Parameters) (PanelInfo, error)
15
GetDataWithIds(params parameter.Parameters) (PanelInfo, error)
16
GetDataWithId(params parameter.Parameters) (FormInfo, error)
17
UpdateData(dataList form.Values) error
18
InsertData(dataList form.Values) error
19
DeleteData(pk string) error
20
21
GetNewForm() FormInfo
22
23
Copy() Table
24
}
Copied!
It mainly includes GetInfo() and GetForm(). The UI corresponding to the type returned by these two functions is the table for displaying data and the form for editing or creating data. The screenshots are as follows:
    This is the Info.
Could not load image
    This is the Form.
Could not load image

Info

1
type InfoPanel struct {
2
FieldList FieldList
3
4
Table string
5
Title string
6
Description string
7
8
TabGroups TabGroups
9
TabHeaders TabHeaders
10
11
Sort Sort
12
SortField string
13
14
PageSizeList []int
15
DefaultPageSize int
16
17
ExportType int
18
19
IsHideNewButton bool
20
IsHideExportButton bool
21
IsHideEditButton bool
22
IsHideDeleteButton bool
23
IsHideDetailButton bool
24
IsHideFilterButton bool
25
IsHideRowSelector bool
26
IsHidePagination bool
27
IsHideFilterArea bool
28
FilterFormLayout form.Layout
29
30
FilterFormHeadWidth int
31
FilterFormInputWidth int
32
33
Wheres Wheres
34
WhereRaws WhereRaw
35
36
TableLayout string
37
38
DeleteHook DeleteFn
39
PreDeleteFn DeleteFn
40
DeleteFn DeleteFn
41
42
DeleteHookWithRes DeleteFnWithRes
43
44
GetDataFn GetDataFn
45
46
Action template.HTML
47
HeaderHtml template.HTML
48
FooterHtml template.HTML
49
}
50
51
type Field struct {
52
Head string // title
53
Field string // field name
54
TypeName db.DatabaseType // database type name
55
56
Join Join // join table setting
57
58
Width int // width
59
Sortable bool // sortable
60
Fixed bool // fixed
61
Filterable bool // filterable
62
Hide bool // hide or not
63
64
EditType table.Type // edit type
65
EditOptions FieldOptions // edit options
66
67
Display FieldFilterFn // display filter callback function
68
DisplayProcessChains DisplayProcessFnChains // display process function chains
69
}
70
71
// join table setting
72
// example: left join Table on Table.JoinField = Field
73
type Join struct {
74
Table string
75
Field string
76
JoinField string
77
}
Copied!

Form

1
type FormPanel struct {
2
FieldList FormFields // form field list
3
curFieldListIndex int
4
5
// Warn: may be deprecated future.
6
TabGroups TabGroups // tabs, [example](https://github.com/GoAdminGroup/go-admin/blob/master/examples/datamodel/user.go#L76)
7
TabHeaders TabHeaders // tabs headers, [example](https://github.com/GoAdminGroup/go-admin/blob/master/examples/datamodel/user.go#L78)
8
9
Table string
10
Title string
11
Description string
12
13
Validator FormValidator // form post validator function
14
PostHook FormPostHookFn // form post hook function
15
PreProcessFn FormPreProcessFn // form post pre process function
16
17
IsHideContinueEditCheckBox bool
18
IsHideContinueNewCheckBox bool
19
IsHideResetButton bool
20
IsHideBackButton bool
21
22
HeaderHtml template.HTML // header custom html content
23
FooterHtml template.HTML // footer custom html content
24
25
UpdateFn FormPostFn // Form update function, set up this function, it took over the form of updates, PostHook is no longer in effect
26
InsertFn FormPostFn // Form inserts function, set up this function, it took over the form of the insert, PostHook effect no longer
27
}
28
29
type FormPostFn func(values form.Values) error
30
31
// form hook function type
32
type PostHookFn func(values form.Values)
33
34
type FormField struct {
35
Field string
36
TypeName string
37
Head string
38
FormType form.Type
39
40
Default string
41
Value string
42
Options []map[string]string
43
DefaultOptionDelimiter string
44
45
Editable bool
46
NotAllowAdd bool
47
Must bool
48
Hide bool
49
50
HelpMsg template.HTML
51
OptionExt template.JS
52
53
Display FieldFilterFn
54
DisplayProcessChains DisplayProcessFnChains
55
PostFilterFn PostFieldFilterFn
56
57
Placeholder string
58
59
CustomContent template.HTML
60
CustomJs template.JS
61
CustomCss template.CSS
62
63
Width int
64
65
Divider bool
66
DividerTitle string
67
68
OptionExt template.JS
69
OptionInitFn OptionInitFn
70
OptionTable OptionTable
71
}
Copied!
The currently supported form types are:
    default
    normal text
    Single selection
    Password
    rich text
    File
    Code
    double selection box
    Multiple choices
    icon drop-down selection box
    time selection box
    radio selection box
    email input box
    url input box
    ip input box
    color selection box
    Currency input box
    Digital input box
</br>
Can be used like this:
1
import "github.com/GoAdminGroup/go-admin/template/types/form"
2
3
...
4
FormType: form.File,
5
...
Copied!
See more in:admin form components
Where field is the name of the field and value is the value corresponding to the selection.

Filter function FilterFn and processing function PostFn description

The data which framework retrieve from database will be displayed in the table or form. If you want to transform them before displaying, for example turn capital or add some html style etc, you can do that using the field filter callback function. Of course, the framework have some built-in data process functions which will be introduced in the chapter of admin table.
1
// FieldModel contains ID and value of the single query result.
2
type FieldModel struct {
3
ID string
4
Value string
5
}
6
7
// FieldFilterFn determines the value that is retrieved from the database
8
// and passes to the format displayed by the front end.
9
//
10
// The type currently accepted for return is: template.HTML, string, []string
11
//
12
// For tables, you can return the template.HTML type, including html and css
13
// styles, so that the fields in the table can be personalized, such as:
14
//
15
// FilterFn: func(model types.FieldModel) interface{} {
16
// return template.Get("adminlte").Label().SetContent(template2.HTML(model.Value)).GetContent()
17
// },
18
//
19
// For forms, note that if it is a select box type: Select/SelectSingle/SelectBox,
20
// you need to return an array: []string, such as:
21
//
22
// FilterFn: func(model types.FieldModel) interface{} {
23
// return strings.Split(model.Value, ",")
24
// },
25
//
26
// For other form types, return the string type
27
//
28
type FieldFilterFn func(value FieldModel) interface{}
29
30
// PostFieldModel contains ID and value of the single query result.
31
type PostFieldModel struct {
32
ID string
33
Value FieldModelValue
34
Row map[string]interface{}
35
}
36
37
type FieldModelValue []string
38
39
func (r FieldModelValue) Value() string {
40
return r.First()
41
}
42
43
func (r FieldModelValue) First() string {
44
return r[0]
45
}
Copied!
English is not my main language. If any typo or wrong translation you found, you can help to translate in github here. I will very appreciate it.
Last modified 1mo ago