Peet vd Westhuizen
Peet vd Westhuizen

Reputation: 403

Handsontable change a column source

Is it possible to change the source in a Handsontable instance when inside an event?

Below is my code:

var container2 = $('#example2');

var hot2 = new Handsontable(container2, {
    data: {},
    minRows: 5,
    colHeaders: ['Car', 'Year', 'Car Color'],
    columns: [
        {
            type: 'autocomplete',
            source: ['BMW', 'Chrysler', 'Nissan', 'Suzuki', 'Toyota', 'Volvo'],
            strict: true,
            allowInvalid: false
        }, ,
        {},
        {
            type: 'autocomplete',
            source: ['yellow', 'red', 'orange', 'green', 'blue', 'gray', 'black', 'white', 'purple', 'lime', 'olive', 'cyan'],
            strict: true,
            allowInvalid: false
        }]
});

Handsontable.hooks.add('afterChange', afterChangedCallback, hot2);

function afterChangedCallback(p) {
    console.log(p);
    if (p[0][1] == 0) {
        alert('This means the first column has changed, I now want to update the colors here');
    }
}

When a user selects a different car brand, I only want to populate the dropdown of "Car Color" with certain colors. Thus, not all car brands has the same colors.

EDIT

I updated the callback function to this based on the accepted answer:

function afterChanged(p) {
    console.log(p);
    if (p[0][1] == 0) {
        hot2.updateSettings({
            cells: function (row, col, prop) {
                if (row == p[0][0] && col == 2) {
                    var cellProperties = {};

                    cellProperties.source = ['red', 'yellow', 'blue'];

                    return cellProperties;
                }
            }
        });

    }
}

Upvotes: 3

Views: 2194

Answers (1)

ZekeDroid
ZekeDroid

Reputation: 7209

Yup, you can use the updateSettings method to change the source of an entire column or particular cell. You probably want per-cell so I would do:

hot.updateSettings({
    cells: newCellDefinitionFunction()
})

Of course this new definition is up to you to figure out. It could just be returning the same cellProperties each time but check on some global array for what sources to use for which cells.

Upvotes: 4

Related Questions