Remove select options from datatable header in pdf export - datatable

I have included select element in header of datatable. Now all the options append and show in header when I export to pdf. I do not want to show these values in header.
<script>
$(document).ready(function() {
$('#colSearch').DataTable( {
dom: 'Bfrtip',
buttons: [
{
extend: 'excel',
exportOptions: {
columns: [ 0, 1, 2, 3, 4, 5, 6 ]
}
},
{
extend: 'pdf',
exportOptions: {
columns: [ 0, 1, 2, 3, 4, 5, 6 ],
},
],
initComplete: function () {
this.api().columns([0,1,2,3,4,5,6]).every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.header()))
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
});
$( select ).click( function(e) {
e.stopPropagation();
});
column.data().unique().sort().each( function ( d, j ) {
var val = $('<div/>').html(d).text();
select.append( '<option value="' + val + '">' + val + '</option>' );
});
});
},
});
});
</script>
This provided solution removes all of the header.
https://stackoverflow.com/a/54803204/9660462

You can add a format.header option to your existing exportOptions:
exportOptions: {
columns: [ 0, 1, 2, 3, 4, 5, 6 ],
format: {
header: function ( data ) {
var n = data.indexOf("<select>");
if (n > -1) {
return data.substring(0, n);
} else {
return data;
}
}
}
}
The above code assumes your DataTable contains HTML in its headings which looks similar to the following:
<th class="sorting">
Office
<select>
<option value=""></option><option value="Edinburgh">Edinburgh</option><option value="London">London</option><option value="New York">New York</option><option value="San Francisco">San Francisco</option><option value="Singapore">Singapore</option><option value="Sydney">Sydney</option><option value="Tokyo">Tokyo</option>
</select>
</th>
This causes the heading to contain the following text, which is all the inner HTML from the th element:
Office<select><option value=""></option><optionvalue="Edinburgh">Edinburgh</option><option value="London">London</option><option value="New York">New York</option><option value="San Francisco">San Francisco</option><option value="Singapore">Singapore</option><option value="Sydney">Sydney</option><option value="Tokyo">Tokyo</option></select>
To exclude the drop-down values (in my case, the office locations), and to only show the heading (in my case, the word "Office"), my code checks for the location of the first <select> substring in the extracted text. It then ignores everything from that point onwards.
The format.header option is documented in this page.

Related

Feeding highchart with x and y values from ajax

