Add support for setting a 'null' option

This commit is contained in:
Jeremy Stretch 2024-02-07 13:46:30 -05:00
parent 3874c8de9b
commit 6926b3709e
3 changed files with 19 additions and 4 deletions

Binary file not shown.

Binary file not shown.

View File

@ -1,4 +1,4 @@
import { RecursivePartial, TomInput, TomSettings } from 'tom-select/dist/types/types'; import { RecursivePartial, TomInput, TomOption, TomSettings } from 'tom-select/dist/types/types';
import { addClasses } from 'tom-select/src/vanilla' import { addClasses } from 'tom-select/src/vanilla'
import queryString from 'query-string'; import queryString from 'query-string';
import TomSelect from 'tom-select'; import TomSelect from 'tom-select';
@ -13,9 +13,9 @@ import { getElement, replaceAll } from '../../util';
// Extends TomSelect to provide enhanced fetching of options via the REST API // Extends TomSelect to provide enhanced fetching of options via the REST API
export class DynamicTomSelect extends TomSelect { export class DynamicTomSelect extends TomSelect {
/* public readonly nullOption: Nullable<TomOption> = null;
* Transitional code from APISelect
*/ // Transitional code from APISelect
private readonly queryParams: QueryFilter = new Map(); private readonly queryParams: QueryFilter = new Map();
private readonly staticParams: QueryFilter = new Map(); private readonly staticParams: QueryFilter = new Map();
private readonly dynamicParams: DynamicParamsMap = new DynamicParamsMap(); private readonly dynamicParams: DynamicParamsMap = new DynamicParamsMap();
@ -31,6 +31,16 @@ export class DynamicTomSelect extends TomSelect {
// Glean the REST API endpoint URL from the <select> element // Glean the REST API endpoint URL from the <select> element
this.api_url = this.input.getAttribute('data-url') as string; this.api_url = this.input.getAttribute('data-url') as string;
// Set the null option (if any)
const nullOption = this.input.getAttribute('data-null-option');
if (nullOption) {
let valueField = user_settings.valueField || 'value';
let labelField = user_settings.labelField || 'text';
this.nullOption = {}
this.nullOption[valueField] = 'null';
this.nullOption[labelField] = nullOption;
}
// Populate static query parameters. // Populate static query parameters.
this.getStaticParams(); this.getStaticParams();
for (const [key, value] of this.staticParams.entries()) { for (const [key, value] of this.staticParams.entries()) {
@ -64,6 +74,11 @@ export class DynamicTomSelect extends TomSelect {
addClasses(self.wrapper, self.settings.loadingClass); addClasses(self.wrapper, self.settings.loadingClass);
self.loading++; self.loading++;
// Populate the null option (if any) if not searching
if (self.nullOption && !value) {
self.addOption(self.nullOption);
}
// Make the API request // Make the API request
fetch(url) fetch(url)
.then(response => response.json()) .then(response => response.json())