golang select2

API作成

api_handler.go

// Index ...
func Index(c *gin.Context) {
    ctx := appengine.NewContext(c.Request)
    httpclient := urlfetch.Client(ctx)
    client, err := kintone.NewClient(
        os.Getenv("KINTONE_DOMAIN"),
        os.Getenv("KINTONE_USER"),
        os.Getenv("KINTONE_PASSWORD"),
        "38",
        httpclient,
    )
    if err != nil {
        panic(err)
    }

    var us []*user
    query := c.DefaultQuery("q", "")
    if query != "" {
        query := fmt.Sprintf(`name like "%s"`, c.Query("q"))
        rs, err := client.GetRecords(query)
        if err != nil {
            panic(err)
        }
        for _, r := range rs {
            var u user
            u.ID = string(r.Fields["employee_number"].(kintone.SingleLineTextField))
            u.Text = string(r.Fields["name"].(kintone.SingleLineTextField))
            us = append(us, &u)
        }
    }
    if len(us) > 0 {
        c.JSON(200, us)
    } else {
        b := []byte(`[]`)
        c.JSON(200, string(b))
    }
}

レスポンス

[{"id":"1","text":"{名前1}"},{"id":"2","text":"{名前2}"},

ajax

$(function(){
  $('select').select2({
    placeholder: "名前か従業員番号を入力して、検索してください",
    ajax: {
        url: "http://localhost:8080/api/apps/40/records",
        delay: 250,
        cache: true,
        dataType: 'json',
        type: "GET",
        data: function(params) {
          return { q: params.term };
        },
        processResults: function (data, params) {
        return { results: $.map(data, function(obj) {
            return { id: obj.id, text: obj.text };
          })
        };
      }
    }
  })
});

html

<label>{{.FieldInfo.Label}}</label>
<select name={{.FieldInfo.Code}} class="form-control">
</select>