Datatables PDF export right to left - datatable

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,
.....

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

How to implement jqgrid multiselect toolbar

Currently free-jqgrid has feature that supports multiselect toolbar, same feature i want to create in jqgrid also.
http://www.ok-soft-gmbh.com/jqGrid/OK/MultiselectIn.htm
More recent code of usage multiselect with free jqGrid can be seen on the demo https://jsfiddle.net/OlegKi/ty4e68pm/16/. The most important parts of the demo I include below:
var dataInitMultiselect = function (elem, searchOptions) {
var $grid = $(this);
setTimeout(function() {
var $elem = $(elem),
id = elem.id,
inToolbar = searchOptions.mode === "filter",
options = {
selectedList: 2,
height: "auto",
checkAllText: "all",
uncheckAllText: "no",
noneSelectedText: "Any",
open: function() {
var $menu = $(".ui-multiselect-menu:visible");
$menu.width("auto");
$menu.css({
width: "auto",
height: "auto"
});
$menu.children("ul").css({
maxHeight: "300px",
overflow: "auto"
});
}
},
$options = $elem.find("option");
if ($options.length > 0 && $options[0].selected) {
$options[0].selected = false; // unselect the first selected option
}
if (inToolbar) {
options.minWidth = "auto";
}
$grid.triggerHandler("jqGridRefreshFilterValues");
$elem.multiselect(options);
// replace icons ui-icon-check, ui-icon-closethick, ui-icon-circle-close
// and ui-icon-triangle-1-s to font awesome icons
var $header = $elem.data("echMultiselect").header;
$header.find("span.ui-icon.ui-icon-check")
.removeClass("ui-icon ui-icon-check")
.addClass("fa fa-fw fa-check");
$header.find("span.ui-icon.ui-icon-closethick")
.removeClass("ui-icon ui-icon-closethick")
.addClass("fa fa-fw fa-times");
$header.find("span.ui-icon.ui-icon-circle-close")
.removeClass("ui-icon ui-icon-circle-close")
.addClass("fa fa-times-circle");
$elem.data("echMultiselect")
.button
.find("span.ui-icon.ui-icon-triangle-1-s")
.removeClass("ui-icon ui-icon-triangle-1-s")
.addClass("fa fa-caret-down")
.css({
float: "right",
marginRight: "5px"
});
}, 50);
},
multiselectTemplate = {
stype: "select",
searchoptions: {
generateValue: true,
//noFilterText: "Any",
sopt: ["in"],
attr: {
multiple: "multiple",
size: 3
},
dataInit: dataInitMultiselect
}
};
declares multiselectTemplate template. The next code fragment uses the template in colModel
colModel: [
...
{
name: "ship_via", width: 85, align: "center",
template: multiselectTemplate
},
...
],
Finally loadComplete include the code, which create filter toolbar after the data are loaded from the server:
loadComplete: function () {
if (!this.ftoolbar) {
// create filter toolbar if it isn't exist
$(this).jqGrid("filterToolbar", {
defaultSearch: "cn",
beforeClear: function() {
$(this.grid.hDiv)
.find(".ui-search-toolbar button.ui-multiselect")
.each(function() {
$(this).prev("select[multiple]").multiselect("refresh");
});
}
});
$(this).triggerHandler("jqGridRefreshFilterValues");
$(this.grid.hDiv)
.find(".ui-search-toolbar button.ui-multiselect")
.each(function() {
$(this).prev("select[multiple]")
.multiselect("refresh");
});
}
},
If required one can reload the data in filter toolbar by destroying it by destroyFilterToolbar method and executing the same code fragment which create it once more (I mean above code inside of loadComplete).

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

How to make a multiple table header