I'm trying to feed my highchart from a database using ajax. From my ajax request, I want to return both x and y values (the x value is like that: year-week, ie 2020-16; the y value is a random number). My chart remains blank, I have a silent error that I cannot figure out. I'm pretty sure it comes from the strucure of the data returned by ajax, but I can't seem to fix it on my own.
Here's my javascript:
var weekOptions = {
chart: {
renderTo: 'weekContainer',
type: 'column',
},
title: {
text: 'Last 52 weeks',
},
credits: {
enabled: false,
},
xAxis: {
lineWidth: .5,
tickWidth: 1,
tickLength: 10,
},
yAxis: {
title: {
text: 'Distance (miles)'
},
labels: {
formatter: function() {
return this.value;
},
},
allowDecimals: false,
gridLineWidth: 1,
},
tooltip: {
crosshairs: true,
split: true,
useHTML: true,
valueDecimals: 2,
valueSuffix: ' miles',
formatter: '',
},
plotOptions: {
spline: {
marker: {
symbol: "circle",
radius: 3,
}
}
},
lang: {
noData: "No Data. Make sure at least one activity type is selected."
},
noData: {
style: {
fontWeight: 'bold',
fontSize: '15px',
color: '#303030'
}
},
exporting: {
buttons: {
contextButton: {
menuItems: ['viewFullscreen']
}
},
},
series: [{}],
};
//get series from ajax filtered by activity types
$.ajax({
url: "weekGetSeries.php",
type: "POST",
data: {
activityType: activityTypeSelected,
dataToDisplay: dataToDisplay,
},
dataType: "JSON",
success: function (json) {
weekOptions.series = json;
var chart = new Highcharts.Chart(weekOptions);
}
});
And here my ajax php file:
<?php
require 'dbConnection.php';
$activityType = array(1,2,3,4,5);
$dataToDisplay = "distance";
$startingDate = date('Y-m-d', strtotime('-52 week', time()));
$firstWeek = strtotime($startingDate);
$conditionActivityType = ' WHERE startingTime >= "' . $startingDate . '" AND (type=' . implode(" OR type=",$activityType) . ')';
$dataSerie = array("name" => "Weekly Stats","data" => array());
for($i = 0; $i < 52; $i++){
$nextWeek = strtotime('+'.$i.' week', $firstWeek);
$dataSerie["data"][date("o",$nextWeek) . "-" . date("W",$nextWeek)] = 0;
}
$getActivities = $conn->query("SELECT * FROM activity" . $conditionActivityType . " ORDER BY startingTime ASC");
if ($getActivities->num_rows > 0) {
while($row = $getActivities->fetch_assoc()) {
$date = substr($row["startingTime"],0,10);
$date = strtotime($date);
$week = date("W",$date);
$category = date("Y-",$date).$week;
$distance = ($row["distance"]);
$movingTime = $row["movingTime"];
$elapsedTime = $row["elapsedTime"];
$totalElevationGain = ($row["totalElevationGain"])*3.28084;
switch ($dataToDisplay) {
//distance
case "distance":
$dataSerie["data"][$category] += $distance;
break;
//Moving Time
case "movingTime":
break;
//Elapsed Time
case "elapsedTime":
break;
//elevation gain
case "totalElevationGain":
break;
//number activities
case "activities":
break;
}
}
};
$data = array();
array_push($data,$dataSerie);
echo json_encode($data);
?>
My ajax returns this:
[{"name":"Weekly Stats","data":{"2019-17":13184.4,"2019-18":73560.2,"2019-19":36899.4,"2019-20":0,"2019-21":38691.3,"2019-22":165127.8,"2019-23":188163.2,"2019-24":12888.5,"2019-25":60011.3,"2019-26":32585.2,"2019-27":12952.8,"2019-28":7944.8,"2019-29":79258.3,"2019-30":60885.2,"2019-31":0,"2019-32":0,"2019-33":0,"2019-34":0,"2019-35":0,"2019-36":0,"2019-37":30974.6,"2019-38":7766.5,"2019-39":7685,"2019-40":21128.7,"2019-41":28996,"2019-42":46362.6,"2019-43":0,"2019-44":0,"2019-45":63694.8,"2019-46":81551.1,"2019-47":104595.9,"2019-48":18121.7,"2019-49":18691.6,"2019-50":37538,"2019-51":40671.8,"2019-52":22109.6,"2020-01":22079,"2020-02":22086.7,"2020-03":21933.2,"2020-04":30702.1,"2020-05":58259,"2020-06":38811.3,"2020-07":43754,"2020-08":45109.1,"2020-09":50870.1,"2020-10":62917.8,"2020-11":0,"2020-12":95912.5,"2020-13":20836.2,"2020-14":25293,"2020-15":110540.5,"2020-16":150804.9}}]
How do I structure my data so I can feed my chart?
In your case series.data needs to be an array of arrays or an array of objects. Now it is an object.
data: [
[0, 6],
[1, 2],
[2, 6]
]
Or:
data: [{
x: 1,
y: 9
}, {
x: 1,
y: 6
}]
Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4977/
API Reference: https://api.highcharts.com/highcharts/series.column.data

Datatables PDF export right to left

