Sunday, 26 June 2016

Customize context menu in handsontable

Using handsontable we can create excel like grid and it allows to customize a lot. Handsontable has a default context menu but it allows developers to customize. Let us check how we can create a simple handsontable with default context menu.

View


<div id="sample"></div>

JS


var data = [
 ["", "India", "US", "China", "Russia"],
 ["2016", 10, 11, 12, 13],
 ["2017", 20, 11, 14, 13],
 ["2018", 30, 15, 12, 13]
];

var container = document.getElementById('sample');
var hot = new Handsontable(container, {
 data: data,
 rowHeaders: true,
 colHeaders: true,
 dropdownMenu: true,
 contextMenu : true
});


If you don't want context menu simply don't add it or set it as false.

Customize context menu

Let us check with asn example how we can customize context menu.


var data = [
 ["", "India", "US", "China", "Russia"],
 ["2016", 10, 11, 12, 13],
 ["2017", 20, 11, 14, 13],
 ["2018", 30, 15, 12, 13]
];

var container = document.getElementById('sample');
var hot = new Handsontable(container, {
 data: data,
 rowHeaders: true,
 colHeaders: true,
 dropdownMenu: true,
 contextMenu : {
  callback: function(key, options) {
 if (key === 'custom_menu1') {
  console.log(hot.getSelected());
  //your function 
 }
 if (key === 'custom_menu1') {
  console.log(hot.getSelected());
  //your function
 }
 },
 items: {
 "custom_menu1": {
  "name": "My first context menu",
 },
 "custom_menu2": {
  "name": "My second context menu",
 }
}
};
});

Suppose if we need to hide some context menu option for any particular selection, we can do that very easily. See the below code which will hide the particular option if the condition is true.


"custom_menu1": {
 "name": "Disable this selection if the condition is true",
 disabled: function() {
 //hot.getSelected()// get selected row/column info and data
 if(your_condtion){
  return true
 }
}
}

And also you can override the custom context menu option as well. Below list contains the custom context menu option provided by handsontable and you can override these also using the above example.

1. row_above

2. row_below

3. hsep1

4. col_left

5. col_right

6. hsep2

7. remove_row

8. remove_col

9. hsep3

10. undo

11. redo

12. make_read_only

13. alignment

No comments :

Post a Comment