I am trying to make a table with 2 headers merged. At the moment i made 2 seperate tables with 2 seperate headers and it looks okay, but when the table width expands the first table header does not expand. How can i merge the 2 headers or can i make 1 table with 2 tableheaders. Please see picture (how the table is at the moment with 2 tableheaders)
Here is my code :
function createPDF(){
/** START PDF INSTANCE */
//var doc = new jsPDF('p', 'pt');
var doc = new jsPDF('l', 'pt');
var row = 80;
addPdfHeader(doc, row, vm.translate("REPORT.LEGALFORMS ")+" "+vm.activeCompanyYear);
doc.setFillColor(33, 150, 243);
var columns = [ " ",vm.activeCompanyYear,vm.activeCompanyYear-1,vm.activeCompanyYear-2];
var rows = [];
var description = "";
for(var j=0; j<vm.reportData.length; j++){
var obj = vm.reportData[j];
description = obj.descriptionEng;
if(description == "total"){
description = vm.translate("REPORT.REGISTRY.TOTAL");
}
var singleRow = [description,
obj.year3Total,
obj.year3Local,
obj.year3International,
obj.year2Total,
obj.year2Local,
obj.year2International,
obj.year1Total,
obj.year1Local,
obj.year1International
]
rows.push(singleRow);
}
doc.autoTable(columns, [], {
theme : 'grid',
styles: {
halign: 'right'
},
headerStyles: {
fillColor: [33, 150, 243],
halign:'center',
lineWidth: 1,
lineColor: [221, 221, 221]
},
columnStyles:{
0: {columnWidth: 266}
},
margin : {
top : 100
}
});
var columns2 = [ vm.translate("MENU.SETTINGS.LEGALFORM"),
vm.translate("REPORT.REGISTRY.TOTAL"),
vm.translate("REPORT.REGISTRY.LOCAL"),
vm.translate("REPORT.REGISTRY.INTERNATIONAL"),
vm.translate("REPORT.REGISTRY.TOTAL"),
vm.translate("REPORT.REGISTRY.LOCAL"),
vm.translate("REPORT.REGISTRY.INTERNATIONAL"),
vm.translate("REPORT.REGISTRY.TOTAL"),
vm.translate("REPORT.REGISTRY.LOCAL"),
vm.translate("REPORT.REGISTRY.INTERNATIONAL")
];
doc.autoTable(columns2, rows, {
theme : 'grid',
styles: {
halign: 'right'
},
headerStyles: {
halign:'center',
lineWidth: 1,
lineColor: [221, 221, 221]
},
margin : {
top : 120
},
columnStyles:{
0: {halign:'left'}
},
createdCell: function(cell, data) {
if(data.row.raw[0] === vm.translate("REPORT.REGISTRY.TOTAL")) {
cell.styles.fontStyle = 'bold';
cell.styles.fillColor = [255,251,204];
}
}
});
doc.save();
};
Something like this (v3 and up):
let head = [
[
{content: 'People', colSpan: 3, styles: {halign: 'center', fillColor: [22, 160, 133]}},
{content: 'Data', colSpan: 2, styles: {halign: 'center', fillColor: [22, 160, 133]}}
],
['ID', 'Name', 'Email', 'City', 'Sum'],
];
doc.autoTable({
startY: 60,
head: head,
body: body,
theme: 'grid'
});

How to maintain checkbox selection while reloading the JQuery Grid?

