I already know how to modify the style of the result of print button, I just need to have 2 print button that output different style.
Multiple of the same button extension
Row grouping with printing
I believe i solved the problem with printing with row grouping. I found a snippet of code on StackOverflow here and was able to fix it up to work with row grouping. This is placed in datatable-buttons.js on line 1564.
Heres some images of it working!
http://prntscr.com/fhx1vu
http://prntscr.com/fhx1ia
var _exportData = function ( dt, inOpts )
{
var config = $.extend( true, {}, {
rows: null,
columns: '',
grouped_array_index: [],
modifier: {
search: 'applied',
order: 'applied'
},
orthogonal: 'display',
stripHtml: true,
stripNewlines: true,
decodeEntities: true,
trim: true,
format: {
header: function ( d ) {
return strip( d );
},
footer: function ( d ) {
return strip( d );
},
body: function ( d ) {
return strip( d );
}
}
}, inOpts );
var strip = function ( str ) {
if ( typeof str !== 'string' ) {
return str;
}
// Always remove script tags
str = str.replace( /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '' );
if ( config.stripHtml ) {
str = str.replace( /<[^>]*>/g, '' );
}
if ( config.trim ) {
str = str.replace( /^\s+|\s+$/g, '' );
}
if ( config.stripNewlines ) {
str = str.replace( /\n/g, ' ' );
}
if ( config.decodeEntities ) {
_exportTextarea.innerHTML = str;
str = _exportTextarea.value;
}
return str;
};
var header = dt.columns( config.columns ).indexes().map( function (idx) {
var el = dt.column( idx ).header();
return config.format.header( el.innerHTML, idx, el );
} ).toArray();
var footer = dt.table().footer() ?
dt.columns( config.columns ).indexes().map( function (idx) {
var el = dt.column( idx ).footer();
return config.format.footer( el ? el.innerHTML : '', idx, el );
} ).toArray() :
null;
var rowIndexes = dt.rows( config.rows, config.modifier ).indexes().toArray();
var selectedCells = dt.cells( rowIndexes, config.columns );
var cells = selectedCells
.render( config.orthogonal )
.toArray();
var cellNodes = selectedCells
.nodes()
.toArray();
var grouped_array_index = config.grouped_array_index; //customised
var no_of_columns = header.length;
var no_of_rows = no_of_columns > 0 ? cells.length / no_of_columns : 0;
var body = new Array( no_of_rows );
var body_data = new Array( no_of_rows ); //customised
var body_with_nodes = new Array( no_of_rows ); //customised
var body_with_nodes_static = new Array( no_of_rows ); //customised
var cellCounter = 0;
for (var i = 0, ien = no_of_rows; i < ien; i++)
{
var rows = new Array( no_of_columns );
var rows_with_nodes = new Array( no_of_columns );
for ( var j=0 ; j<no_of_columns ; j++ )
{
rows[j] = config.format.body( cells[ cellCounter ], i, j, cellNodes[ cellCounter ] );
rows_with_nodes[j] = config.format.body( cellNodes[ cellCounter ], i, j, cells[ cellCounter ] ).outerHTML;
cellCounter++;
}
body[i] = rows;
body_data[i] = rows;
body_with_nodes[i] = $.parseHTML('<tr class="even">'+rows_with_nodes.join("")+'</tr>');
body_with_nodes_static[i] = $.parseHTML('<tr class="even">'+rows_with_nodes.join("")+'</tr>');
}
/******************************************** GROUP DATA *****************************************************/
var row_array = dt.rows().nodes();
var row_data_array = dt.rows().data();
var iColspan = no_of_columns;
var sLastGroup = "";
var inner_html = '',
grouped_index;
var individual_group_array = [],
sub_group_array = [],
total_group_array = [];
var no_of_splices = 0; //to keep track of no of element insertion into the array as index changes after splicing one element
for (var i = 0, row_length = body_with_nodes.length; i < row_length; i++)
{
sub_group_array[i] = [];
individual_group_array[i] = [];
var sGroup = '';
for(var k = 0; k < grouped_array_index.length; k++)
{
sGroup = row_data_array[i][grouped_array_index[k]];
inner_html = row_data_array[i][grouped_array_index[k]];
grouped_index = k;
individual_group_array[i][k] = row_data_array[i][grouped_array_index[k]];
sub_group_array[i][k] = sGroup;
}
total_group_array[i] = sGroup;
console.log("grouped_index",grouped_index);
if ( sGroup !== sLastGroup )
{
var table_data = [];
var table_data_with_node = '';
for(var $column_index = 0;$column_index < iColspan;$column_index++)
{
if($column_index === 0)
{
table_data_with_node += '<td style="border-left:none;border-right:none">'+inner_html+'</td>';
table_data[$column_index] = inner_html + " ";
}
else
{
table_data_with_node += '<td style="border-left:none;border-right:none"></td>';
table_data[$column_index] = '';
}
}
body_with_nodes.splice(i + no_of_splices, 0, $.parseHTML('<tr class="group group_'+grouped_index+' grouped-array-index_'+grouped_array_index[grouped_index]+'">'+table_data_with_node+'</tr>'));
body_data.splice(i + no_of_splices, 0, table_data);
no_of_splices++;
sLastGroup = sGroup;
}
}
return {
header: header,
footer: footer,
body: body_data
};
};
Usage:
Define grouped_array_index in exportOptions
exportOptions: {
// Any other settings used
grouped_array_index: [<place row to use here>],
},
Datatables column modification after initcomplete
I have a list of projects that the controller send to the view:
[HttpGet]
public ActionResult GetAllProjects(string userid, string stat)
{
return Json(new
{
aaData = Repository.GetAllProjects(userid).Select(x => new String[] {
x.ID,
x.ProjectNumber.ToString(),
x.ProjectTypeText,
x.SelectedProjectType,
x.Priority.ToString(),
x.StatusText,
x.Status,
x.ProjectStateText,
x.ProjectState,
x.CreatedDateForDisplay,
x.ProjectTitle,
x.Description,
x.CreatedBy,
x.AssignedUserName,
x.AssignedUser,
x.BackUpUserName,
x.BackUpUser,
x.Criticality.ToString(),
x.EvaluationDeadlineDateForDisplay,
x.SolutionDeadlineDateForDisplay,
x.NumberofComments.ToString(),
x.Notify.ToString(),
x.ITDRequest.ToString(),
x.NewFunding.ToString()
})
}, JsonRequestBehavior.AllowGet);
}
The problem is that the list of statuses is different for each project type and I am trying to change the dropdown after I initialize the table. I can display ALL statuses with this:
"render": function(data, type, full, meta){
var typestatlist;
var $ddiv = $("<div class='tooltip'><span class='tooltiptext' style='font-size:x-small !important;'>Select Project Status for this project.</span></div>");
var $select = $("<select></select>", { 'class' : 'ctrl-status'});
$select.attr("id", "ddl" + full[0])
$.each(statuslist, function (Value, Text) {
var $opt = $('<option value=' + Text.Value + '>' + Text.Text + '</option>');
if (Text.Value === full[6]){
$opt.attr("selected", "selected");
}
$select.append($opt);
});
$ddiv.append($select);
return $ddiv.prop("outerHTML");
But I am trying to change it based on type in the initcomplete:
var tab = $("#tblProjects").DataTable();
tab.rows().every(function (idx, tbll, rwl){
var dat = this.data();
var c = dat[3];
var rw = this;
var $ddiv = $("<div class='tooltip'><span class='tooltiptext' style='font-size:x-small !important;'>Select Project Type for this project.</span></div>");
var $select = $("<select></select>", { 'class' : 'ctrl-status'});
$.ajax({
type:'GET',
url: '@Url.Action("GetAllProjectStatusPairsByType")',
data: { type : c},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
if (data.length === 0){
typestatlist = { "Value" : "NONE", "Text" : "NONE"};
} else {
typestatlist = data;
}
$.each(typestatlist, function (Value, Text) {
var $opt = $('<option value=' + Text.Value + '>' + Text.Text + '</option>');
if (Text.Value === c){
$opt.attr("selected", "selected");
}
$select.append($opt);
});
$ddiv.append($select);
dat[5] = $ddiv;
rw.data(dat);
}
});
});
"uncaught exception: Unknown button type: print" and I'm only wanting to offer Excel-Export
Example (here)[http://mbaas.de/DataTable%20Buttons.html]
(Debugger: akefek)[http://debug.datatables.net/akefek]
I am trying to make just Excel-Export available via the buttons-plugin with the option "buttons":"excel"
- but when I load the page, I get the error shown in the title. What am I doing wrong?
Integration problem with Editor and Select2 plugin
I would like to integrate the select2 plugin with Editor but the following problems occur:
- What should the data of Office field be in order to Select2 plugin reads and inserts correct values?
- If you click on X in selected Tag, it does not cause removing this tag and the drop-down list stays open as well.
- After manually removing all picked tags, do nothing happens, I mean that no POST request is sent and there is still data in the field.
Below is an example (this is made according to your documentation) with the above problems.
http://webinsert.pl/bug_test/
I am asking for help in removing these problems. Thnx.
The image behind the print view doesnt display in datatable
Hi,
My Code Snippet below there.I want to display a logo image behind the writings on print view of datatable.But I cant.Please help me how i can do that.(p.s. "images" folder is in my visual studio project.)
My Code Snippet
$(document).ready(function () {
var table = $('#RaporList').DataTable({
"aLengthMenu": [[4, 8, 12, -1], [4, 8, 12, "All"]],
"iDisplayLength": 4,
"bPaginate": false,
"bLengthChange": false,
"bFilter": true,
"bInfo": false,
"bAutoWidth": false,
"aaSorting": [[1, 'asc']],
dom: 'Bfrtip',
buttons: [
{
extend: 'excelHtml5',
exportOptions: {
columns: [1,2,3,4,5,6,7,8]
}
},
{
extend: 'print',
title: '',
messageTop: '<p style="font-size:24px">' + 'Haftalık Rapor Listesi',
customize: function (win) {
$(win.document.body)
.css('font-size', '14pt')
.prepend(
'<img src="images/Logo2.png" height=79 width=116
style="position:absolute; top:0; left:0;" />'
);
$(win.document.body).find('table')
.addClass('compact')
.css('font-size', 'inherit');
},
exportOptions: {
columns: [1, 2, 3, 4, 5, 6, 7, 8]
}
},
],
select: {
style: 'single'
},
});
});
FileUpload and ServerSide processing incompatible?
hello i was just trying to use editor, on tip from a friend, but i think that i found a critical bug:
https://editor.datatables.net/examples/advanced/upload.html
if you use the file upload feature in combination with server side processing Datatables PHP Server API will still continue to give in the reply json the full list of the "files" table that, and does not limit on the record shown, looking at the future when having like 1000+ rows can result in a lot of unuseful transmitted data on each request.
is there a way to limit the file list to the shown records? am i doing something wrong?
Upload many combined with child table
Hello everyone,
I tried to combine the upload many example (https://editor.datatables.net/examples/advanced/upload-many.html) with child table example (https://datatables.net/blog/2016-03-25) to upload files only for the child entries, but I always get the error message "A server error occurred while uploading the file".
I guess the error occurs due the php server script.
I set up an extra SQL-Table like this (with one manually created entry):
CREATE TABLE `files` (
`id` int(8) NOT NULL auto_increment,
`user_id` varchar(128) NOT NULL,
`file_id` varchar(128) NOT NULL,
`filename` varchar(128) NOT NULL,
`filesize` varchar(128) NOT NULL,
`web_path` varchar(256) NOT NULL,
`system_path` varchar(256) NOT NULL,
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `files` (`id`, `user_id`, `file_id`, `filename`, `filesize`, `web_path`, `system_path`) VALUES
(1, '58', '1', 'tset.pdf', '4232424', 'http://127.0.0.1/upload/', '/upload/');
Do I need a second "users_files" table? I don't understand this part in the upload example:
Mjoin::inst( 'files' )
->link( 'users.id', 'users_files.user_id' )
->link( 'files.id', 'users_files.file_id' )
Can anyone explain this part to me?
I already changed a lot, so it would be hard to review my whole code, but if anyone interested in it than I can publish it.
Thanks in advance
pib
How Can I Change Font Size of PDF Message?
Hi,
How can i change the font size of PDF " messageTop" font size and font style(bold)?
{
extend: 'pdfHtml5',
messageTop: 'Report List',
}
How to load nested object array in DataTable
I have a json file that contains information and multiple recordsets (2 in this case). I'm trying to load them in individual datatable. I would like to load DMale DFemale in each a separate DataTable. My json file look looks like:
{
"event":[
{
"name":"test",
"date":"Feb 11, 2018"
}
],
"results":[
{
"Cat-D-Male":[
{
"Rank":"1",
"Bib":"192",
"First Name":"Kerry",
"Last Name":"Reve",
"Time":"01:01:28.445",
"Gap":"",
"Lap 1":"00:00:13.15",
"Lap 2":"00:11:44.58",
"Lap 3":"00:12:09.24",
"Lap 4":"00:12:03.94",
"Lap 5":"00:12:31.31",
"Lap 6":"00:12:46.20"
}
],
"Cat-D-Female":[
{
"Rank":"1",
"Bib":"178",
"First Name":"Lisa",
"Last Name":"Sax",
"Time":"00:58:40.708",
"Gap":"",
"Lap 1":"00:00:14.89",
"Lap 2":"00:11:49.55",
"Lap 3":"00:11:29.52",
"Lap 4":"00:11:21.15"
},
{
"Rank":"2",
"Bib":"325",
"First Name":"Mellisa",
"Last Name":"Sweet",
"Time":"00:51:12.671",
"Gap":"-1 Lap",
"Lap 1":"00:00:17.52",
"Lap 2":"00:12:56.86",
"Lap 3":"00:12:23.24",
"Lap 4":"00:12:54.41"
}
]
}
]
}
But I'm unable to extract DMale and DFemale to create the 2 DataTable. This is what I have so far:
<script>
$( document ).ready( function( $ ) {
$.ajax({
type: "POST",
url: 't4.json',
cache: false,
dataType: 'json',
success: function(response) {
$("#ResultsDiv").empty();
$("#eventname").append(response.event[0].name);
$("#eventdate").append(response.event[0].date);
$("#eventlocation").append(response.event[0].location);
console.log("1:" + response);
var totalMessages = Object.keys(response.results[0]).length;
console.log("2: Count= " + totalMessages);
$.each(response.results[0], function(key, val) {
console.log("3a:" + key);
console.log("3b:" + val.length);
console.log("3c:" + JSON.stringify(val));
initiateTable(key, val);
});
}
})
function initiateTable(tableId, source) {
$("#ResultsDiv").append('<table id="' + tableId + '" class="table table-striped table-condensed" cellspacing="0" width="100%"></table>');
var table = $("#" + tableId).dataTable({
"data": source,
"bProcessing": true,
"bPaginate": false,
"bLengthChange": false,
"bFilter": true,
"bInfo": false,
"bAutoWidth": true,
"columnDefs": [{
"targets": 'no-sort',
"orderable": false
}]
});
}
});
</script>
How can I pass each dataset to create a new DataTable and load the data and append it to the others tables in my div? I'm vey new at using JSon and DataTable, this is the fist time I use it.
Is is it possible to set fixed width to header(s) in DataTable Js ?
I want to set width of each header column dynamically (mean getting the width value from Database) .
Please suggest !!
Thank you
ajax.reload is lazy-loading and resizing
Hello together,
it's my first time working with DataTables but I really enjoy the functionality of the framework.
While developing i happened to get two behaviours i didn't expect:
Resizing
I have a server-side-processed dataTable on my page which is initialized when the document is ready (jQuery).
Sometimes the width of the table-header-row isn't calculated probably so the visual result looks kinda buggy.
The table body is sized perfectly after loading the data but the header-row is only at minimum width and not as wide as the body.ajax.reload
The API-Method ajax.reload seems to be lazy-loading. It only works for me if i change a property of the API-object via the search method (or any other method) before i call ajax.reload.
Is there anyway to force the ajax reload?
Greetings dvol
Bug Responsive 2.2.1 bootstrap 4 in Collapse Componet
Responsive-2.2.1
https://getbootstrap.com/docs/4.0/components/collapse/
When entering a table into a collapse, the table is not responsive unless the window is resized manually. (Large and reduce again)
CSS ::before property only working in first column of multi-column colvis buttons in Chrome v63.0.32
I am using Colvis. I have set the collectionLayout property to 'fixed three-column'. I use CSS to put a tick or a cross before my button text, to indicate whether the column is selected or not. Since the lastest version of Chrome has been released, the tick or cross does not show in anything but the first column. It does work in IE11, Edge, Firefox and Chrome v62.0.32.
Here is a screen shot of my problem:
This is the css
/* put a cross to show that a column is not visible */
a.dt-button.buttons-columnVisibility span.glyphicon:before {
content:"\e014";
}
/* put a tick to show that a column is visible */
a.dt-button.buttons-columnVisibility.active:not(.disabled) span.glyphicon:before{
content: "\e013";
}
This is the javascript:
{
extend: 'colvis',
columns: ':not(.excluded-from-colvis)',
className: 'btn btn-primary colvis-button',
collectionLayout: 'fixed three-column',
columnText: function ( dt, idx, title ) {
return '<span class="glyphicon"></span> ' + title;
},
postfixButtons: [{
extend: 'colvisGroup',
text: 'Show all columns',
show: ':not(.excluded-from-colvis)'
}]
}
Custom column filter with filter icon beside column header text!!!
Hi Team,
I'm wondering if is there anyway to add a filter icon beside column header name, and when user click on it, it should show the filter options like search and strings from the table for that particular column. Please find the attached reference image.
Thanks!
Toggle button not work on page 2 and so on. How can I fix it.
See the image of first page. The toggle button work on 1st page.
Toggle button not properly working on page 2.
DataTables Inline Editor select does not maintain selected value
Dear,
We are having same problem like the one mentioned in the https://datatables.net/forums/discussion/31210/datatables-inline-editor-select-does-not-select-current-value-or-submit-first-value. Can you please send us the fixed .js files.
Basically select combo doesn't maintain the selected value and instead when we click it for editing combo box always initialized and select first value instead of the selected one.
An early reply will be helpful.
Set focus to search easily
One thing I noticed recently is that it would be nice if the search-field on many of the Datatables I created could automically get focus on PageLoad. Now there is a lot of JS-Code around on the web t do this - but...
* it would be nice to have this as an optional feature in DT
* the HTML5-approach to this seems to be to set the "autofocus"-attribute on the control - and that calls for Datatables even louder (I suspect it would be need to be set early on).
Is there a way to combine Child Rows with Knockout.js Bindings?
So, I'm using Knockout to iterate through an array of objects to inject the html elements (aka, the tr's) needed to create the DataTable.
An example is:
< !-- ko foreach: foo -->
<tr>
<td data-bind="text: id"></>
<td data-bind="text: description"></td>
</tr>
<!-- /ko -->
This create a two-column row with the 'id' property of each 'foo' as the text of the first and the 'description' property as the second.
This works great. Here's where it gets funky, I'm trying to use DataTable's child rows so that I can include more information about my 'foo' objects when a user clicks on the row, as is done on this page:
https://datatables.net/extensions/responsive/examples/child-rows/whole-row-control.html
but this function that adds extra elements to the html will not work for me, as all html elements that are bound to my Knockout object require the 'data-bind' attribute function and for the 'data-bind' attribute to work, they must all be present when the view model object is bound to the page (during the time of initial page rendering, and before the DataTable is created.)
Is there a way I could use the DataTable initializer to include a child element for all of my rows that would include this data-bind attribute, instead of inject html elements every time I click on the row, or to create rows that are already linked to one another and not separated when the DataTable is created?
Responsive rules based on table width
I've read through all the documentation, but I'm not seeing a way to accomplish what I'm trying to do.
I have a table that I'm attaching the responsive extension to. The table has 15 columns. 7 of the columns, I always want to show when the table width is above a certain breakpoint. The responsive breakpoint system works based on the viewport, not the table size so it does not do what I need.
I looked into using the responsive-resize
event, but it fires after the resize and you can't use the columns
argument to override the column behavior. Also, there's no API for manually overriding the column to show up as a column.
Is there a good way to accomplish this?
Also, is there a way to apply a max-width to a column at various table width breakpoints?
I ask because one of the related problems I'm having is I have a particular column that at times can contain some long strings. The responsive extension ends up making the column much wider than I'd prefer, which ends up causing other columns to drop. I'd really like to set some max constraints to columns based upon the table width.
For example, if the table is less 800px, make column 2 have a max width of 200px.
If I could constrain the columns based on the parent table width, this would resolve my issues.
Thanks!