I am trying to rename a column in dataTables when exporting to excel.
The reason is cause I have added a select filter option on one of the header titles.
When I try to export it, the whole name shows like this:
CategoryBeautyChristmasDecorFood - BakeryFood - DeliFood - DrinksGardenGift Cards and StationaryGifts - Children - ClothingGifts - Children - ToysGifts - LadiesGifts - MenJeweleryPets
Instead of just saying: Category
Please help!
My code:
$(document).ready(function () {
$('#datatables').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
},
'columns': [ // see https://datatables.net/reference/option/columns.searchable
null,
null,
null,
null,
null,
{'searchable': false},
{'searchable': false}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'excelHtml5',
orientation: 'landscape',
exportOptions: {
columns: [0, 1, 2, 3],
customize: function ( xlsx ) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('c[r=A2] t', sheet).text( 'Custom text' );
}
/**format: {
//this isn't working....
header: function (data, columnIdx) {
return columnIdx + ': ' + data;
}
}*/
}
}
/**,{
extend: 'pdfHtml5',
orientation: 'landscape',
exportOptions: {
columns: [ 0, 1, 2, 3 ],
header: false
}
}*/
],
//add drop downs to columns
initComplete: function () {
this.api().columns([3]).every(function () {
var column = this;
var select = $('<select><option value="">Category</option></select>')
.appendTo($(column.header()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
var table = $('#datatables').DataTable();
});
I've looked everywhere and cant seem to find a solution.
I managed to figure out the customize placement was wrong.
$(document).ready(function () {
$('#datatables').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
},
'columns': [ // see https://datatables.net/reference /option/columns.searchable
null,
null,
null,
null,
null,
{'searchable': false},
{'searchable': false}
],
dom: 'lBfrtip',
buttons: [
{
extend: 'excelHtml5',
text: 'Excel Export',
customize: function (xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('c[r=D2] t', sheet).text('Category');
},
exportOptions: {
columns: [0, 1, 2, 3],
modifier: {
page: 'current',
}
}
}
],
initComplete: function () {
this.api().columns([3]).every(function () {
var column = this;
var select = $('<select><option value="">Category</option></select>')
.appendTo($(column.header()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
var table = $('#datatables').DataTable();
});
I had the exact same issue. I managed to get it working using the the header formatting function inside the exportOptions object instead of the customize function. Assuming that the header that needs to be modified is the first one i.e the header index is 0, you could script your header function like this to make it work.
...
exportOptions: {
format: {
header: function ( data, columnIdx ) {
return columnIdx === 0 ? "Category" : data;
}
}
},
...
Reference: https://datatables.net/extensions/buttons/examples/html5/outputFormat-function
Related
I am using Select2 JS and Datatables JS. The data is in JSON format. The data for one value should display as Animal & Veterinary. In JSON it appears as Animal \u0026amp; Veterinary. The Select2 filter displays it as Animal & Veterinary. How can I add a function to the JS below that will decode the Unicode? Below is a function that can work but I dont know how to add it to the JS below.
var title = 'Animal & Veterinary';
function stringToSlug (title) {
return title.toLowerCase().trim()
.replace(/&/g, 'and')
}
Below is the script. This is where I would like to pass the function into the filter. "select2config"
jQuery( document ).ready( function($) {
'use strict';
// Check condition first if the table class exists then run this init.
if ($('.lcds-datatable--advisory-committee-materials').length > 0) {
let pageClass = function () {
let el = $( 'ul.pagination' ).addClass('pagination-sm');
}
// define order of table's control element
let domStyling = "<'row'<'col-sm-12'lB>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>";
var otable9 = $('table.lcds-datatable--advisory-committee-materials').DataTable( {
// Sort of first date column descending.
order: [[0, 'desc']],
deferRender: true,
deferLoading: 50,
dom: domStyling,
ajax: {
"url": "/datatables-json/advisory-committee-materials-json",
//"url": "/sites/default/files/actest1.json",
"dataSrc": ""
},
processing: true,
columns: [
{ "data": "field_publish_date" }, // publish_date 0
{ "data": "title" }, // node title summary 1
{ "data": "field_site_structure" } // site_structure Committee/Topic 2
],
columnDefs: [
{
"type": "date",
"targets": [ 0 ]
}
],
pageLength: 10,
searching: true,
autoWidth: false,
responsive: true,
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
buttons: [
{
extend: 'excel',
text: 'Export Excel',
exportOptions: {
columns: [ 0, 1, 2 ]
}
}
],
initComplete: pageClass,
drawCallback: pageClass
}); // end datatable
// config and initialize filters
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
}
let search = $( '#lcds-datatable-filter--search' ).lcdsTableFilter({
table: otable9,
type: 'search'
});
let clear = $( '#lcds-datatable-filter--clear' ).lcdsTableFilter({
table: otable9,
type: 'clear'
});
// wait for ajax call to complete to load column data load
$('table.lcds-datatable--advisory-committee-materials').on( 'init.dt', function() {
let committee = $( '#lcds-datatable-filter--committee-topic' ).lcdsTableFilter({
column: 2,
table: otable9,
select2Options: select2config,
type: 'select',
dataType: 'datatable'
});
})
}}); // end ready function and condition if the table class exists.
I was able to pass in a function to alter the output of JSON so now the filter displays “Animal & Veterinary” not “Animal & Veterinary” By adding this below. The filter now displays Animal & Veterinary but selecting this in the filter does not match the value in the datatable?
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
escapeMarkup: function (text) { return text; }
}
This question might have been answered somewhere but I can't get it right yet. I have a data table that I'm exporting to Excel but my problem is the field 'Account Number' has a string like "800953". When I export to excel it's displaying "800,953".
My JS code below seems to be missing something. I had tried to put a dot in front of string then replace it with blank. The bit where it's supposed to pick the first 4 columns is working fine.
"use strict";
$(document).ready(function () {
$('.export-table').DataTable({
fixedHeader: {
header: true
},
dom: 'Bflit',
lengthMenu: [
[100, -1],
['100 rows', 'Show All']
],
buttons: [
{
extend: 'excel',
exportOptions: {
columns: [1, 2, 3, 4],
exportOptions: {
format: {
body: function (data, row, column, node) {
return data.replace(/\./g, ' ');
}
}
}
}
}
]
});
$('.data-table').DataTable({
"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]]
});
$('#datable_2').DataTable({ "lengthChange": false });
});
I got solution to my question after going through this thread.
"use strict";
$(document).ready(function () {
$('.export-table').DataTable({
fixedHeader: {
header: true
},
dom: 'Bflit',// 'lBfrtip',// 'Bfrtip',
lengthMenu: [
[100, -1],
['100 rows', 'Show All']
],
buttons: [
{
extend: 'excelHtml5',
customize: function (xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('row c[r^="C"]', sheet).attr('s', '50'); //"C" is Account number column
}
}
]
});
$('.data-table').DataTable({
"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]]
});
$('#datable_2').DataTable({ "lengthChange": false });
});
I'm trying to hide a button. If it was on the html i would simply do
<security:authorize access="hasAuthority('Administrator')">
//html button code
</security:authorize>
but my delete button is being generated from datatable.
var table = $('#dataTable').DataTable({
language: {
searchPlaceholder: "Search...",
emptyTable: "There are no available flows."
},
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
},
{type: "date-euro", targets: 7},
{type: "date-euro", targets: 8}
],
order: [[1, 'desc']],
select: {
style: 'multi',
selector: 'td:first-child'
},
lengthChange: false,
dom: 'Bfrtip',
buttons: [
{
text: '<span class="fa fa-plus"></span> Create',
className: 'btn-primary-outline',
action: function () {
location.href = "create-flow";
}
},
{
text: '<span class="fa fa-trash"></span> Delete',
className: 'btn-danger-outline',
action: function () {
console.log($('#hasAuthority').val());
var selectedRows = table.rows({selected: true});
if (selectedRows.nodes().length > 0) {
//Get names
var data = selectedRows.data();
var names = [];
$.each(data, function (index, value) {
names.push(value[2]);
});
//Remove them
$.ajax({
url: '/flow/delete?names=' + names,
type: 'delete',
success: function () {
//reload page
location.reload();
}
});
//de-select selected rows
table.rows('.selected').deselect();
}
}
}
]
});
I'm trying to give a value to a input if user is admin or not but I'm getting undefined
<security:authorize access="hasAuthority('Administrator')" var="hasAuthority"></security:authorize>
<input type="hidden" id="hasAuthority" value="${hasAuthority}">
But then how do I corporate the if(hasAuthority) only on the delete button? The syntax doesn't match.
I have a table that I'm saving as a pdfHtml5 in datatable. I'm trying to make the table full width but I have been unsuccessful. How can I make my table 100% width using styles for my pdfHtml5?
dom: 'Bfrtip',
buttons: [
{
extend: 'collection',
text: '<div class="image"><img src="/Asset/Image/Capture.jpg" alt="" /></div>',
autoClose: true,
buttons: [{
extend: 'pdfHtml5', text: 'Download PDF Document', className: 'pdfdoc', title: podTitle, message: pod.data.pod_description_text + "\n" + "\n" + printDate, customize: function (doc) {
doc.defaultStyle.alignment = 'left';
doc.styles.tableHeader.alignment = 'left';
doc.styles.message = {
alignment: 'center'
}
doc.styles.table = {
alignment: 'center',
width: '100%',
}
/*doc.content[1].table.widths = Array(doc.content[1].table.body[0].length + 1).join('*').split('');*/
doc.pageMargins = [ 80, 20, 80, 20 ];
}
}, { extend: 'excel', text: 'Download Excel Document', className: 'exceldoc' },
]
}
]
});
By further extending pdfHtml5, you can instruct the pdfmake library, used by the Buttons extension, to use 100% width. The DataTables forum has a post with the required code:
var tbl = $('.dTable');
var settings={};
settings.buttons = [
{
extend:'pdfHtml5',
text:'Export PDF',
orientation:'landscape',
customize : function(doc){
var colCount = new Array();
$(tbl).find('tbody tr:first-child td').each(function(){
if($(this).attr('colspan')){
for(var i=1;i<=$(this).attr('colspan');$i++){
colCount.push('*');
}
}else{ colCount.push('*'); }
});
doc.content[1].table.widths = colCount;
}
}
];
$('.dTable').dataTable(settings);
Note that if you just copy the customize portion of the code above, you must replace tbl by "#myTable" or something similar.
See also the related GitHub ticket, including another implementation (which may or may not be out-of-date).
I use this and works for me. Good luck.
{
extend: 'pdfHtml5',
charset: 'utf-8',
title:tableOptions.title.toUpperCase(),
orientation: 'landscape',
text: '<i class="fas fa-file-pdf"></i> PDF',
exportOptions: {
columns: [1,2,3,4]
},
customize: function(doc) {
doc.content.splice( 0, 0, {
margin: [ 7, 0, 0, -45 ],
width: 85,
height: 55,
alignment: 'right',
image: 'base64...'
});
let downloadDate=`${moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('DD-MM-YYYY')}`;
let downloadTime=`${moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')}`.slice(11,16);
doc.content.splice( 2, 0, {
alignment: 'left',
fontSize:12,
margin: [ 0, 0, -10, 20 ],
color:"#003d66",
text:`${downloadDate} / ${downloadTime} Hrs`
});
doc.defaultStyle.alignment = 'center';
doc.defaultStyle.color = '#666';
doc.styles.title.color="#00c4cc";
doc.styles.title.alignment="left";
doc.styles.title.fontSize=14;
if(doc.content[3].table.body[0]){
let columns=doc.content[3].table.body[0].length;
let widths=[];
for (let i = 0; i < columns; i++) {
widths.push(`${99/columns}%`)
}
doc.content[3].table.widths = widths;
}
doc.styles.tableHeader.fontSize=12;
doc.styles.tableHeader.fillColor="#003d66";
doc.styles.tableBodyOdd.margin =[5, 5, 5, 5];
doc.styles.tableBodyEven.margin = [5, 5, 5, 5];
}
},
I try to add a filter after clicking on a button. For me, it won't work and I don't know why. Maybe I have an error in my code or is misunderstood something?
As result, I get an empty table.
In my console will be the error "TypeError: table.ext is undefined"
jQuery:
var table = $('#ajax_table1').DataTable( {
"processing": true,
"serverSide": true,
"ajax": $.fn.dataTable.pipeline( {
url: 'data_kontakte.php',
pages: 5 // number of pages to cache
} ),
"columnDefs": [
{
"targets": 0,
"data": 'type'
},
{
"targets": 1,
"data": 1
},
{
"targets": 2,
"data": 3
},
{
"targets": 3,
"data": 4
},
{
"targets": 4,
"data": 5
},
{
"targets": 5,
"data": 'funcs'
}
],
"drawCallback": function( settings ) {
$('.tooltips').tooltip();
//Confirmbox
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
});
//End Confirmbox
},
"language": {
url: '../lang/<?php echo $_GET['lang'].'/'.$_GET['lang']; ?>.json'
},
// setup buttons extentension: http://datatables.net/extensions/buttons/
buttons: [
{ extend: 'print', className: 'btn dark btn-outline' },
{ extend: 'pdf', className: 'btn green btn-outline' },
{ extend: 'csv', className: 'btn purple btn-outline' }
],
"lengthMenu": [
[5, 10, 15, 20, -1],
[5, 10, 15, 20, "All"] // change per page values here
],
//responsive: true,
"bFilter": true,
// set the initial value
"pageLength": 10,
//Layout
"dom": "<'pull-left'f><'pull-right' B>r<'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>><'row'<'col-md-5 col-sm-12'l><'col-md-7 col-sm-12'>>",
} );
//HERE IS THE FILTER_FUNCTION
$(document).on('click', '.related_contacts', function (event) {
table.ext.search.push(
function( settings, data, dataIndex ) {
var min = parseInt( this.value , 10 );
var max = parseInt( this.value , 10 );
var resdata = parseFloat( data[1] ) || 0; // use data for the datatable column
if ( ( isNaN( min ) && isNaN( max ) ) ||
( isNaN( min ) && resdata <= max ) ||
( min <= resdata && isNaN( max ) ) ||
( min <= resdata && resdatae <= max ) )
{
return true;
}
return false;
}
).draw();
});