Looks like yesterday they released v4.0.0.
Bootstrap 4 released
Datatables not working for webform using master page
Hello,
I am new to datatables and I am having issues getting my webform that uses a master page to use the datatable functionality. Can anyone give me any ideas?
I have the js files included on the html and the jQuery to reference the datatables.
Thanks!
[DT 10.1] Select row
Hi,
How can I programmatically select a row after inserting a new one ? (its has be inserted with an ajax call to the DB)
Thanks
Can't use DataTables with boostrap 4
Hi,
I'm sorry but I don't understand how to make DataTable work correctly with Bootstrap 4.
I've used the download builder to get a bootstrap 4 package, without any other option than boostrap 4 checked.
I use bootstrap-4.0.0-beta.3
The package includes 4 standard files at the root of the archive :
- datatables.css (+datatables.min.css)
- datatables.js (+datatables.min.js)
If I use those files, the plugin works, but the border-spacing is separated (I want it collapsed). I did not find a way to make it collapsed (I don't want to add a "style" attribute on my table).
See : https://i.imgur.com/H0EmNSb.png
I thought I was not using the right correct files for bootstrap.
In the archive, there is also a "DataTables-1.10.16" folder which includes some folders (css, js, images) in which I found :
- dataTables.bootstrap4.js
- dataTables.bootstrap4.css
I've tried to use those two files instead of the original files : now my borders are collapsed, but DataTables does not work anymore : I get a "$().DataTable is not a function" error in the javascript console.
Could you tell me what i'm doing wrong ?
Thanks !
Robust audit logging
I wanted to add something to my logging so that could quickly see at a glance what the actual changes to the data were.
There's an example of logging changes here: https://editor.datatables.net/manual/php/events#Logging-changes
And a related discussion here: https://datatables.net/forums/discussion/44932
I do an additional step to compare the $prevValues and the $values and store the difference in two different fields in the database.
I add each of these events to the instance of Editor:
// Pre functions
->on( 'preEdit', function ( $editor, $id, $values ) {
getPrevValues($editor->db(), $editor->table()[0], $id);
} )
->on( 'preRemove', function ( $editor, $id, $values ) {
getPrevValues($editor->db(), $editor->table()[0], $id);
} )
// Post functions
->on( 'postCreate', function ( $editor, $id, $values, $row ) {
logChange( $editor->db(), $editor->table()[0], 'create', $id, $values );
} )
->on( 'postEdit', function ( $editor, $id, $values, $row ) {
logChange( $editor->db(), $editor->table()[0], 'edit', $id, $values );
} )
->on( 'postRemove', function ( $editor, $id, $values ) {
logChange( $editor->db(), $editor->table()[0], 'delete', $id, $values );
} )
And then I use array_intersect_key()
along with array_diff_assoc()
(in PHP) to find the difference between the two and store that in separate fields:
$prevValues = [];
function getPrevValues ( $db, $table, $id ) {
global $prevValues;
$prevValues = $db->select( $table, '*', [ 'id' => $id ] )->fetch();
}
function logChange ( $db, $table, $action, $id, $values ) {
global $prevValues;
switch ($action) {
case "create":
$old_values = [];
$new_values = $values;
break;
case "edit":
$old_values = array_intersect_key(array_diff_assoc($prevValues,$values),array_diff_assoc($values,$prevValues));
$new_values = array_intersect_key(array_diff_assoc($values,$prevValues),array_diff_assoc($prevValues,$values));
break;
case "delete":
$old_values = $prevValues;
$new_values = [];
break;
}
if (!empty($old_values) || !empty($new_values) ) {
$db->insert( 'ws_log', [
'user' => $_POST['currentUser'],
'when' => date('c'),
'table' => $table,
'row' => $id,
'action' => $action,
'same_values' => json_encode($prevValues),
'old_values' => json_encode($old_values),
'new_values' => json_encode($new_values)
]);
}
}
Now at a glance I can see 1) who made a change, 2) when it was done, 3) what table and row was it done on, 4) what type of action it was (create, edit, or delete), and 5) what the specific changes to the data were. I also have the prev_values
in case I'd like to dig deeper.
Submit on row blur when using inline editing?
Using inline editing, is there a way to submit on row blur instead of on the cell blur?
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.
DataTable date filter function not working on Chrome for mobile
Hello all,
i'm having a strange issue:
this function is working perfectly on desktop:
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
var iFini = document.getElementById('date_min').value;
var iFfin = document.getElementById('date_max').value;
var iStartDateCol = 3;
var iEndDateCol = 3;
iFini=iFini.substring(0,4) + iFini.substring(5,7)+ iFini.substring(8,10);
iFfin=iFfin.substring(0,4) + iFfin.substring(5,7)+ iFfin.substring(8,10);
var datofini=aData[iStartDateCol].substring(0,4) + aData[iStartDateCol].substring(5,7)+ aData[iStartDateCol].substring(8,10);
var datoffin=aData[iEndDateCol].substring(0,4) + aData[iEndDateCol].substring(5,7)+ aData[iEndDateCol].substring(8,10);
if ( iFini === "" && iFfin === "" )
{
return true;
}
else if ( iFini <= datofini && iFfin === "")
{
return true;
}
else if ( iFfin >= datoffin && iFini === "")
{
return true;
}
else if (iFini <= datofini && iFfin >= datoffin)
{
return true;
}
return false;
}
);
But for some reason when i try to filter the data table on Mobile (android 7 - latest chrome version) the filter is not working.
These are my includes:
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
Can you think of any reason why?
"New Discussion" missing "Edit" button after preview
I noticed here on the forums that if I select "Ask a Question" then I can select the "Preview" button and there will be a button to "Edit" after the preview comes up.
However if I select "New Discussion" and then "Preview", there is no "Edit" button available afterwards.
Update field value based on another field changed inline.
I need to reset fields values based on a value changed in another inline field . I tried using the following script, however when the table is loaded the first time, the code is executed and wipes out the values in said fields. I just need to perform this operation when a user changes the HRWPER. So let's say, if the percent field changed from 2.0 to 3.0, I need to reset other fields.
I am sure there is a better way to do this so all suggestions are welcomed.
$( editor.field( 'HRWPER' ).input() ).on( 'change', function () {
//**Reset Plant Manager Approval function
editor.field( 'HRWMGR' ).val( 0);
editor.field( 'HRWMNA' ).val( '');
} );
Customized search applicable to both normal datatable and datatable with child rows.
I have an application with two datatables.
1.Has only parent rows (no child rows) say datatable1.
2.Has parent rows as well as child rows say datatable2.
I want to implement only one search for both the datatables.
For the datatable2 I implemented davidkonrad's answer on this link: https://stackoverflow.com/questions/30471089/datatables-search-child-row-content/ which works fine.
But the search does not work for the datatable2.
Any help would be greatly appreciated.
Thank you.
datatables editor and having to return custom JSON
Okay because of the specific way the actual table is populated using JSON. I have to duplicate the custom JSON when returning. Now to return this custom JSON Would I use echo or return?
`row.add()` throws error when attempting to add a row using an object.
https://codepen.io/anon/pen/GyPeqr demonstrates the problem.
I'd like to be able to populate my table with objects to ensure that the data gets populated sanely everywhere. The example at https://datatables.net/reference/api/row.add() indicates that this is completely doable. I presume I'm missing some sort of special sauce around populating the table with objects, but I'm unclear as to what it is.
Problem with jQuery Datatables Buttons - Excel Export - Using Special Character like "&" or "
Hi,
like i mentioned in the header, we have a problem with the excel export funtion from jQuery Datatable Buttons - when using special characters like "&" or "<". The excel export function works great if the data in the Datatable doesnt contain any "&" or "<".
the csv export function has no problem with the special character its seems like this problem only happens in the export to excel function.
is there any solution for this problem?
best regards
Why do multiple mjoins on tbl with alias work when Creating Records, breaks when updating records
Hello, I have a test case.
retracted
I am trying to assign users to different templates. I have a Persons table, a Roles table, and a PersonRoles table. The idea is that I can assign different PersonRoleIDs to a TemplateID in the PersonRoleTemplates table when creating or updating a record in the Templates2 page. This is because someone might have an Admin role, but for only 1 template. While somebody else may have both an Admin role and an Analyst role but for only 2 templates.
The issue is that this code below works correctly when creating a record on the templates2 page. The page is also reading the json data correctly when you select a row and click edit. However, when you click update, the 'users' that have been assigned does not update correctly, in fact they get deleted, but for only 1 of the 2 mjoins. This is true if you edit who is assigned, and this is true when you hit update without changing who is assigned.
I cannot figure out the issue because the create works like a charm. I could use some help. I need to mention that the table 'PersonInfo' is a stored query. This is because I need to pull in more columns on the mjoin so that I can display info related to the person in the subtable (drill down) + and - icons, and so I can use the Name of the person in the checkboxes on the form.
The purpose of the $q->where( 'RoleID', '1', '=' ); and $q->where( 'RoleID', '2', '=' ); in pi1 and pi2 is so that the query being used in the mjoin only contains the correct RoleID, in this case, RoleID 1 = Admin, RoleID2 = Analyst.
PS - 'Users' come from the same table. They have different PersonRoleIDs in the case of 1 person have more than 1 role assigned to them. So I am performing more than 1 mjoin on the same table, in this case, a query with additional information. The completed project will have at least 4 mjoins on the same users query, all with alias pi1, pi2, pi3, and pi4.
/* Formatting function for row details - modify as you need */
function format ( d ) {
var mystring = ""
for (var i=0; i < d.pi1.length; i++){
var mystring = mystring + '<td>'+d.pi1[i].FName+'</td>'
};
var mystring2 = ""
for (var i=0; i < d.pi2.length; i++){
var mystring = mystring + '<td>'+d.pi2[i].FName+'</td>'
};
// `d` is the original data object for the row
return '<table id="testtable" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Report Desc:</td>'+
'<td>'+d.Templates.ReportDesc+'</td>'+
'</tr>'+
'<tr>'+
'<td>Admin</td>'+
mystring +
'<td>Analyst</td>'+
mystring2 +
'</tr>'+
'</table>';
}
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "../../php/Scripts/templates2.php",
table: "#example",
fields: [ {
label: "Report Name:",
name: "Templates.ReportName"
}, {
label: "Report Title:",
name: "Templates.ReportTitle"
}, {
label: "Report Desc:",
name: "Templates.ReportDesc"
}, {
label: "Frequency:",
name: "Templates.FrequencyID",
type: "select"
}, {
label: "DueDate Report Inbound:",
name: "Templates.NextDueDatePackager"
}, {
label: "DueDate Report Outbound:",
name: "Templates.NextDueDateRecipient"
},{
"label": "Admin:",
"name": "pi1[].PersonRoleID",
"type": "checkbox"
},{
"label": "Analyst:",
"name": "pi2[].PersonRoleID",
"type": "checkbox"
}
]
} );
var table = $('#example').DataTable( {
dom: "Bfrtip",
ajax: {
url: "../../php/Scripts/templates2.php",
type: 'POST'
},
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: "Templates.ReportName"},
{ data: "Templates.ReportTitle" },
{ data: "Frequencies.Frequency" },
{ data: "Templates.NextDueDatePackager" },
{ data: "Templates.NextDueDateRecipient" }
],
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
});
});
<?php
// DataTables PHP library
include( "../DataTables.php" );
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Options,
DataTables\Editor\Upload,
DataTables\Editor\Validate,
DataTables\Editor\ValidateOptions;
/*
* Example PHP implementation used for the joinLinkTable.html example
*/
Editor::inst( $db, 'Templates', 'TemplateID' )
->field(
Field::inst( 'Templates.ReportName' ),
Field::inst( 'Templates.ReportTitle' ),
Field::inst( 'Templates.ReportDesc' ),
Field::inst( 'Templates.FrequencyID' )
->options( Options::inst()
->table( 'Frequencies' )
->value( 'FrequencyID' )
->label( 'Frequency' )
),
Field::inst( 'Frequencies.Frequency' ),
Field::inst( 'Templates.NextDueDatePackager' ),
Field::inst( 'Templates.NextDueDateRecipient' )
)
->leftJoin( 'Frequencies', 'Frequencies.FrequencyID', '=', 'Templates.FrequencyID' )
->Join(
Mjoin::inst( 'PersonInfo' )
->where( function ($q) {
$q->where( 'RoleID', '1', '=' );
})
->name( 'pi1' )
->link( 'Templates.TemplateID', 'PersonRoleTemplates.TemplateID' )
->link( 'PersonInfo.PersonRoleID', 'PersonRoleTemplates.PersonRoleID' )
->order( 'PersonID asc' )
->fields(
Field::inst( 'PersonRoleID' )
->validator( Validate::required() )
->options( Options::inst()
->table( 'PersonInfo' )
->value( 'PersonRoleID' )
->label( 'FName' )
->where( function ($r) {
$r->where( 'RoleID', '1', '=' );
})
),
Field::inst( 'PersonID' ),
Field::inst( 'FName' ),
Field::inst( 'RoleID' )
)
)
->Join(
Mjoin::inst( 'PersonInfo' )
->where( function ($q) {
$q->where( 'RoleID', '2', '=' );
})
->name( 'pi2' )
->link( 'Templates.TemplateID', 'PersonRoleTemplates.TemplateID' )
->link( 'PersonInfo.PersonRoleID', 'PersonRoleTemplates.PersonRoleID' )
->order( 'PersonID asc' )
->fields(
Field::inst( 'PersonRoleID' )
->validator( Validate::required() )
->options( Options::inst()
->table( 'PersonInfo' )
->value( 'PersonRoleID' )
->label( 'FName' )
->where( function ($r) {
$r->where( 'RoleID', '2', '=' );
})
),
Field::inst( 'PersonID' ),
Field::inst( 'FName' ),
Field::inst( 'RoleID')
)
)
->process($_POST)
->json();
[How-To] Install DataTables with Meteor JS + Bootstrap 3
Hi, I decided to write about the process how I successfully installed DataTables with MeteorJS.
In my case :
- Meteor version 1.4.3.2 (as for March 2017)
- Installed via npm
- Bootstrap 3 - Note that, I'm not using the default styling
DataTables is a jQuery plugin, thus, there's a trick to bind the plugin with the existing jQuery that comes with Meteor. I'm using import
as this example is in ES6.
Installation
Step 1 :
Install DataTable core via npm : npm install --save datatables.net
Step 2 :
Install DataTable Bootstrap via npm : npm install --save datatables.net-bs
Step 3 :
Import datatable core and datatable bootstrap into you file. For example, you can write like this :
import datatables from 'datatables.net';
import datatables_bs from 'datatables.net-bs';
import 'datatables.net-bs/css/dataTables.bootstrap.css';
The third line is where I import the css for datatable bootstrap.
Step 4 :
Bind the "plugin" with jQuery, within the .onCreated(...)
block :
datatables(window, $);
datatables_bs(window, $);
If you're working inside the body template, then, the code will look something like this :
Template.body.onCreated(function(){
datatables(window, $);
datatables_bs(window, $);
// rest of your code
});
Usage
Let's say this happen inside your body template (body tag).
HTML :
<body>
<table id="mytable" class="table table-hover table-bordered">
<thead>
<tr>
<th>Column Header 1</th>
<th>Column Header 2</th>
<th>Column Header 3</th>
<th>Column Header 4</th>
</tr>
</thead>
</table>
</body>
I recommend that we do the init inside .onRendered(...)
block :
Template.body.onRendered(function(){
var data = [
['Data 1', 'Data 2', 'Data 3', 'Data 4'],
['Data 1', 'Data 2', 'Data 3', 'Data 4']
];
$('#mytable').DataTable({
data : data
});
});
That's all. It should be working now
The one polish font makes problem, why?
We have noticed that EditTable does not support our Polish fonts, the Ć font in particular, you can create Ć using the right Alt + C on polish keyboard. Our other fonts (ś,ń,ó,ł,ż,ź,ę,ą) work correctly. What may be the reason? You can find this problem in your example too. https://editor.datatables.net/examples/extensions/keyTable.html
Any suggestions?
Does editor work with nonstandard named id columns in database.
We're using a mix of virtuemart and custom tables none of which of a standard id field. Does the PHP editor instance posess the ability to use the customs like virtuemart_product_id and pid?
dataTables editor plugin DateTime format issue
I'm using EF6 + MVC for a site. The dataTables editor is used for an UI. One table has a field 'StartDate'. It is a datetime type in the SQL Server.
It works fine until when I try to edit the 'StartDate' value. From the browser debug, I can see that the JSON send from backend to UI is in the timestamp format, i.e. /Date(1541923200000)/ .
In the dataTables, I convert this to the correct local datetime format, so it shows correctly.
However, I could not figure out how to do this in Editor. It always shows the /Date(1541923200000)/ .
The code I use is:
editorAdvertisement = new $.fn.dataTable.Editor({
ajax: '/APN/GetAdvertisementData',
table: "#tblAdvertisements",
fields: [{
label: "StartDate",
name: "AdvStartDate"
, type: "datetime"
, format: 'MM\/DD\/YYYY h:mm a'
}, {
label: "Deadline",
name: "AdvDeadline"
, type: "datetime"
}, {
label: "TitleOfAdv",
name: "TitleOfAdv"
}, {
label: "ListPrice",
name: "ListPrice"
}
]
});
var tbl = $('#tblAdvertisements').DataTable({
pageLength: 10,
dom: '<"html5buttons"B>lTfgitp',
ajax: '/APN/GetAdvertisementData'
,
columns: [
{
data: "AdvStartDate", name: "AdvStartDate"
, type: "datetime"
, render: function (value) {
var r = convertDate(value);
return r;
}
, "autoWidth": true
},
{
data: "AdvDeadline", name: "AdvDeadline"
, type: "datetime"
, render: function (value) {
var r = convertDate(value);
return r;
}
, "autoWidth": true
},
{ data: "TitleOfAdv", name: "TitleOfAdv", "autoWidth": true },
{
data: "ListPrice", name: "ListPrice", "autoWidth": true
, render: $.fn.dataTable.render.number(',', '.', 0, '$')
}
],
order: [1, 'asc'],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [
{ extend: "create", editor: editorAdvertisement }
, { extend: "edit", editor: editorAdvertisement }
, { extend: "remove", editor: editorAdvertisement }
]
, select: true
, searching: false
, paging: false
});
In the controller
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult GetAdvertisementData()
{
var request = HttpContext.Request.Form;
var settings = Properties.Settings.Default;
using (var db = new Database(settings.DbType, settings.DbConnection))
{
var response = new Editor(db, "Advertising", new[] { "AdvertisingID" })
.TryCatch(false)
.Model<Advertising2>()
.Field(new Field("AdvStartDate")
.Validator(Validation.DateFormat(
"MM/dd/yyyy",
new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
))
.GetFormatter(Format.DateTime("yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy"))
.SetFormatter(Format.DateTime("MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss"))
)
.Field(new Field("AdvDeadline")
.Validator(Validation.DateFormat(
"MM/dd/yyyy",
new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
))
.GetFormatter(Format.DateSqlToFormat("MM/dd/yyyy"))
.SetFormatter(Format.DateFormatToSql("MM/dd/yyyy"))
)
.Field(new Field("TitleOfAdv"))
.Field(new Field("ListPrice"))
.Process(request)
.Data();
return Json(response, JsonRequestBehavior.AllowGet);
}
}
How to fix this?
Datatable pagination does not appear properly
I followed the example found here: https://datatables.net/examples/styling/bootstrap.html
I tried it on Google Chrome, Mozilla Firefox and even Internet Explorer.
Also, I am using the same version of (Bootstrap, JQuery and Datatables). It works but, unfortunately, the pagination under the table does not appear properly (It looks like a sequence of page links rather than page buttons [See the attached figure])
Could you help me?