Jquery Customize Datatable exportoptions - javascript

In my datatable I have some columns with data like this: 'XXXX unit'.
When I export it I want to remove the unit part.
What is the rule I should put here?
exportOptions: {
columns: "thead th:not(.noExport)"
}
Thanks

The following function will remove " unit" from the end of every cell in column 2 (offset index 1) in the body of a table:
exportOptions: {
format: {
body: function ( data, row, column, node ) {
return column === 1 ? data.replace( / unit/g, '' ) : data;
}
}
}
This example uses replace() but there are other ways, of course.
In my case, here is how I placed the above option in my buttons section:
buttons: [
$.extend (
true,
{},
{ exportOptions: {
format: {
body: function ( data, row, column, node ) {
return column === 1 ? data.replace( / unit/g, '' ) : data;
}
}
} },
{ extend: 'excel' }
)
]
There is an example here which also shows how to extract the exportOptions into re-usable code, if you want to apply it to multiple buttons.

Related

Column order doesn't change in DataTables plugin

I wanted to reverse column on export data from DataTables. I look for method to do it and finally ended up with this way:
$(document).ready(function(){
var arrayCol = new Array();
var table = $('#example').DataTable({
dom: 'Bfrtip',
initComplete:function ( ) {
var len = this.api().columns().count();
var array = Array.from(Array(len).keys())
arrayCol = array.reverse();
},
buttons: [
{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible:not(.not-export-col)',
orthogonal: 'export'
}
},
{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'A4',
exportOptions: {
columns: arrayCol, // this doesn't work
//columns:[5,4,3,2,1,0], //this work
orthogonal: 'export'
}
}
]
});
});
The var arrayCol when debugging has values but when exporting to PDF the PDF doesn't have any columns.
Maybe it doesn't assign to columns or something like that.
I think the simplest way is to reverse each individual row array, as you are exporting the data. You can use exportOptions.rows to do this.
You also need to reverse the headers, which can be done using exportOptions.format.heeader. In this case, you only get access to one header field at a time, so there is a bit more work needed to build a reversed array of header values and then access each index location in that array:
$(document).ready(function() {
var table = $('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
{
extend: 'pdf',
text: 'To PDF',
exportOptions: {
rows: function ( idx, data, node ) {
return data.reverse();
},
format: {
header: function ( data, idx, node ) {
var headers = $('#example').DataTable().table().header();
var reversedHeaders = headers.innerText.split('\t').reverse();
return reversedHeaders[idx];
}
}
}
}
]
} );
} );
References:
export options
row selectors - function

how to destroy table and reinitialize same table with new updated data using Datatables Jquery plugin

