Hello,
I am trying to use data-tables in my angular app using below one
https://l-lin.github.io/angular-datatables/#/getting-started
But its only giving me plain jquery style and couldnt integrate bootstrap with it.
Any help is appreciated.
Ruki
Couldnt integrate bootstrap, need help
Check for duplicate fileds in editor
I've read the discussion https://datatables.net/forums/discussion/12650/check-for-duplicates/p1.
My problem is that I have to compare two fields: the first of course I get from $ val but I did not understand how to get a second field.
Field::inst( 'contratti.con_date' ),
Field::inst( 'contratti.con_num' )
->validator( function($val, $data) {
global $db;
$res = $db
->sql('SELECT COUNT(*) as count FROM contratti WHERE con_num = '.$val.' AND con_date = .....');
$count = $res->fetch();
if($count !== 0){
return "Duplicate value ".$val."";
}
return true;
}
File upload not working with two Editors on same page
One of the tables used in my application has a large number of fields, including two fields used to hold references to file uploads (one an image the other a pdf). Because the number of fields is large, I'm using multiple tabs to segregate the data into reasonable size chunks. Each tab has its own editor to handle the data within that tab. Works well, but I've run into an issue when uploading image and pdf files.
One of the editors ends up referencing the incorrect set of files when attempting to open the editor. I've created a fairly easily replication of the problem starting with the Editor sample upload.html/php. To reproduce, do the following:
Add another column to the users table as pdf int default NULL, and recreate the sample database.
Copy upload.html to uploadTest.html and modify contents as follows:
<snip><snip><snip>
var editor1; // use a global for the submit and return data rendering in the examples
var editor2; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor1 = new $.fn.dataTable.Editor( {
ajax: "../../controllers/uploadTestImage.php",
table: "#editor1",
fields: [ {
label: "Last name:",
name: "last_name"
}, {
label: "Image:",
name: "image",
type: "upload",
display: function ( file_id ) {
return '<img src="'+editor1.file( 'files', file_id ).web_path+'"/>';
},
clearText: "Clear",
noImageText: 'No image'
}
]
} );
var table = $('#editor1').DataTable( {
dom: "Bfrtip",
ajax: "../../controllers/uploadTestImage.php",
columns: [
{ data: "last_name" },
{
data: "image",
render: function ( file_id ) {
return file_id ?
'<img src="'+editor1.file( 'files', file_id ).web_path+'"/>' :
null;
},
defaultContent: "No image",
title: "Image"
}
],
select: true,
buttons: [
{ extend: "create", editor: editor1 },
{ extend: "edit", editor: editor1 },
{ extend: "remove", editor: editor1 }
]
} );
editor2 = new $.fn.dataTable.Editor( {
ajax: "../../controllers/uploadTestPDF.php",
table: "#editor2",
fields: [ {
label: "Last name:",
name: "last_name"
}, {
label: "PDF:",
name: "pdf",
type: "upload",
display: function ( file_id ) {
return '<img src="'+editor2.file( 'files', file_id ).web_path+'"/>';
},
clearText: "Clear",
noImageText: 'No image'
}
]
} );
var table = $('#editor2').DataTable( {
dom: "Bfrtip",
ajax: "../../controllers/uploadTestPDF.php",
columns: [
{ data: "last_name" },
{
data: "pdf",
render: function ( file_id ) {
return file_id ?
'<img src="'+editor2.file( 'files', file_id ).web_path+'"/>' :
null;
},
defaultContent: "No PDF",
title: "PDF"
}
],
select: true,
buttons: [
{ extend: "create", editor: editor2 },
{ extend: "edit", editor: editor2 },
{ extend: "remove", editor: editor2 }
]
} );
} );
</script>
</head>
<body class="dt-example php">
<div class="container">
<section>
<h1>Editor example <span>File upload</span></h1>
<div class="info">
<p>This example shows Editor being used with the <a href="//editor.datatables.net/reference/field/upload"><code class="field" title=
"Editor field type">upload</code></a> fields type to give end users the ability to upload a file in the form. The <a href=
"//editor.datatables.net/reference/field/upload"><code class="field" title="Editor field type">upload</code></a> field type allows just a single file to be
uploaded, while its companion input type <a href="//editor.datatables.net/reference/field/uploadMany"><code class="field" title=
"Editor field type">uploadMany</code></a> provides the ability to have multiple files uploaded for a single field.</p>
<p>The upload options of Editor are extensively documented in the manual (<a href="//editor.datatables.net/manual/upload">Javascript</a>, <a href=
"//editor.datatables.net/manual/php/upload">PHP</a>, <a href="//editor.datatables.net/manual/net/upload">.NET</a> and <a href=
"//editor.datatables.net/manual/node/upload">NodeJS</a>) and details the various options available.</p>
<p>In this example an image file can be uploaded, limited to 500KB using server-side validation. To display the image a simple <code class="tag" title=
"HTML tag">img</code> tag is used, with information about the file to be displayed retrieved using the <a href=
"//editor.datatables.net/reference/api/file()"><code class="api" title="Editor API method">file()</code></a> method which Editor makes available and is
automatically populated based on the server-side configuration.</p>
</div>
<div class="demo-html"></div>
<table id="editor1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Last name</th>
<th>Image</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Last name</th>
<th>Image</th>
</tr>
</tfoot>
</table>
<table id="editor2" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Last name</th>
<th>PDF</th>
</tr>
</thead>
<tfoot>
<tr>
<th>PDF</th>
<th>Image</th>
</tr>
</tfoot>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<snip><snip><snip>
Then, copy upload.php to uploadTestImage.php and change as follows:
<?php
/*
* Example PHP implementation used for the index.html example
*/
// DataTables PHP library
include( "../lib/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;
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'users' )
->fields(
Field::inst( 'last_name' ),
Field::inst( 'image' )
->setFormatter( Format::ifEmpty( null ) )
->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/uploads/__ID__.__EXTN__' )
->db( 'files', 'id', array(
'filename' => Upload::DB_FILE_NAME,
'filesize' => Upload::DB_FILE_SIZE,
'web_path' => Upload::DB_WEB_PATH,
'system_path' => Upload::DB_SYSTEM_PATH
) )
->validator( Validate::fileSize( 500000, 'Files must be smaller that 500K' ) )
->validator( Validate::fileExtensions( array( 'png', 'jpg', 'jpeg', 'gif' ), "Please upload an image" ) )
)
)
->process( $_POST )
->json();
Similarly, copy upload.php to uploadTestPDF.php and changes a follows:
<?php
/*
* Example PHP implementation used for the index.html example
*/
// DataTables PHP library
include( "../lib/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;
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'users' )
->fields(
Field::inst( 'last_name' ),
Field::inst( 'pdf' )
->setFormatter( Format::ifEmpty( null ) )
->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/uploads/__ID__.__EXTN__' )
->db( 'files', 'id', array(
'filename' => Upload::DB_FILE_NAME,
'filesize' => Upload::DB_FILE_SIZE,
'web_path' => Upload::DB_WEB_PATH,
'system_path' => Upload::DB_SYSTEM_PATH
) )
->validator( Validate::fileSize( 500000, 'Files must be smaller that 500K' ) )
->validator( Validate::fileExtensions( array( 'pdf' ), "Please upload a PDF file" ) )
)
)
->process( $_POST )
->json();
Now you're ready to test. Load the uploadTest.html and you should see two tables, each with two columns. First table has Last Name and Image columns, second table has Last Name and PDF columns. All good to this point.
Next, select first record in first table, then Edit first table, and upload any image. This is good.
Then, select second record in second table, then Edit second table, and upload any PDF. This works too.
Next, refresh the page. Image and PDF are there. That's good.
Now select the first record in first table, and then Edit first table. Doesn't work. Edit button just shows spinning cursor. I poked around down into DataTables.editor.min.js:105 -- and wrong array of files seems to be there (array from second editor, not first one).
If you refresh the page, select the second record in the second table, and then Edit, everything works okay.
Somewhere along the way, the list of files used for each editor is getting out of synch.
Note, I am using DataTables 1.10.18 and Editor 1.8.1 for both my own application, and for the example that I reproduced above.
Also, I did make the change you outlined in this fix from this issue to editor.php, but the problem still exists for me.
Problem reloading DataTable
I'm having trouble reloading the datatable. I used fetch api to dynamically fill my table. And the problem is, when I'm doing add, edit, or delete, the database updates, but the datatable does not. When I search, sort, or change page, the data inside the table reverts to the old one. And when I refresh the page, that's the time when the datatable becomes updated. I use express JS for the backend.
Here's my code:
Code Snippet for the initialization of datatable
$(document).ready(function(){
fillTable();
})
//fetch api (AJAX) to fill table
fillTable = () => {
fetch('http://localhost:3000/home.json')
.then(response => response.json())
.then(data => {
for (i = 0; i < data.length; i++){
html += '<tr>'+
'<td class="tdUsername pv3 w-35 pr3 bb b--black-20">'+ data[i].username + '</td>'+
'<td class="tdPassword pv3 w-35 pr3 bb b--black-20">'+ data[i].password + '</td>'+
'<td class="pv3 w-30 pr3 bb b--black-20">'+
'<div class="btn-group" role="group" aria-label="Basic example">'+
'<a class="editButton f6 grow no-underline ba bw1 ph3 pv2 mb2 dib black pointer" data-toggle="modal">EDIT</a>'+
'<a class="deleteButton f6 grow no-underline ba bw1 ph3 pv2 mb2 dib black pointer" data-toggle="modal">DELETE</a>'+
'</div>'+
'</td>'+
'</tr>'
}
$('#tblBody').html(html);
$('#user').DataTable(); //DataTable initialization
})
.catch(err => console.log("ERROR!: ", err))
}
Here's the code snippet for adding users
addUserToDB = () => {
fetch('http://localhost:3000/addUser', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username: user.value,
password: pass.value
})
})
.then(response => response.json())
.then(user => {
if(user.username){
$("#addModal").modal('hide');
$("#showConfirm").modal('toggle');
fillTable(); // I call the function to refresh the table
$('#addModal').on('hidden.bs.modal', function () {
$(this).find("input").val('').end();
});
} else {
window.alert('USER ALREADY EXIST!');
}
})
.catch(err => console('ERROR!: ', err))
}
Metro UI and DataTables select
When using Metro UI and Datatables select, when a row is selected, it is shifted to the right by one column.
Metro UI developer advised to write on this forum
Sample project
sorting, pagination not working
Hi,
the tables are working fine if i put hard coded data like th, td but sorting , pagination not working as soon as i use ngFor in my angular,
Any help appreciated.
Thank you
Basic understanding of API — table.$('td').addClass('tablecell');
Can someone explain why the second to last line here does not add a class of 'tablecell' to all my <td> elements?
$(document).ready(function() {
var table = $('#ratings-table').DataTable({
"ajax": 'table_senate_info.json',
"columns": [
{ "data": "ratingPhrase" },
{ "data": "state" },
{ "data": "fullName" },
{ "data": "trump_margin" },
{ "data": "firstName" },
{ "data": "lastName" },
{ "data": "raceRatingID" },
{ "data": "open_seat" }
],
"columnDefs": [
{ targets: [4, 5, 6, 7], visible: false },
{
"targets": 2,
"render": function(data, type, row) {
return data + ' (' + row.open_seat + ')';
}
},
{ "orderData": 5, "targets": 2 },
{ "orderData": [6, 5], "targets": 0 }
],
renderer: "bootstrap",
responsive: "true",
});
table.$('td').addClass('tablecell');
});
Problems with change of columns when server side processing after reload of datatable
Hello to forum,
Please, I have big trouble with colReorder with serverSide processing and use stateSave.
What is the problem?
If I made the initial load of dataTable by click to fetch Data button it looks OK, The sorting is OK, and the functions which change teh data in the field to anchor work fine and in console I see that it call only one saveState for save the state into DB. When I change the Column position for example id from 1st position to 3rd position after invoice number, it looks OK, but is call the stateSave two times.
But When I call the fetch Data by the button again, then the column name change position to basic position and the data stay on the new position, Unfortunately the function for change the data to anchor not change the right column, but the column by the column name, not by the column with right data. How it looks? The data with ID are in 3rd column, but the column name ID is on top of 1st column. even I see that loadState is called one time and saveState is called two times.
OK, So i try to push the button again and the name of column with ID changed the position to 2nd column and the data is still on 3rd. loadState called only one time, saveState called 2 times. When I click on the button fetchData the ID name of column move to 3rd column and function at this time run correctly and change the data to anchor. The loadState called only one time, saveState called two times again.
Please, can you help me with this? I can to find what I do bad.
Shall I run the script with debug script with write the resolution into DB?
Thanks a lot for help
Honza H
Filtering columns in Datatables as used in AdminLTE
I'm building a Laravel app with AdminLTE integrated in the backend. AdminLTE uses DataTables to generate the tables, this works fine. But in AdminLTE it's only possible to sort columns, and it's not possible to filter columns. In one admin view I want to filter columns with a dropdown as shown in this DataTables example. I've tried to integrate the example code in AdminLTE file main.js. But I haven't got it working. In main.js there is a codesnippet where probably the new code should or could be integrated.
$('.datatable').each(function () {
if ($(this).hasClass('dt-select')) {
window.dtDefaultOptions.select = {
style: 'multi',
selector: 'td:first-child'
};
window.dtDefaultOptions.columnDefs.push({
orderable: false,
className: 'select-checkbox',
targets: 0
});
}
$(this).dataTable(window.dtDefaultOptions);
});
Does anyone have an idea how to get the filtering working?
Append text on top in a select list
In Datatables select lists the first row on the top is empty. Is it possible to put here a text for indicating to the user what is to be done? E.g. 'Select an option'.
Targeting a column filter if a column before is not visible
I recently asked this question:
This appeared to work - BUT if I have column visibility enabled and one of the columns before the above scenario of filtering the column are hidden then the target to reset the filter won't work because it is taking into account the invisible column in the numbering which I am referencing.
Is there a way to get this to work? I have tried targeting like this:
$('#example thead tr:eq(1) th:visible:eq('+column+') input').val('')
But this doesn't work - I need either a way of targeting visible inputs or to target the filter input css ID but I can't seem to be able to match the filter name e.g. #filter-customer on the input to the column number being passed back from column-visibility.dt
As my columns are in DataTables the ideal would be to get the column name back rather than the ID, anyway to do that?
I tried:
table.columns(column).name()
and
table.column(column).name()
with no luck.
Too much data for a cell, how to make readable?
Hey, I'm building a UI Builder interface, I'm implementing Datatables on it, but I found a problem that did not happen to me before
I could not upload a image of the problem, so theres a link:
https://i.imgur.com/UWtvKQ3.jpg
As you can see in the attached image, the data is not splitting into 2 lines so It can be readable, tried modifying the css and all..
These are my res:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-![](https://datatables.net/forums/uploads/editor/jv/wd3vifts23nx.jpg "")
MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.0.2/css/responsive.dataTables.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
<link rel="stylesheet" href="vendor/css/st.action-panel.css">
<link rel="stylesheet" href="vendor/css/style.css">
do you know what might be doing this?
Call initComplete on table.ajax.reload()
Due to special layout on my webpage I need to get the "recordsTotal" value in a function when I do a table.ajax.reload()
When I do my initial datatable init I have an initCompletefunction where I can get the value in "settings._iRecordsTotal"
But initComplete is not called on ajax.reload. Is there any way to pass the "settings._iRecordsTotal" value when you do a ajax.reload?
I have tried to do a callback function but can 't get i to work: this.$datatable.DataTable().ajax.reload( function(){
this.totalHitsRender();
alert('COME ON')
});
If I could only call my totalHItsRender() function like that....
Regarding alignment issue?
Hi @allan ,
I created a test case regarding the issue for alignment issue.
Please go through the steps below to replicate the issue:
--> Run this code in .
-->Select No1 field try to update it to any name (example ::
System Architectaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) and click outside of the table.
--> the header and body alignment came correctly.
Result in my application:
-->When i edit any field and insert so many characters (Example::
System Architectaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) and click outside.
--> In our case input field is expanding but header is not expanding, we are not using anything extra styles/css. How to resolve this issue.
--> we are using data table version-
datatables-1.10.19/js/jquery.dataTables.min.js
editor-1.8.0/js/dataTables.editor.min.js
editor-1.8.0/css/editor.bootstrap4.min.css
Please go through this updated link @allan
http://live.datatables.net/diyariwa/33/edit
Thanks,
Saidulu.
Disable Scroll To Next Row | Keytable stop scroll to next line | Stop scrolling to next row
Hi!
I'm using Keytable for excel-like navigation. My user wants to stop scrolling to next row once he reached the end of each row.
Currently, it is having continuous scroll if you press the right arrow key.
How to disable that?
Thanks for the help!
Datatables with tooltips
I have a table created which pulls information from mySQL and displays it on a web page. What I am interested in is adding a hover to a set of cells.;
All the elements in first column is meant to have a however which displays a date and a link to a web page.
I came across tooltip to achieve this, but just not able to figure out how do I go about this. Any suggestions?
Individual column search is not working with Horizontal scroll on (scrollX = true) at a time
I have table created column dynamically and bind JSON data to it using Jquery. Implement coumn search on Document.Ready function and column search working fine. but when I set scrollX= true to implement horizontal scroll and fixcolumn then horizontal scroll apply to table but column search stop working with it.
Can you guide me how to work together column search and horizontal scrollbar and fixcolumn together..
sample code
Column search
$j('#tblMasterList tfoot th').each(function () {
var title = $j(this).text();
$j(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
// DataTable
var table = $j('#tblMasterList').DataTable();
// Apply the search
table.columns().every(function () {
var that = this;
$j('input', this.footer()).on('keyup change', function () {
debugger;
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
var r = $j('#tblMasterList tfoot tr');
r.find('th').each(function () {
$j(this).css('padding', 8);
});
$j('#tblMasterList thead').append(r);
$j('#search_0').css('text-align', 'center');
DataTable binding with columns and JsonData
$j('#tblMasterList').DataTable({
data: jsondata,
columns: vCols,
scrollX: true
});
Editor alias for same table name?
I have this code in editor:
the problem is that it says i have same name for 'zcv_orders_details.data', can i set an alias or something?
Field::inst( 'zcv_orders_details.data' )->getFormatter( function ( $val, $data ) { return date( 'H:i d-m-Y', $val);})
Field::inst( 'zcv_orders_details.data' )->getFormatter( function ( $val, $data ) { return date( 'd-m-Y', $val);})
Full code:
// Build our Editor instance and process the data coming from _POST
$editor = Editor::inst( $db, 'zcv_orders_details', 'zcv_orders_details.id' )
->fields(
Field::inst( 'zcv_orders_details.id' ),
Field::inst( 'zcv_clients.firstname' ) ->validator( 'Validate::notEmpty' ),
Field::inst( 'zcv_clients.lastname' ) ->validator( 'Validate::notEmpty' ),
Field::inst( 'zcv_orders_details.data' )->getFormatter( function ( $val, $data ) { return date( 'H:i d-m-Y', $val);})
Field::inst( 'zcv_orders_details.data' )->getFormatter( function ( $val, $data ) { return date( 'd-m-Y', $val);})
)
->leftJoin( 'zcv_clients', 'zcv_clients.id', '=', 'zcv_orders_details.clients' );
if(isset($_POST['year'])){
$editor->where( 'FROM_UNIXTIME(zcv_orders_details.data, "%Y")', $_POST['year']);
}
if(isset($_POST['month'])){
$editor->where( 'FROM_UNIXTIME(zcv_orders_details.data, "%c")', $_POST['month']);
}
if(isset($_POST['sala'])){
$editor->where( 'zcv_orders_details.gyms', $_POST['sala']);
}
$editor
->process( $_POST )
->json();
Any idea is really apreciates.
AutoComplete AutoFocus Select 1st suggestion Select 1st Dropdown
In inline Editor, I managed to use autocomplete. It shows suggestion when keys are entered. My user would like to press on TAB and also click out of the cell, to submit the top suggestion (1st row autocomplete). Even if he entered e.g "A" and sugguestion shows "Apple, Ape, etc", Apple will be autofilled and submitted into database.
I have found autocomplete with autofocus solutions but could not make it work with Datatables.
Something like this for AutoComplete:
https://codepen.io/anon/pen/rVJyRO
http://api.jqueryui.com/autocomplete/#option-autoFocus
What syntax should I use?
AutoComplete AutoFocus Select 1st suggestion Select 1st Dropdown
In inline Editor, I managed to use autocomplete. It shows suggestion when keys are entered. My user would like to press on TAB and also click out of the cell, to submit the top suggestion (1st row autocomplete). Even if he entered e.g "A" and sugguestion shows "Apple, Ape, etc", Apple will be autofilled and submitted into database.
I have found autocomplete with autofocus solutions but could not make it work with Datatables.
Something like this for AutoComplete:
https://codepen.io/anon/pen/rVJyRO
http://api.jqueryui.com/autocomplete/#option-autoFocus
What syntax should I use?