How to conditionally display TableTools buttons

1.7k views Asked by At

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

There are 1 answers

0
Gyrocode.com On BEST ANSWER

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
   }
});