Skip to content

Commit

Permalink
MVC / form handling (opnsense.js) -- Support optgroup atributes for s…
Browse files Browse the repository at this point in the history
…elect boxes, when a fieldtype offers an "optgroup" attribute on an element the items will be put into <optgroup> containers.

<optgroup label='my_group'>
  <option value='1'>option 1</option>
</optgroup>

Required for #6928
  • Loading branch information
AdSchellevis committed Oct 12, 2023
1 parent 1bec000 commit 9206823
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/opnsense/www/js/opnsense.js
Expand Up @@ -147,6 +147,7 @@ function setFormData(parent,data) {
targetNode.tokenize2().trigger('tokenize:clear');
}
targetNode.empty(); // flush
let optgroups = [];
if (Array.isArray(node[keypart]) && node[keypart][0] !== undefined && node[keypart][0].key !== undefined) {
// key value (sorted) list
// (eg node[keypart][0] = {selected: 0, value: 'my item', key: 'item'})
Expand All @@ -155,19 +156,34 @@ function setFormData(parent,data) {
if (String(node[keypart][i].selected) !== "0") {
opt.attr('selected', 'selected');
}
targetNode.append(opt);
let optgroup = node[keypart][i].optgroup ?? '';
if (optgroups[optgroup] === undefined) {
optgroups[optgroup] = [];
}
optgroups[optgroup].push(opt);
}
} else{
// default "dictionary" type select items
// (eg node[keypart]['item'] = {selected: 0, value: 'my item'})
$.each(node[keypart],function(indxItem, keyItem){
let opt = $("<option>").val(htmlDecode(indxItem)).text(keyItem["value"]);
let optgroup = keyItem.optgroup ?? '';
if (String(keyItem["selected"]) !== "0") {
opt.attr('selected', 'selected');
}
targetNode.append(opt);
if (optgroups[optgroup] === undefined) {
optgroups[optgroup] = [];
}
optgroups[optgroup].push(opt);
});
}
for (const [group, items] of Object.entries(optgroups)) {
if (group == '' && optgroups.length == 1) {
targetNode.append(items);
} else {
targetNode.append($("<optgroup/>").attr('label', group).append(items));
}
}
} else if (targetNode.prop("type") === "checkbox") {
// checkbox type
targetNode.prop("checked", node[keypart] != 0);
Expand Down

0 comments on commit 9206823

Please sign in to comment.