I have created a custom multiselect by extending Autocomplete editor, but it resets everytime I open the editor again.
// eslint-disable-next-line no-undef
export default class MultiSelectAutocompleteEditor extends Handsontable.editors.AutocompleteEditor {
constructor(hotInstance) {
super(hotInstance);
this.selectedValues = [];
}
prepare(row, col, prop, td, originalValue, cellProperties) {
super.prepare(row, col, prop, td, originalValue, cellProperties);
this.TD = td;
this.selectedValues = originalValue || [];
}
open() {
super.open();
if (this.TD) {
this.htEditor.updateSettings({
afterRenderer: (TD, row, col, prop, value) => {
const isSelected = this.selectedValues.includes(value);
const actionText = isSelected ? ’ (enter to deselect)’ : ’ (enter to select)’;
// eslint-disable-next-line unicorn/prefer-dom-node-text-content
TD.innerText = value + actionText;
},
beforeOnCellMouseDown: (event, coords, _TD) => {
// Handle mouse click selection/deselection
const value = this.htEditor.getDataAtRow(coords.row)[0];
this.toggleSelection(value);
this.htEditor.render(); // Refresh dropdown to reflect changes
event.stopImmediatePropagation(); // Prevent closing on click
event.preventDefault();
},
});
}
}
close() {
super.close();
}
getValue() {
// Return selected values as an array
return this.selectedValues;
}
setValue(value) {
// Only fix: properly initialize selectedValues from the cell data
this.selectedValues = Array.isArray(value) ? […value] : []; // Treat as array or empty if not
}
onBeforeKeyDown(event) {
// eslint-disable-next-line no-undef
const isEnter = Handsontable.helper.KEY_CODES.ENTER === event.keyCode;
if (isEnter) {
const selectedItem = this.htEditor.getDataAtRow(this.htEditor.getSelected()[0]);
if (selectedItem) {
const value = selectedItem[0];
this.toggleSelection(value);
this.htEditor.render(); // Refresh dropdown to reflect changes
}
// Prevent default behavior so that the dropdown doesn't close automatically
event.stopImmediatePropagation();
event.preventDefault();
}
super.onBeforeKeyDown(event); // Ensure we keep default key handling behavior for other keys
}
toggleSelection(value) {
const valueIndex = this.selectedValues.indexOf(value);
if (valueIndex === -1) {
// Add to selected values if not already selected
this.selectedValues.push(value);
}
else {
// Remove from selected values if already selected
this.selectedValues.splice(valueIndex, 1);
}
}
}
I know this is not the right place to paste this. I’m not able to make a JS fiddle out of it at the moment for some reason. Can you please help me in getting this corrected? I have already sent my license ID to support@handsontable.com
I just need the autocomplete editor to behave as multiselect i.e when options are selected each options gets pushed to an array of values and dropdown shows enter to select/deselect beside the options based on the data that is selected.
I already have a multi select renderer which joins these array values with ", " and shows it on the cell