省市区三级联动的应用非常广泛,涉及到用户档案、收货地址什么的都需要用的,Go-Admin通过Field的FieldOptions、FieldOnChooseAjax、FieldOptionInitFn三个方法来完成三级联动。
一、准备基础数据方法[gorm]
//加载省
func GetMercProvOption() []types.FieldOption{
var results []types.FieldOption
var list []GopayMercProv
PayDB.Order("prov_name").Limit(50).Find(&list)
for _, item := range list {
results = append(results, types.FieldOption{Text: item.ProvName, Value: item.ProvCode})
}
return results
}
//城市
func GetMercCityOptionByProv(prov string) []selection.Option{
var results []selection.Option
var list []GopayMercCity
PayDB.Where("prov_code=?",prov).Order("city_name").Limit(50).Find(&list)
for _, item := range list {
results = append(results, selection.Option{ Text : item.CityName, ID: item.CityCode})
}
return results
}
func GetMercCityFieldOptionByProv(prov ,city string ) []types.FieldOption{
var results []types.FieldOption
var list []GopayMercCity
PayDB.Where("prov_code=?",prov).Order("city_name").Limit(50).Find(&list)
for _, item := range list {
results = append(results, types.FieldOption{ Text : item.CityName, Value: item.CityCode , Selected: item.CityCode==city })
}
return results
}
//区
func GetMercCountyOptionByCity(city string) []selection.Option{
var results []selection.Option
var list []GopayMercCounty
PayDB.Where("city_code=?",city).Order("county_name").Limit(50).Find(&list)
for _, item := range list {
results = append(results, selection.Option{ Text : item.CountyName, ID: item.CountyCode})
}
return results
}
func GetMercCountyFieldOptionByCity(city, county string) []types.FieldOption{
var results []types.FieldOption
var list []GopayMercCounty
PayDB.Where("city_code=?",city).Order("county_name").Limit(50).Find(&list)
for _, item := range list {
results = append(results, types.FieldOption{ Text : item.CountyName, Value: item.CountyCode, Selected: item.CountyCode == county })
}
return results
}
二、省市区下拉框
formList.AddField("归属省", "merc_prov", db.Varchar, form.SelectSingle).
FieldOptions(entitys.GetMercProvOption()).
FieldOnChooseAjax("merc_city", "/choose/prov", func(ctx *context.Context) (bool, string, interface{}) {
prov := ctx.FormValue("value")
return true, "ok", entitys.GetMercCityOptionByProv(prov)
})
formList.AddField("归属市", "merc_city", db.Varchar, form.SelectSingle).
FieldOnChooseAjax("merc_county", "/choose/city", func(ctx *context.Context) (bool, string, interface{}) {
city := ctx.FormValue("value")
return true, "ok", entitys.GetMercCountyOptionByCity(city)
}).
FieldOptionInitFn(func(val types.FieldModel) types.FieldOptions {
var prov = val.Row["merc_prov"].(string)
var city = val.Row["merc_city"].(string)
return entitys.GetMercCityFieldOptionByProv(prov,city)
})
formList.AddField("归属县区", "merc_county", db.Varchar, form.SelectSingle).
FieldOptionInitFn(func(val types.FieldModel) types.FieldOptions {
var city = val.Row["merc_city"].(string)
var county = val.Row["merc_county"].(string)
return entitys.GetMercCountyFieldOptionByCity(city,county)
})