I have a JQuery grid which I am reloading everytime when some event occurs on the server (i.e. update in the data set) and display the latest set of data in the grid. This grid has also got checkboxes in it's first column. What's happening is let's say user is selecting some checkboxes and in the meantime if the grid gets reloaded due to update in the data on the server, my grid gets reloaded with the latest set of data but all my previous checkbox selection gets lost. How can I mark these selected checkboxes again after grid reload?
Please suggest.
function PushData() {
// creates a proxy to the Alarm hub
var alarm = $.connection.alarmHub;
alarm.notification = function () {
$("#jqTable").trigger("reloadGrid",[{current:true}]);
};
// Start the connection and request current state
$.connection.hub.start(function () {
BindGrid();
});
}
function BindGrid() {
jqDataUrl = "Alarm/LoadjqData";
var selectedRowIds;
$("#jqTable").jqGrid({
url: jqDataUrl,
cache: false,
datatype: "json",
mtype: "POST",
multiselect: true ,
postData: {
sp: function () { return getPriority(); },
},
colNames: ["Id", "PointRef", "Value", "State", "Ack State", "Priority", "AlarmDate", "", ""],
colModel: [
//{ name: 'alarmId_Checkbox', index: 'chekbox', width: 100, formatter: "checkbox", formatoptions: { disabled: false }, editable: true, edittype: "checkbox" },
{ name: "AlarmId", index: "AlarmId", width: 70, align: "left" },
{ name: "PointRef", index: "PointRef", width: 200, align: "left" },
{ name: "Value", index: "Value", width: 120, align: "left" },
{ name: "AlarmStateName", index: "AlarmStateName", width: 150, align: "left" },
{ name: "AcknowledgementStateName", index: "AcknowledgementStateName", width: 200, align: "left" },
{ name: "Priority", index: "Priority", width: 130, align: "left" },
{ name: "AlarmDate", index: "AlarmDate", width: 250, align: "left" },
{ name: "TrendLink", index: "Trends", width: 100, align: "left" },
{ name: "MimicsLink", index: "Mimics", width: 100, align: "left" }
],
// Grid total width and height
width: 710,
height: 500,
hidegrid: false,
// Paging
toppager: false,
pager: $("#jqTablePager"),
rowNum: 20,
rowList: [5, 10, 20],
viewrecords: true, // "total number of records" is displayed
// Default sorting
sortname: "Priority",
sortorder: "asc",
// Grid caption
caption: "Telemetry Alarms",
onCellSelect: function (rowid, icol, cellcontent, e) {
var cm = jQuery("#jqTable").jqGrid('getGridParam', 'colModel');
var colName = cm[icol];
//alert(colName['index']);
if (colName['index'] == 'AlarmId') {
if ($("#AlarmDialog").dialog("isOpen")) {
$("#AlarmDialog").dialog("close");
}
AlarmDialogScript(rowid)
}
else if (colName['index'] == 'Trends') {
TrendDialogScript(rowid)
}
else if (colName['index'] == 'Mimics') {
MimicsDialogScript(rowid)
}
else {
$("#jqTable").setCell(rowid, "alarmId_Checkbox", true); //Selects checkbox while clicking any other column in the grid
}
},
recreateFilter: true,
emptyrecords: 'No Alarms to display',
loadComplete: function () {
var rowIDs = jQuery("#jqTable").getDataIDs();
for (var i = 0; i < rowIDs.length; i++) {
rowData = jQuery("#jqTable").getRowData(rowIDs[i]);
//change the style of hyperlink coloumns
$("#jqTable").jqGrid('setCell', rowIDs[i], "AlarmId", "", { 'text-decoration': 'underline', 'cursor': 'pointer' });
$("#jqTable").jqGrid('setCell', rowIDs[i], "TrendLink", "", { 'text-decoration': 'underline', 'cursor': 'pointer' });
$("#jqTable").jqGrid('setCell', rowIDs[i], "MimicsLink", "", { 'text-decoration': 'underline', 'cursor': 'pointer' });
if ($.trim(rowData.AcknowledgementStateName) == 'Active') {
$("#jqTable").jqGrid('setCell', rowIDs[i], "AcknowledgementStateName", "", { 'background-color': 'red', 'color': 'white' });
}
else if ($.trim(rowData.AcknowledgementStateName) == 'Acknowledged') {
$("#jqTable").jqGrid('setCell', rowIDs[i], "AcknowledgementStateName", "", { 'background-color': 'Navy', 'color': 'white' });
}
}
//$("#jqTable").jqGrid('hideCol', "AlarmId") //code for hiding a particular column
},
gridComplete: function () {
$('#jqTable input').bind('mouseover', function () {
var tr = $(this).closest('tr');
if ($("#AlarmDialog").dialog("isOpen")) {
$("#AlarmDialog").dialog("close");
}
AlarmDialogScript(tr[0].id);
}
);
}
}).navGrid("#jqTablePager",
{ refresh: true, add: false, edit: false, del: false },
{}, // settings for edit
{}, // settings for add
{}, // settings for delete
{sopt: ["cn"]} // Search options. Some options can be set on column level
)
.trigger('reloadGrid', [{page:1, current:true}]);
}
If I understand you correct you need just use additional parameter i
$("#list").trigger("reloadGrid", [{current:true}]);
or
$("#list").trigger("reloadGrid", [{page: 1, current: true}]);
(See the answer). It do almost the same what Justin suggested.
Depend from what you want exactly mean under reloading of the grid it can be that waht you need is to save the grid state inclusive the list of selected items in localStorage and reload the state after loading the grid. This answer describes in details the implementation. The corresponding demo from the answer could be simplified using new jqGrid events which are introduced in version 4.3.2.
You could save the selections before reloading the grid, for example in the beforeRequest event:
selectedRowIDs = jQuery('#myGrid').getGridParam('selarrrow');
Then after the grid has been reloaded, you can loop over selectedRowIDs and reselect each one using setSelection. For example:
for (i = 0, count = selectedRowIDs.length; i < count; i++) {
jQuery('#myGrid').jqGrid('setSelection', selectedRowIDs[i], false);
}
You might run this code in the loadComplete event.
use
recreateFilter: true
and you should be done

Resources