How to set up a key-value dropdown
HTML
<script src="https://handsontable.com/docs/scripts/fixer.js"></script>
<script src="https://cdn.jsdelivr.net/npm/handsontable@latest/dist/handsontable.full.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/handsontable@latest/dist/handsontable.full.min.css" />
<script src="https://handsontable.com/docs/scripts/fixer.js"></script>
<div id="example"></div>
Babel + JSX
import Handsontable from 'handsontable';
import 'handsontable/dist/handsontable.full.min.css';
/**
* The cell type adds supports for displaing the label value except the key in the key-value
* dropdown editor type.
*/
class KeyValueListEditor extends Handsontable.editors.HandsontableEditor {
prepare(row, col, prop, td, value, cellProperties) {
super.prepare(row, col, prop, td, value, cellProperties);
Object.assign(this.htOptions, {
data: this.cellProperties.source,
columns: [{
data: '_id',
},
{
data: 'label',
},
],
hiddenColumns: {
columns: [1],
},
colWidths: '150',
beforeValueRender(value, {
row,
instance
}) {
return instance.getDataAtRowProp(row, 'label')
}
});
if (cellProperties.keyValueListCells) {
this.htOptions.cells = cellProperties.keyValueListCells;
}
}
setValue(value) {
if (this.htEditor) {
const index = this.htEditor.getDataAtProp('_id').findIndex(id => id === value);
if (index !== -1) {
value = this.htEditor.getDataAtRowProp(index, 'label');
}
}
super.setValue(value);
}
getValue() {
const value = super.getValue();
if (this.htEditor) {
const labels = this.htEditor.getDataAtProp('label');
const row = labels.indexOf(value);
if (row !== -1) {
return this.htEditor.getDataAtRowProp(row, '_id');
}
}
return value;
}
}
const keyValueListValidator = function(value, callback) {
let valueToValidate = value;
if (valueToValidate === null || valueToValidate === void 0) {
valueToValidate = '';
}
if (this.allowEmpty && valueToValidate === '') {
callback(true);
} else {
callback(this.source.find(({
_id
}) => _id === value) ? true : false);
}
};
const keyValueListRenderer = function(hot, TD, row, col, prop, value, cellProperties) {
const item =...