Skip to content

Instantly share code, notes, and snippets.

@davidthingsaker
Last active March 17, 2016 15:31
Show Gist options
  • Save davidthingsaker/10567e46aca2ebc4252a to your computer and use it in GitHub Desktop.
Save davidthingsaker/10567e46aca2ebc4252a to your computer and use it in GitHub Desktop.
Datatables class
function Datatable(table){
this.table = table;
this.dataKeys = $(this.table).data('columns');
this.buildDatatable();
}
Datatable.prototype.options = function(){
var options = {};
options.table = $(this.table).data('model');
options.scope = $(this.table).data('scope');
options.actions = $(this.table).data('actions');
options.parent = $(this.table).data('parent');
options.parentid = $(this.table).data('parentid');
options.relation = $(this.table).data('relation');
options.filters = $(this.table).data('filters');
options.columnsRaw = this.columnsArr(true);
if(options.relation == 'relatedBelongsMany'){
options.selected = $("input[name='related[" + options.table + "]']").val();
} else if(options.relation == 'relatedOne'){
options.selected = $("input#" + options.table).val();
}
return options;
}
Datatable.prototype.columnsArr = function(raw){
!raw ? false : true;
var columns = [];
var columnsRaw = [];
$.each(this.dataKeys, function(index, value){
columnsRaw.push({'data': value});
value = value.split(".");
if(parseInt(index, 10) || index == 0) {
if (value.length > 1) {
columns.push({'data': value[value.length - 1]});
} else {
columns.push({'data': value[0]});
}
} else {
columns.push({'data': index});
}
});
return raw ? columnsRaw : columns;
}
Datatable.prototype.buildEditBtn = function(){
// Create Edit button
var editBtn = $('<button>');
$(editBtn).text('Edit');
$(editBtn).addClass('btn btn-primary');
$(editBtn).attr('type', 'button')
var icon = $('<i>');
$(icon).addClass('fa fa-pencil');
$(editBtn).prepend(icon);
this.editBtn = editBtn;
}
Datatable.prototype.buildSaveBtn = function(){
// Create Save button
var saveBtn = $('<button>');
$(saveBtn).text('Save');
$(saveBtn).addClass('btn btn-success pull-right');
$(saveBtn).css({
'display': 'none',
'margin-left': 10
});
var icon = $('<i>');
$(icon).addClass('fa fa-save');
$(saveBtn).prepend(icon);
this.saveBtn = saveBtn;
}
Datatable.prototype.addBtnEvents = function(){
var that = this;
// Add Edit button event
$(this.editBtn).click(function(){
if(typeof that.selectAllCheckbox !== 'undefined'){
$(that.selectAllCheckbox).css('display', 'inline');
}
$(this).css('display', 'none');
$(that.icons).css('display', 'none');
$(that.inputs).css('display', 'inline');
$(that.saveBtn).css('display', 'inline');
});
// Add Save button Event
$(this.saveBtn).click(function(e){
e.preventDefault()
that.saveObjects();
if(typeof that.selectAllCheckbox !== 'undefined'){
$(that.selectAllCheckbox).css('display', 'none');
}
$(this).css('display', 'none');
$(that.inputs).css('display', 'none');
$(that.editBtn).css('display', 'inline');
$(that.icons).css('display', 'inline');
});
}
Datatable.prototype.saveObjects = function(){
var that = this;
var input = $(that.saveBtn).closest('.table-responsive').siblings('input[type=hidden]');
var method = $(input).data('method');
var id = $(input).data('id');
var model = $(input).data('model');
$.ajax({
url: '/' + model + '/' + id,
method: method,
data: input.serialize(),
dataType: 'json',
success: function(response){
console.log(response);
if(response.statuscode == 202 || response.statuscode == 200){
$(that.table).find('td:last-child').css({
'background-color': '#dff0d8'
});
setTimeout(function(){
$(that.table).find('td:last-child').css({
'background-color': '#fff'
});
}, 1000);
}
},
error: function(response){
console.log(response);
$(that.table).find('td:last-child').css({
'background-color': '#f2dede'
});
setTimeout(function(){
$(that.table).find('td:last-child').css({
'background-color': '#fff'
});
}, 1000);
},
beforeSend: function(){
$(that.saveBtn).prop('disabled', true);
},
complete: function(){
$(that.saveBtn).prop('disabled', false);
}
});
}
Datatable.prototype.addCheckboxEvents = function(){
var that = this;
$.each(this.inputs, function(index, el){
if(that.selectedVal.indexOf(parseInt($(el).val())) == -1){
$(el).prop('checked', false);
} else {
$(el).prop('checked', true);
}
});
$(this.inputs).change(function(e){
var input = $(this).data('input');
var id = $(this).val();
var selectedVal = JSON.parse($(that.selectedEl).val());
if($(this).is(':checked')){
var index = selectedVal.indexOf(parseInt(id));
if (index == -1) {
selectedVal.push(parseInt(id));
}
$(that.selectedEl).val(JSON.stringify(selectedVal));
$(this).siblings('.fa').removeClass('fa-times').addClass('fa-check');
} else {
$(that.selectAllCheckbox).prop('checked', false);
console.log('current value = ' + selectedVal);
var index = selectedVal.indexOf(parseInt(id));
console.log('id = ' + id + ' index = ' + index);
if (index > -1) {
selectedVal.splice(index, 1);
}
$(that.selectedEl).val(JSON.stringify(selectedVal));
$(this).siblings('.fa').removeClass('fa-check').addClass('fa-times');
}
});
$(this.selectAllCheckbox).change(function(e){
console.log('all changed');
if($(this).is(':checked')){
var warning = '<div class="alert alert-warning alert-dismissible" role="alert">'
+ '<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>'
+ 'Select all will select all objects, not just those shown here.'
+ '</div>';
$(this.table).closest('.dataTables_wrapper').prepend(warning);
var qs = '?table=' + that.options.table;
$.ajax({
url: '/backend/data/ids' + qs,
success: function(response){
console.log(JSON.stringify(response));
$(that.selectedEl).val(JSON.stringify(response));
$(that.inputs).prop('checked', true);
},
error: function(jqXHR){
console.log(jqXHR.responseText);
}
});
} else {
$(this.table).closest('.dataTables_wrapper').find('.alert-warning').remove();
$(that.selectedEl).val('[]');
that.selectedVal = [];
$(that.inputs).prop('checked', false);
}
});
}
Datatable.prototype.addInputEvents = function(){
var that = this;
if($(this.inputs).attr('type') == 'checkbox'){
this.addCheckboxEvents();
} else {
$(this.inputs).change(function(e){
var id = $(this).val();
$(that.selectedEl).val(id);
that.selectedVal = id;
$(this).siblings('.fa').removeClass('fa-times').addClass('fa-check');
$(this).closest('tr').siblings('tr').find('.fa-check').removeClass('fa-check').addClass('fa-times');
});
}
}
Datatable.prototype.makeEditable = function(){
this.icons = $(this.table).find('tbody tr td .fa');
if(this.options.relation == 'relatedBelongsMany'){
this.selectAllCheckbox = $(this.table).find('thead input[type=checkbox]');
this.inputs = $(this.table).find('tbody tr td input[type=checkbox]');
this.selectedEl = $("input[name='related[" + this.options.table + "]']");
this.selectedVal = JSON.parse($(this.selectedEl).val());
// Append buttons to the DOM
}else if(this.options.relation == 'relatedOne'){
this.inputs = $(this.table).find('tbody tr td input[type=radio]');
this.selectedEl = $("input#" + this.options.table);
this.selectedVal = $(this.selectedEl).val();
}
if(!this.noButtons){
this.buildEditBtn();
this.buildSaveBtn();
this.addBtnEvents();
}else {
$(this.selectAllCheckbox).css('display', 'inline');
$(this.icons).css('display', 'none');
$(this.inputs).css('display', 'inline');
}
this.addInputEvents();
$(this.table).siblings('.dt-toolbar-footer').find('.dataTables_paginate').prepend(this.saveBtn);
if($(this.table).find('.selectAllObjs button').length < 1){
$(this.table).find('.selectAllObjs').append(this.editBtn);
}
}
Datatable.prototype.buildDatatable = function(){
var that = this;
this.options = that.options();
var datatable = $(this.table).DataTable({
"sDom" : "<'dt-toolbar'<'col-sm-6 col-xs-12'><'col-xs-12 col-sm-6'l>>r" +
"t<'dt-toolbar-footer'<'col-sm-6 col-xs-12'i><'col-xs-12 col-sm-6'p>>",
"processing": true,
"serverSide": true,
"ordering" : false,
"ajax": {
"url": '/backend/data/' + location.search,
'data': that.options
},
"columns": that.columnsArr(),
"fnDrawCallback": function( oSettings ) {
that.noButtons = $(that.table).closest('.table-responsive').hasClass('no-buttons') ? true : false;
that.addDeleteFunctionality();
if(that.options.relation == 'relatedBelongsMany' || that.options.relation == 'relatedOne'){
that.makeEditable();
}
}
});
}
Datatable.prototype.addDeleteFunctionality = function(){
$('.btn.delete').click(function(e){
e.preventDefault();
var id = $(this).data('id');
var table = $(this).data('table');
var modal = $('#confirm-delete');
$(modal).find('#id-copy').text(id);
$(modal).find('input[name=id]').val(id);
$(modal).find('input[name=table]').val(table);
$(modal).modal('show');
});
}
$(document).ready(function(){
$.each($('.datatable'), function(index, el){
return new Datatable(el);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment