Add grouping for form’s select field

We will only allow to select a tax from each of the tax classes, but
the user needs to know what class each tax belongs to, and grouping
the taxes by class in the select helps with that.
This commit is contained in:
jordi fita mas 2023-03-01 11:40:23 +01:00
parent 2add9c74c1
commit 79ea2f366a
3 changed files with 38 additions and 3 deletions

View File

@ -66,6 +66,7 @@ func (field *InputField) Float64() float64 {
type SelectOption struct {
Value string
Label string
Group string
}
type SelectField struct {
@ -158,6 +159,29 @@ func MustGetOptions(ctx context.Context, conn *Conn, sql string, args ...interfa
return options
}
func MustGetGroupedOptions(ctx context.Context, conn *Conn, sql string, args ...interface{}) []*SelectOption {
rows, err := conn.Query(ctx, sql, args...)
if err != nil {
panic(err)
}
defer rows.Close()
var options []*SelectOption
for rows.Next() {
option := &SelectOption{}
err = rows.Scan(&option.Value, &option.Label, &option.Group)
if err != nil {
panic(err)
}
options = append(options, option)
}
if rows.Err() != nil {
panic(rows.Err())
}
return options
}
func mustGetCountryOptions(ctx context.Context, conn *Conn, locale *Locale) []*SelectOption {
return MustGetOptions(ctx, conn, "select country.country_code, coalesce(i18n.name, country.name) as l10n_name from country left join country_i18n as i18n on country.country_code = i18n.country_code and i18n.lang_tag = $1 order by l10n_name", locale.Language)
}

View File

@ -418,7 +418,7 @@ func (form *invoiceForm) AddProducts(ctx context.Context, conn *Conn, productsId
}
func mustGetTaxOptions(ctx context.Context, conn *Conn, company *Company) []*SelectOption {
return MustGetOptions(ctx, conn, "select tax_id::text, name from tax where company_id = $1 order by name", company.Id)
return MustGetGroupedOptions(ctx, conn, "select tax_id::text, tax.name, tax_class.name from tax join tax_class using (tax_class_id) where tax.company_id = $1 order by tax_class.name, tax.name", company.Id)
}
type invoiceProductForm struct {

View File

@ -43,16 +43,27 @@
<div class="input {{ if .Errors }}has-errors{{ end }}">
<select id="{{ .Name }}-field" name="{{ .Name }}"
{{- range $attribute := .Attributes }} {{$attribute}} {{ end -}}
{{ if .Multiple }}multiple="multiple"{{ end }}
{{ if .Required }}required="required"{{ end }}
{{ if .Multiple }} multiple="multiple"{{ end -}}
{{ if .Required }} required="required"{{ end -}}
>
{{- with .EmptyLabel }}
<option value="">{{ . }}</option>
{{- end}}
{{- $withinGroup := "" -}}
{{- range $option := .Options }}
{{- if ne .Group $withinGroup }}
{{- if ne $withinGroup "" }}
</optgroup>
{{ end }}
<optgroup label="{{ .Group }}">
{{- $withinGroup = .Group -}}
{{ end }}
<option value="{{ .Value }}"
{{- if $.IsSelected .Value }} selected="selected"{{ end }}>{{ .Label }}</option>
{{- end }}
{{- if ne $withinGroup "" }}
</optgroup>
{{- end }}
</select>
<label for="{{ .Name }}-field">{{ .Label }}</label>
{{- if .Errors }}