1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-25 21:11:29 +00:00

Merge pull request #147 from miraclesu/form

ignore struct field if form tag value is '-'
This commit is contained in:
astaxie 2013-08-11 07:44:28 -07:00
commit ca1354e77f
2 changed files with 24 additions and 15 deletions

View File

@ -195,6 +195,8 @@ func ParseForm(form url.Values, obj interface{}) error {
var tag string
if len(tags) == 0 || len(tags[0]) == 0 {
tag = fieldT.Name
} else if tags[0] == "-" {
continue
} else {
tag = tags[0]
}
@ -280,19 +282,23 @@ func RenderForm(obj interface{}) template.HTML {
fieldT := objT.Field(i)
tags := strings.Split(fieldT.Tag.Get("form"), ",")
name := fieldT.Name
if len(tags) < 2 {
if len(tags) == 1 && len(tags[0]) > 0 {
name = tags[0]
}
raw = append(raw, fmt.Sprintf(`%v: <input name="%v" type="text" value="%v">`,
fieldT.Name, name, fieldV.Interface()))
} else {
fType := "text"
if len(tags) > 0 && tags[0] == "-" {
continue
}
if len(tags) == 1 && len(tags[0]) > 0 {
name = tags[0]
} else if len(tags) >= 2 {
if len(tags[0]) > 0 {
name = tags[0]
}
raw = append(raw, fmt.Sprintf(`%v: <input name="%v" type="%v" value="%v">`,
fieldT.Name, name, tags[1], fieldV.Interface()))
if len(tags[1]) > 0 {
fType = tags[1]
}
}
raw = append(raw, fmt.Sprintf(`%v: <input name="%v" type="%v" value="%v">`,
fieldT.Name, name, fType, fieldV.Interface()))
}
return template.HTML(strings.Join(raw, "</br>"))
}

View File

@ -104,8 +104,8 @@ func TestInSlice(t *testing.T) {
func TestParseForm(t *testing.T) {
type user struct {
Id int
tag string `form:tag`
Id int `form:"-"`
tag string `form:"tag"`
Name interface{} `form:"username"`
Age int `form:"age,text"`
Email string
@ -114,6 +114,8 @@ func TestParseForm(t *testing.T) {
u := user{}
form := url.Values{
"Id": []string{"1"},
"-": []string{"1"},
"tag": []string{"no"},
"username": []string{"test"},
"age": []string{"40"},
@ -148,10 +150,11 @@ func TestParseForm(t *testing.T) {
func TestRenderForm(t *testing.T) {
type user struct {
Id int
tag string `form:tag`
Id int `form:"-"`
tag string `form:"tag"`
Name interface{} `form:"username"`
Age int `form:"age,text"`
Sex string
Email []string
Intro string `form:",textarea"`
}
@ -163,9 +166,9 @@ func TestRenderForm(t *testing.T) {
}
output = RenderForm(&u)
result := template.HTML(
`Id: <input name="Id" type="text" value="0"></br>` +
`Name: <input name="username" type="text" value="test"></br>` +
`Name: <input name="username" type="text" value="test"></br>` +
`Age: <input name="age" type="text" value="0"></br>` +
`Sex: <input name="Sex" type="text" value=""></br>` +
`Intro: <input name="Intro" type="textarea" value="">`)
if output != result {
t.Errorf("output should equal `%v` but got `%v`", result, output)