I've managed to make a new font and add it to the datatable, but when I generated the PDF the text was aligned from left to right which is the opposite of what I wants, is there any configurations that I could use to make is right to left.
Also I'm using server side processing, and multi-column filtering, and the PDF button only prints the current page, what is the configuration to make it print the whole filter result.
Thanks in advance
You need to use specific pdfmake configuration options to manipulate the exported PDF:
https://datatables.net/reference/button/pdfHtml5
This will make the text to align right, it won't make the text run from right-to-left, however:
buttons: [
{
extend: 'pdf',
customize: function ( doc ) {
doc.content[0].alignment = 'right';
}
}
]
hi here is my code for persian ltr to rtl this is a function that's can use in datatable to export as pdf :
function buttonForDatatable(columns, margins, prtrait = "portrait",title='',message='') {
return [
{
extend: 'copy',
text:"کپی",
exportOptions: {
columns: columns.reverse(),
},
}, {
extend: 'csv',
text:"سی اس وی",
exportOptions: {
columns: columns.reverse(),
},
}, {
extend: 'print',
text:"پرینت",
exportOptions: {
columns: columns.reverse(),
},
}, {
extend: 'excel',
text:"اکسل",
exportOptions: {
columns: columns,
},
} ,{
extend: 'pdfHtml5',
orientation: prtrait,
footer: true,
alignment: "center",
title: title,
messageTop:message,
text: "PDF",
exportOptions: {
alignment: "center",
orthogonal: "PDF",
columns: columns,
modifier: {order: 'index', page: 'current'}
},
customize: function (doc) {
doc.styles.message.alignment = "right";
doc.styles.tableBodyEven.alignment = "center";
doc.styles.tableBodyOdd.alignment = "center";
doc.styles.tableFooter.alignment = "center";
doc.styles.tableHeader.alignment = "center";
doc.content[0]['text'] = doc.content[0]['text'].split(' ').reverse().join(' ');
doc.content[1].margin = margins;
doc.content[2].margin = margins;
for (var i = 0; i < doc.content[2].table.body.length; i++) {
// console.log(doc.content[1].table.body[i].length);
for (var j = 0; j < doc.content[2].table.body[i].length; j++) {
doc.content[2].table.body[i][j]['text'] = doc.content[2].table.body[i][j]['text'].split(' ').reverse().join(' ');
}
}
}
}
];
}
and after that you are can use same as here :
table = $('#mydatatable').DataTable({
language: language,
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "all"]],
dom: 'Blfrtip',
buttons: buttonForDatatable([2, 3, 4], [0, 0, 0, 0]),
processing: true,
serverSide: true,
.....

Jquery Selected Rows Value

