diff --git a/src/pat/select2/select2.js b/src/pat/select2/select2.js index c7581723e..3518ff60c 100644 --- a/src/pat/select2/select2.js +++ b/src/pat/select2/select2.js @@ -217,15 +217,22 @@ export default Base.extend({ this.options.multiple === undefined ? true : this.options.multiple; this.options.ajax = this.options.ajax || {}; this.options.ajax.url = this.options.vocabularyUrl; - // XXX removing the following function does'nt break tests. dead code? this.options.initSelection = ($el, callback) => { const data = []; const value = $el.val(); for (const val of value.split(this.options.separator)) { + if (val === "") { + // Skip empty values, e.g. from an empty input. + continue; + } const _val = utils.removeHTML(val); data.push({ id: _val, text: _val }); } - callback(data); + // Select2 v3 expects a single object for single-select + // widgets and an array for multi-select widgets. Passing an + // array to a single select leaves `data.text` undefined and + // the pre-set value is not rendered. + callback(this.options.multiple ? data : data[0] || null); }; } diff --git a/src/pat/select2/select2.test.js b/src/pat/select2/select2.test.js index 7fd4cb70c..6301c5248 100644 --- a/src/pat/select2/select2.test.js +++ b/src/pat/select2/select2.test.js @@ -100,6 +100,50 @@ describe("Select2", function () { expect(select2.options.ajax.url).toEqual("select2-users-vocabulary"); }); + it("renders the preset value of a single-select input widget", async function () { + document.body.innerHTML = ` + + `; + + registry.scan(document.body); + await utils.timeout(1); + + const el = document.querySelector("input.pat-select2"); + expect($(el).select2("data")).toEqual({ + id: "Europe/Vienna", + text: "Europe/Vienna", + }); + expect($(el).parent().find(".select2-chosen").text()).toEqual("Europe/Vienna"); + }); + + it("renders the preset value of a single-select select widget", async function () { + document.body.innerHTML = ` + + `; + + registry.scan(document.body); + await utils.timeout(1); + + const el = document.querySelector("select.pat-select2"); + // For a native