I am using Datatables plugin and dynmically populating the table with the data returned from server. on different table draws the returned data has variable no of columns. On each table intilization the code is checking if there has been previous initializations and removes it before creating a new table with dynamic data, using this code:
if ( $.fn.dataTable.isDataTable( '#contracts_forecast' ) ) {
$('#contracts_forecast').DataTable().clear();
$('#contracts_forecast').DataTable().destroy();
$('#contracts_forecast tbody').empty();
$('#contracts_forecast thead').empty();
}
On the serverside I am manually editing the data and updating the database. When the database is updated with new data , I want to refresh the table so the change is reflected in the table. In order to do that I am using an POST SUBMIT event, which is triggered after the data is submitted to server and then call the function getDT(filter_product_code, filter_product_name) to update the table with new data
PROBLEM:
When the post submit event is triggered , it recalls the function getDT(filter_product_code, filter_product_name); and change is reflected. BUT THE NEW TABLE with UPDATED IS ADDED TO CURRENT TABLE WITHOUT THE OLD TABLE BEING DESTROYED Which leaves me with two same tables on screen
p.s I am assuming every time getDT() function is called it should check for if table is initialized and destroy it before creating a new one using the same
$(document).ready(function() {
$('#filter').click(function(){
var filter_product_code = $('#filter_product_code').val();
var filter_product_name = $('#filter_product_name').val();
if(filter_product_code == '' || filter_product_name == '')
{
alert('Select Both filter option');
}
var columns = [];
getDT(filter_product_code, filter_product_name);
function getDT(filter_product_code, filter_product_name) {
$.ajax({
serverSide: true,
type:'POST',
url: "/XXX/_fetch.php",
data: {filter_product_code: JSON.stringify(filter_product_code),
filter_product_name: JSON.stringify(filter_product_name)},
success: function (data) {
data = JSON.parse(data);
columnNames = Object.keys(data.data[0]);
for (var i in columnNames) {
columns.push({data: columnNames[i],
title: capitalizeFirstLetter(columnNames[i])});
}
if ( $.fn.dataTable.isDataTable( '#contracts_forecast' ) ) {
$('#contracts_forecast').DataTable().clear();
$('#contracts_forecast').DataTable().destroy();
$('#contracts_forecast tbody').empty();
$('#contracts_forecast thead').empty();
}
table = $('#contracts_forecast').DataTable({
data: data.data,
columns: columns,
dom: "Bfrtip",
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
],
"columnDefs": [
{
"targets": [0],
"visible": false,
"searchable": false
},
{ className: "tablecolumns", targets: "_all" },
]
} );
$('#contracts_forecast').on( 'click', 'tbody td:not(:first-child)', function (e) {
editor.inline( this );
} );
}
});
editor.on( 'postSubmit', function ( e, json, data, action, xhr ) {
getDT(filter_product_code, filter_product_name);
});
}
});
} );
I was doing a mistake by declaring the column variable outside function. Each time the function was called it was adding to already existing columns. So just needed to define column variable inside function.
getDT(filter_product_code, filter_product_name);
function getDT(filter_product_code, filter_product_name) {
var columns = [];
$.ajax({
serverSide: true,
// paging: true,
// retrieve:true,
type:'POST',

Is there a way to use NumberFormat() formatter (Google Charts) in vue-google-charts vue.js wrapper

I have been tasked with formatting some columns in charts using vue-google-charts, a vue.js wrapper for Google Charts and I am not sure that 'NumberFormat()' is even supported in vue-google-charts.
First, if somebody knows if it is or isn't, I would like to know so I don't waste much time pursuing something that isn't possible. But if it is, I sure would love an example of how to do it.
What we are doing is returning our chart data from the database and passing it into this vue.js wrapper. We are creating several charts but there are columns that have commas in them we want to remove.
Please review the existing code. I am trying to implement this using #ready as documented in the docs for vue-google-charts.
vue-google-charts docs -> https://www.npmjs.com/package/vue-google-charts
Here is our existing code with a little framework of the onChartReady method already in place.
<GChart
v-if="chart.data"
id="gchart"
:key="index"
:options="{
pieSliceText: chart.dropDownPie,
allowHtml: true
}"
:type="chart.ChartType"
:data="filtered(chart.data, chart.query, chart.query_type)"
:class="[
{'pieChart': chart.ChartType == 'PieChart'},
{'tableChart': chart.ChartType == 'Table'}
]"
#ready = "onChartReady"
/>
And then ...
<script>
import { GChart } from 'vue-google-charts';
import fuzzy from 'fuzzy';
import 'vue-awesome/icons';
import Icon from 'vue-awesome/components/Icon';
export default {
components: {
GChart,
Icon
},
props: {
},
data() {
return {
charts: window.template_data,
selected: 'null',
selects: [],
chartToSearch: false,
directDownloads: {
'Inactive Phones' : {
'slug' : 'phones_by_status',
'search_by' : 2,
'search' : '/Inactive/'
},
'Active Phones' : {
'slug' : 'phones_by_status',
'search_by' : 2,
'search' : '/Active/'
},
}
}
},
created(){
for (let i in this.charts){
if( !this.charts[i].slug ) continue;
$.post(ajaxurl, {
action: 'insights_' + this.charts[i].slug,
}, (res) => {
console.log(res.data);
if (res.success) {
this.$set(this.charts[i], 'data', res.data);
}
});
}
// console.log(this.charts);
},
methods: {
onChartReady(chart,google) {
let formatter = new.target.visualization.NumberFormat({
pattern: '0'
});
formatter.format(data, 0);
chart.draw(data)
},
toggleChart(chart) {
jQuery.post(ajaxurl, {
'action': 'update_insight_chart_type',
'chartType': chart.ChartType,
'chartSlug': chart.slug
}, (res) => {
chart.ChartType = res.data
})
},
csvHREF(chart) {
return window.location.href + '&rr_download_csv=' + chart.slug + '&rr_download_csv_search_by=' + chart.query_type + '&rr_download_csv_search=' + chart.query.trim()
},
filtered(data, query, column) {
query = query.trim();
if (query){
let localData = JSON.parse(JSON.stringify(data));
let column_Headers = localData.shift();
localData = localData.filter((row)=>{
if( query.endsWith('/') && query.startsWith('/') ){
return new RegExp(query.replace(/\//g, '')).test(String(row[column]));
}
return String(row[column]).toLowerCase().indexOf(query.toLowerCase()) > -1;
});
localData.unshift(column_Headers);
return localData;
}
return data;
},
filterIcon(chart) {
chart.searchVisible = !chart.searchVisible;
chart.query = "";
setTimeout(()=>{
document.querySelector(`#chart-${chart.slug} .insightSearch`).focus();
}, 1);
}
}
}
document.getElementsByClassName('google-visualization-table')
If anybody can help in ANY way, I am all ears.
Thanks!
not familiar with vue or the wrapper,
but in google charts, you can use object notation in your data,
to provide the formatted values.
all chart types will display the formatted values by default.
google's formatters just simply do this for you.
so, in your data, replace your number values with objects,
where v: is the value and f: is the formatted value...
{v: 2000, f: '$2,000.00'}
see following working snippet...
google.charts.load('current', {
packages: ['table']
}).then(function () {
var chartData = [
['col 0', 'col 1'],
['test', {v: 2000, f: '$2,000.00'}],
];
var dataTable = google.visualization.arrayToDataTable(chartData);
var table = new google.visualization.Table(document.getElementById('chart_div'));
table.draw(dataTable);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Datatables change Export format

I can change values inside a column on Excel export with this code.
var buttonExp = {
exportOptions: {
format: {
body: function (data, column, row){
return column === 4 ?
data.replace( 'test', 'REPLACED' ) :
data;
}
}
}
};
var table = $('#myTable').DataTable({
dom: 'lfBrtip',
buttons: [
$.extend(true, {}, buttonExp, {
extend: 'excelHtml5',
text: 'Export xls All',
exportOptions: {
modifier: {
page: 'current'
}
}
How can i change the Excel export format of a Column from this:
To this:
The only option i could find is changing the export from xlsx to csv.
Exporting in csv gives the desired output.

In Tablesorter, setting different values to the dropdown options of a column filter

I'm using Tablesorter to display a table and I have a column with a dropdown filter with several options. Something like this:
widgetOptions : {
filter_functions: {
4: {
users_all : function() {},
users_collaborators : function() {},
users_clients : function() {}
}
}
}
All those three values (users_all, users_collaborators and users_clients) are variables but they're being displayed as strings.
Is there any way to display the variables' content?
UPDATE 1
What I'm trying to do is to display the options in one language or another (nothing to do with the table).
I've tried changing the select options through filter_selectSource like this:
widgetOptions: {
filter_selectSource: {
4 : [ 'Client', 'Collaborator' ]
},
filter_functions: {
4 : true
}
}
But it throws an error (Cannot read property 'format' of undefined) on jquery.tablesorter.widgets.js:1464
I'm populating the table through ajaxProcessing and I'm picking this filter just like any other:
ajaxUrl: '/users/table_users.php?page={page}&size={size}&{sortList:sort}&{filterList:filter}'
I tried setting up your demo myself and had no problem at all.
ONCE RESOLVED IT LOOKS LIKE:
widgetOptions : {
filter_functions: {
4: true
},
filter_selectSource: {
4 : [ user_all, user_collaborators, user_clients ]
}
}
And I've added the class filter-select-nosort to the header of that column in the table.
What exactly are you trying to do with the filter select?
You can change the select options using the filter_selectSource option (demo)
$(function () {
$('table').tablesorter({
theme: 'blue',
widgets: ['zebra', 'filter'],
widgetOptions: {
filter_selectSource: {
1 : [ 'Client', 'Collaborator' ]
}
}
});
});

Categories

Resources