I have a datatable. I want to retrieve the ID values of the rows that are selected.
How can I do that.
My codes:
var DatatableRecordSelectionDemo = function () {
var demo = function () {
var url = '/Data/default.json';
$.getJSON(url, function (data) {
var datatable = $('.m_datatable').mDatatable({
data: {
type: "local",
source: data,
pageSize: 10,
saveState: {
cookie: true,
webstorage: true
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
// layout definition
layout: {
theme: 'default', // datatable theme
"class": '', // custom wrapper class
scroll: false, // enable/disable datatable scroll both horizontal and vertical when needed.
height: 550, // datatable's body's fixed height
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
// columns definition
columns: [{
field: "RecordID",
title: "#",
sortable: false, // disable sort for this column
width: 40,
textAlign: 'center',
selector: { class: 'm-checkbox--solid m-checkbox--brand' }
}, {
field: "OrderID",
title: "Numara",
// sortable: 'asc', // default sort
filterable: true, // disable or enable filtering
// basic templating support for column rendering,
template: '{{OrderID}} - {{ShipCountry}}'
}, {
field: "ShipName",
title: "Adı"
}, {
field: "Status",
title: "Durumu",
// callback function support for column rendering
template: function (row) {
var status = {
true: { 'title': 'Aktif', 'class': ' m-badge--success' },
false: { 'title': 'Pasif', 'class': ' m-badge--danger' }
};
return '<span class="m-badge ' + status[row.Status].class + ' m-badge--wide">' + status[row.Status].title + '</span>';
}
}, {
field: "Actions",
title: "İşlem",
width: 100,
sortable: false,
overflow: 'visible',
template: function (row) {
var tblName = String(row.ShipName).replace(/'/g, "\\'");
var tblid = String(row.RecordID);
return '\
<a href="#" onclick="Modalac('+ tblid + ',\'' + tblName + '\',' + row.Status + ')" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Düzenle">\
<i class="la la-edit"></i>\
</a>\
<a href="#" onclick="Sil('+ tblid + ',\'' + tblName + '\')" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill" title="Sil">\
<i class="la la-trash"></i>\
</a>\
';
}
}]
});
var query = datatable.getDataSourceQuery();
$('#m_form_search').on('keyup', function (e) {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.generalSearch = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(query.generalSearch);
$('#m_form_status').on('change', function () {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.Status = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(typeof query.Status !== 'undefined' ? query.Status : '');
$('#m_form_status').selectpicker();
// on checkbox checked event
$('.m_datatable').on('m-datatable--on-check', function (e, args) {
var count = datatable.setSelectedRecords().getSelectedRecords().length;
$('#m_datatable_selected_number').html(count);
if (count > 0) {
$('#m_datatable_group_action_form').collapse('show');
}
})
.on('m-datatable--on-uncheck m-datatable--on-layout-updated', function (e, args) {
var count = datatable.setSelectedRecords().getSelectedRecords().length;
$('#m_datatable_selected_number').html(count);
if (count === 0) {
$('#m_datatable_group_action_form').collapse('hide');
}
});
$('.m_datatable tbody').on('click', 'tr', function (){
var id = this.RecordID;
var index = $.inArray(id, selected);
if (index === -1)
{
selected.push(id);
} else
{
selected.splice(index, 1);
}
$(this).toggleClass('selected');
});
});
};
return {
// public functions
init: function () {
demo();
}
};
}();
var TopluIslem = function () {
var datatable = $('.m_datatable').mDatatable();
var dataArr = [];
$.each($(".m_datatable tr.selected"),function(){
dataArr.push($(this).find('td').eq(0).text());
});
console.log(dataArr);
alert(rowCount);
};
jQuery(document).ready(function () {
DatatableRecordSelectionDemo.init();
});
İşlem Yap
I solved the problem
var secilenler = [];
$('.m_datatable').on('m-datatable--on-check', function(e, args) {
secilenler.push(args.toString());
}).on('m-datatable--on-uncheck', function (e, args) {
var i = secilenler.indexOf(args.toString());
if(i !== -1) {
secilenler.splice(i, 1);
}
});

Sorting dataTables for date columns

I have a datatable but sorting on its date column treats the data as a text instead of a date. I'm trying to make it sort as a date instead but stuck on it.
I tried adding datetime sorting plugin but it didnt work, or I couldnt make it work.
Here's the complete script of the page
$(document).ready(function () {
$('.datetimeclass').datepicker({
format: "dd/mm/yyyy",
language: "tr"
});
var responsiveHelper_dt_basic = undefined;
var breakpointDefinition = {
laptop: 1366,
tablet: 1024,
phone: 480
};
$('#dt_basic').dataTable({
// Tabletools options:
// https://datatables.net/extensions/tabletools/button_options
"sDom": "<'dt-toolbar'<'col-sm-4 col-xs-4 hidden-xs'T>r>" +
"t" +
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i>>",
"oTableTools": {
"aButtons": [
"copy",
//"csv",
"xls",
{
"sExtends": "print",
"sMessage": "Generated by Derimod <i>(press Esc to close)</i>"
}
],
"sSwfPath": "/Scripts/plugin/datatables/swf/copy_csv_xls_pdf.swf",
"columnDefs": [
{ "type": "datetime", targets: 7 }
]
},
"autoWidth": true,
"preDrawCallback": function () {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_dt_basic) {
responsiveHelper_dt_basic = new ResponsiveDatatablesHelper($('#dt_basic'), breakpointDefinition);
}
},
"rowCallback": function (nRow) {
responsiveHelper_dt_basic.createExpandIcon(nRow);
},
"drawCallback": function (oSettings) {
responsiveHelper_dt_basic.respond();
}
, paging: false
// , "aLengthMenu": [[10, 50, 100, -1], [10, 50, 100, "All"]],
//"iDisplayLength": 10,
//,'sPaginationType': 'full_numbers'
});
});
How can I solve my problem?
EDIT: An example of my date format: 14.6.2017 11:49:47

Show image in datatables codeigniter

sorry for my bad english,
i want to show image in my table using datatables.
var t = $("#mytable").dataTable({
initComplete: function() {
var api = this.api();
$('#mytable_filter input')
.off('.DT')
.on('keyup.DT', function(e) {
if (e.keyCode == 13) {
api.search(this.value).draw();
}
});
},
oLanguage: {
sProcessing: "loading..."
},
processing: true,
serverSide: true,
ajax: {"url": "wisataadmincontroller/json", "type": "POST"},
columns: [
{
"data": "id_wisata",
"orderable": false
},{"data": "nama_wisata"},{"data": "alamat_wisata"},{"data": "no_telp"},{"data": "kategori"},{"data": "longitude"},{"data": "latitude"},{"data": "gambar","render": function(data, type, row) {
return '<img src="'+data+'"style="height:100px;width:100px;" />';
}},{"data": "like"},
{
"data" : "action",
"orderable": false,
"className" : "text-center"
}
],
order: [[0, 'desc']],
rowCallback: function(row, data, iDisplayIndex) {
var info = this.fnPagingInfo();
var page = info.iPage;
var length = info.iLength;
var index = page * length + (iDisplayIndex + 1);
$('td:eq(0)', row).html(index);
}
});
});
and the result :the images are empty
the images are empty because the image source only contains the images file name,
so how to use baseurl in datatables?
Just plug it in?
<img src="<?php echo base_url(); ?>'+data+'"style="height:100px;width:100px;" />

Resources