How to conditionally display TableTools buttons

2019-03-06 03:59发布

问题:

I'm using jQuery DataTables and TableTools extension to display buttons in table header. But is there an option to show button when some condition is met?

My table initialization code is shown below:

projectsTable = $('#projects_table').DataTable({
    "dom": '<"cleaner">lf<"cleaner">T<"cleaner"><"cleaner">rtip',
    "stateSave": true,        
    "data":tableData,
    "bSortCellsTop": true,
    "responsive": true,
    "autoWidth": false,
    "tableTools":{
        "aButtons": [
            {
                "sExtends": "text",
                "sButtonText": "New project",
                "fnClick": function (mButton, oConfig, oFlash){
                    addProjectDialog();
                }
            },{
                "sExtends": "text",
                "sButtonText": "Reset all filters",
                "fnClick": function (mButton, oConfig, oFlash){
                    resetAllFilters();
                }
            }
        ]
    }
});

I want to display "New project" button only if user has right permissions. Is it somehow possible?

回答1:

Since aButtons is an array, this could be solved as shown below:

var canUserCreateProjects = true;

// DataTables TableTools buttons options
var aButtonsData = [];

// If user can create projects
if(canUserCreateProjects){
   aButtonsData.push({
      "sExtends": "text",
      "sButtonText": "New project",
      "fnClick": function (mButton, oConfig, oFlash){
         addProjectDialog();
      }
   });
}

aButtonsData.push({
   "sExtends": "text",
   "sButtonText": "Reset all filters",
   "fnClick": function (mButton, oConfig, oFlash){
      resetAllFilters();
   }
});

// Initialize DataTable
var projectsTable = $('#projects_table').DataTable({
    "dom": '<"cleaner">lf<"cleaner">T<"cleaner"><"cleaner">rtip',
    "stateSave": true,        
    "data":tableData,
    "bSortCellsTop": true,
    "responsive": true,
    "autoWidth": false,
    "tableTools": {
        "aButtons": aButtonsData
   }
});