Skip to content

Commit

Permalink
Merge pull request #126 from tatang26/task-checkbox-tag-allow-string-…
Browse files Browse the repository at this point in the history
…and-arrays

Set a default value true and not checked when bool field is false
  • Loading branch information
paganotoni committed Oct 21, 2019
2 parents c7bf234 + c06cc88 commit a37ad3c
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 3 deletions.
64 changes: 64 additions & 0 deletions form/bootstrap/form_for_test.go
Expand Up @@ -334,3 +334,67 @@ func Test_Field_TagOnly(t *testing.T) {
})
}
}

func Test_Field_Boolean(t *testing.T) {
model := struct {
IsAdmin bool `schema:"-"`
}{}
cases := []struct {
f func(field string, opt tags.Options) *tags.Tag
Value bool
name string
opts tags.Options
output string
}{
{
Value: false,
name: "IsAdmin",
opts: tags.Options{
"tag_only": true,
"class": "custom-input",
},
output: `<input class="custom-input" id="-IsAdmin" name="IsAdmin" type="checkbox" value="true" />`,
},
{
Value: true,
name: "IsAdmin",
opts: tags.Options{
"tag_only": true,
"class": "custom-input",
},
output: `<input class="custom-input" id="-IsAdmin" name="IsAdmin" type="checkbox" value="true" checked />`,
},
{
Value: false,
name: "IsAdmin",
opts: tags.Options{},
output: `<div class="form-group"><label><input class="" id="-IsAdmin" name="IsAdmin" type="checkbox" value="true" /> IsAdmin</label></div>`,
},
{
Value: true,
name: "IsAdmin",
opts: tags.Options{},
output: `<div class="form-group"><label><input class="" id="-IsAdmin" name="IsAdmin" type="checkbox" value="true" checked /> IsAdmin</label></div>`,
},
{
Value: false,
name: "IsAdmin",
opts: tags.Options{
"unchecked": false,
},
output: `<div class="form-group"><label><input class="" id="-IsAdmin" name="IsAdmin" type="checkbox" value="true" /><input name="IsAdmin" type="hidden" value="false" /> IsAdmin</label></div>`,
},
}

for index, tcase := range cases {
t.Run(fmt.Sprintf("%v", index), func(tt *testing.T) {
r := require.New(tt)

model.IsAdmin = tcase.Value
f := bootstrap.NewFormFor(model, tags.Options{})

l := f.CheckboxTag(tcase.name, tcase.opts)
r.Equal(tcase.output, l.String())
})
}
}
6 changes: 3 additions & 3 deletions form/form_for.go
Expand Up @@ -96,10 +96,10 @@ func (f FormFor) buildCheckboxOptions(field string, opts tags.Options) {
if fn.Kind() == reflect.Bool {
if ov == nil {
opts["value"] = true
}

if opts["checked"] == nil && !fn.Bool() {
opts["checked"] = fn.Bool()
}
if opts["checked"] == nil && !fn.Bool() {
opts["checked"] = fn.Bool()
}
}
}
Expand Down

0 comments on commit a37ad3c

Please sign in to comment.