I know that for a select input type it is : $('select', editor.field('myselect').node()).change( function () { but I don't know how to adapt it for a date field.
How to catch a change on a date input field in the editor ?
Sorting Server Side
I would like to apply my sorting on the server, we cannot forward the sorting through JavaScript
The following code does not work because the Row count gets the same ORDER BY clause as the select statement used to fetch the data.
SELECT COUNT( id ) as cnt, FROM data_relations_view ORDER BY Rel_code ASC
This is the code i am currently using:
[Datatables.Editor].Where(x => {
x.Order(sort.Column + " " + sort.Order);
});
Is there any workaround / solution available to get rid of this issue?
columns.render
I have a table which has two columns where the data is serialized. I use a custom function to unserialize the data, and when the table loads all is as it should be. But when I submit an edit I encounter a problem. The database is updated but the edit for doesn't disappear and the spinner displays forever as if the form is waiting for something. I can see that the ajax call returns a correctly formatted json so I am assuming that the render function doesn't like something. (The form works as expected if I populate the field without using render). Does anyone see anything wrong with what I'm doing?
This is the javascript:
function unserialize(data) {
// discuss at: http://phpjs.org/functions/unserialize/
// original by: Arpad Ray (mailto:arpad@php.net)
// improved by: Pedro Tainha (http://www.pedrotainha.com)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Chris
// improved by: James
// improved by: Le Torbi
// improved by: Eli Skeggs
// bugfixed by: dptr1988
// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// revised by: d3x
// input by: Brett Zamir (http://brett-zamir.me)
// input by: Martin (http://www.erlenwiese.de/)
// input by: kilops
// input by: Jaroslaw Czarniak
// note: We feel the main purpose of this function should be to ease the transport of data between php & js
// note: Aiming for PHP-compatibility, we have to translate objects to arrays
// example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
// returns 1: ['Kevin', 'van', 'Zonneveld']
// example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
// returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}
"use strict";
var utf8Overhead = function(chr) {
// http://phpjs.org/functions/unserialize:571#comment_95906
var code = chr.charCodeAt(0);
if ( code < 0x0080
|| 0x00A0 <= code && code <= 0x00FF
|| [338,339,352,353,376,402,8211,8212,8216,8217,8218,8220,8221,8222,8224,8225,8226,8230,8240,8364,8482].indexOf(code)!=-1)
{
return 0;
}
if (code < 0x0800) {
return 1;
}
return 2;
};
var read_until = function(data, offset, stopchr) {
var i = 2,
buf = [],
chr = data.slice(offset, offset + 1);
while (chr != stopchr) {
if ((i + offset) > data.length) {
}
buf.push(chr);
chr = data.slice(offset + (i - 1), offset + i);
i += 1;
}
return [buf.length, buf.join('')];
};
var read_chrs = function(data, offset, length) {
var i, chr, buf;
buf = [];
for (i = 0; i < length; i++) {
chr = data.slice(offset + (i - 1), offset + i);
buf.push(chr);
length -= utf8Overhead(chr);
}
return [buf.length, buf.join('')];
};
var _unserialize = function(data, offset) {
var dtype, dataoffset, keyandchrs, keys, contig,
length, array, readdata, readData, ccount,
stringlength, i, key, kprops, kchrs, vprops,
vchrs, value, chrs = 0,
typeconvert = function(x) {
return x;
};
if (!offset) {
offset = 0;
}
dtype = (data.slice(offset, offset + 1))
.toLowerCase();
dataoffset = offset + 2;
switch (dtype) {
case 'i':
typeconvert = function(x) {
return parseInt(x, 10);
};
readData = read_until(data, dataoffset, ';');
chrs = readData[0];
readdata = readData[1];
dataoffset += chrs + 1;
break;
case 'b':
typeconvert = function(x) {
return parseInt(x, 10) !== 0;
};
readData = read_until(data, dataoffset, ';');
chrs = readData[0];
readdata = readData[1];
dataoffset += chrs + 1;
break;
case 'd':
typeconvert = function(x) {
return parseFloat(x);
};
readData = read_until(data, dataoffset, ';');
chrs = readData[0];
readdata = readData[1];
dataoffset += chrs + 1;
break;
case 'n':
readdata = null;
break;
case 's':
ccount = read_until(data, dataoffset, ':');
chrs = ccount[0];
stringlength = ccount[1];
dataoffset += chrs + 2;
readData = read_chrs(data, dataoffset + 1, parseInt(stringlength, 10));
chrs = readData[0];
readdata = readData[1];
dataoffset += chrs + 2;
if (chrs != parseInt(stringlength, 10) && chrs != readdata.length) {
}
break;
case 'a':
readdata = {};
keyandchrs = read_until(data, dataoffset, ':');
chrs = keyandchrs[0];
keys = keyandchrs[1];
dataoffset += chrs + 2;
length = parseInt(keys, 10);
contig = true;
for (i = 0; i < length; i++) {
kprops = _unserialize(data, dataoffset);
kchrs = kprops[1];
key = kprops[2];
dataoffset += kchrs;
vprops = _unserialize(data, dataoffset);
vchrs = vprops[1];
value = vprops[2];
dataoffset += vchrs;
if (key !== i)
var contig = false;
readdata[key] = value;
}
if (contig) {
array = new Array(length);
for (i = 0; i < length; i++)
array[i] = readdata[i];
readdata = array;
}
dataoffset += 1;
break;
default:
break;
}
return [dtype, dataoffset - offset, typeconvert(readdata)];
};
return _unserialize((data + ''), 0)[2];
}
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function()
{
"use strict";
editor = new $.fn.dataTable.Editor
(
{
table: "#example",
fields:
[
{
label: "First Name:",
name: "m_first_name.meta_value"
},
{
label: "Last Name:",
name: "m_last_name.meta_value"
},
{
label: "Auto EOT:",
name: "m_auto_eot_time.meta_value"
} ],
ajax:
{
edit: "edit-lastname.php?id=_id_"
}
}
);
$('#example').DataTable
(
{
dom: "Bfrtip",
ajax: "users.php",
type: 'POST',
columns:
[
{ data: "ul.ID", className: "dt-body-center" },
{
data: "m_user_capabilities.meta_value",
className: "dt-body-center",
render : function ( data )
{
var $user_capabilities = unserialize( data );
var $user_level = 'Undefined';
if ($user_capabilities.subscriber)
{ // a whole series of tests go here
return $user_level;
}
},
{ data: "m_first_name.meta_value", className: "dt-body-center" },
{ data: "m_last_name.meta_value", className: "dt-body-center" },
{
data: "m_custom_fields.meta_value",
className: "dt-body-center",
render : function ( data )
{
var $business_name = unserialize( data ).business_name;
if ($business_name === undefined || $business_name === null)
{
return '';
}
else
{
return $business_name;
}
}
},
{ data: "m_subscriber_id.meta_value", className: "dt-body-center" },
{ data: "m_auto_eot_time.meta_value" , editField: "m_auto_eot_time.meta_value", className: "dt-body-center" }
],
select: true,
buttons:
[
{ extend: "edit", editor: editor }
]
}
);
});
I can see the JS throws an uncaught exception: out of memory.
Any help would be much appreciated.
Column set to Orderable False shows sorting icon until a column that is orderable is clicked on
Environment: DataTables version 1.10.10 and Editor 1.5.4, Server side processing using the Editor PHP libraries
I am trying to create a table with a custom order by statement that is set from within the script but does not allow the user to select or change the ordering.
Following is what I have been able to achieve, but it is not perfect.
If the following function is used it generates an Invalid JSON response.
ordering: false
The first part of the JSON response include the following data:
<br />
<b>Notice</b>: Undefined index: order in <b>../Editor.php</b> on line <b>1171</b><br />
I determined that the request string did NOT include the following sections
order[0][column]=0
order[0][dir]=asc
If the following line is added to the javascript, the request string still does not include the order sections and generates an Invalid JSON response..
order:[[1,'asc'],[0,'asc']]
Instead of using the ordering:false setting I used the columns attribute to turn off ordering and kept the order statement, this produced the desired results except that the class for the header is set to sorting_asc when it should be set to sorting_disabled, and as such displays a sorting triangle to the right of the column title.
columns: [
{ data: "CPRT_STREET_NO",
orderable: false },
{ data: "CPRT_STREET",
orderable: false }
],
order:[[1,'asc'],[0,'asc']]
So my question is how do I correct the class of the header?
Note: If the first column is set to orderable:false and the second column is set to orderable:true the header when first created will set the class of the first column to sorting_asc and after the second header is selected the first header will have it's class changed to sorting_disabled with the subsequent removal of the up or ascending triangle next to the column header title.
Getting checkbox in Editor
I have a column of data 1,2,3 and each of the number represent different equipment. I would like to show the equipment in a list of checkboxes when user create a new record. How can I display the list of the equipment on the editor?
Appreciate for your help.
After Editor create, how to apply sort?
Not sure how to best create example for this, but will try if necessary. I suspect this is an easy answer without an example needed.
I tried using fixedOrder for the column I'm interested in, but after the create the new row is at the bottom of the table. Note I have ordering: false
for this table, which I think turns off user's ability to change the order. But I want the table shown in a particular order.
On a side issue, it would be nice (and make for more maintainable code) if column name could be given rather than index for order
and fixedOrder
options.
How to achieve autocomplete for the dropdown present in datatable editor?
I have tried various methods of implementation but have been unsuccessful as i was getting errors. Please can u show me an example for the same..
Thanks
Exit gracefully from Editor's PHP preRemove function
Hi,
I am using PHP libraries for Editor. I am using the 'on preRemove' function to run some checks before the delete (remove) actually occurs, and in some cases i want to exit back to the caller gracefully WITHOUT actually performing the delete.
Is this possible?
Richard
Non mapped property on Model
I'm using the .Net library, and have many editors up and running fine.
Now, I want to have a property on one of my returned models that depends on 3 columns in the table. I can return the 3 columns fine into my model. I want to have property on my model that is not mapped to a database table, but for example checks ColumnX > 5 AND ColumnY == true AND ColumnZ >= current date.
Very easy to do in C#, but not sure how to make sure that property is not picked up by _FieldFromModel and added on to the query.
hope that makes sense.
select2 plug-in selected property
I can select options and save data. However, when I load the editor, the selected values for a given record are not indicated. If I change the field type to a checkbox, the correct checkboxes are checked when the editor form loads. What needs to be done in order to get selected values for the select2 field type?
ajax.reload
I have a page with 2 datatables, one (parent) acting as filter for another (child).
what i want to do is on editing the child table, the parent data is reloaded.
I can do this with
setInterval( function () {
pagestable.ajax.reload(null, false);
}, 3000 );
which reloads every 3 seconds
if i try
editor
.on( 'postCreate postEdit postRemove', function () {
pagestable.ajax.reload( null, false );
});
nothing happens, the function is not triggered
New Row, DOM only
I want to add new rows only to the DOM....I don't want an ajax call. Same for edit. I see that I could override the ajax call with my own function, but I'd rather not have to write the logic for the insertions. Can this be done?
ck editor config
probably simple, but how do i configure the toolbar on the ckeditor editor plugin?
i have a config.js file but changing it doesn't seem to make any difference.
Cant seem to find an example
can i do this directly with ...
type: "ckeditor",
opts: "{}"
can i point to a js file within opts, or key in the values ?
How do i set focus to select2?
I need to focus on a control select2 which allows me to enter text immediately
JSP add on for Editor
Has anyone been able to get this to work in JSP ... if so is there examples some where i can look in order to implement it.
Thank you,
Brendon
How to set up selectize options when using Editor
Reference http://codepen.io/louking/pen/adQMaP
I want to have a select field in create and update which has a set of items, but also allows the user to type in something new. I thought select2 or selectize would support this. However, I am having trouble getting to square one.
My example is with selectize, When user clicks New I want col0 to have a select pulldown with the options in optvalues
, and to be able to type in the field to find matching options. I've tried optvalues
in this format, and just a simple array, and with array of objects {'label':xx, 'value':yy}
without success.
var data = []
for (i = 1; i < 4; i++) {
data.push({
id: i,
a: 'a' + i,
b: 'b' + i,
c: 'c' + i
})
}
var optvalues = [
['aaaa', 'aaaa'],
['bbbb', 'bbbb'],
['ccaa', 'ccaa'],
];
var editor = new $.fn.dataTable.Editor({
table: '#tbl',
idSrc: 'id',
fields: [
{ label: 'col0', name: 'col0',
type: 'selectize', options: optvalues,
},
{ label: 'col1', name: 'col1' },
{ label: 'col2', name: 'col2' },
],
} );
var table = $('#tbl')
.DataTable({
dom: 'lBfrtip',
data: data,
columns: [
{
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{ data: 'a', className: 'dt-body-center' },
{ data: 'b', className: 'dt-body-center' },
{ data: 'c', className: 'dt-body-center' }
],
select: true,
buttons: [
{ extend: 'create', editor: editor },
],
});
<table id=tbl>
<thead>
<tr>
<th></th>
<th>col0</th>
<th>col1</th>
<th>col2</th>
</tr>
</thead>
</tbody>
</table>
New Editor Fail!
I upgraded my Editor libraries to take advantage of mjoin.
After doing that, mjoin works great for display, however, none of my tables can edit at all anymore.
Even if I back out the code to all working before mjoin, and then I just replace the libraries, the new ones make any in-line edit return empty data with no updates to the database. Switch the libs back and all is working again.
What is going on?
<?php $siteRoot = substr(__FILE__, 0, -strlen($_SERVER['SCRIPT_NAME']));
include $siteRoot.'/login/include/datatables/php/lib/DataTables.php';
use DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Join,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
Editor::inst($db, 'Booked_Trips', 'TripID')
->field(
Field::inst('TripID'),
Field::inst('OrderID'),
Field::inst('NumPass'),
Field::inst('NumBags'),
Field::inst('CostTip'),
Field::inst('Name'),
Field::inst('PickupTime'),
Field::inst('PickupLocation'),
Field::inst('DropoffLocation'),
Field::inst('VehicleType'),
Field::inst('CostTrip'),
Field::inst('CostExtras'),
Field::inst('CostTax'),
Field::inst('CostTotal'),
Field::inst('Mileage'),
Field::inst('Duration'),
Field::inst('Tolls'),
Field::inst('MapLink'),
Field::inst('Status')
)
->where('OrderID', $_REQUEST['order'], '=')
->process( $_POST )
->json();
The above works for display with either library, but only works for editing with the old library. How can I fix this?
File Upload
Is there a way to upload the file when the form is submitted, as opposed to immediately uploading the file when it is selected? Would I need to write a custom editor.fieldType
to handle this? If so, how would I go about implementing the get
method so that editor will send the file(s) along with the rest of the form data?
Thanks,
Kurt
Undefined index error on AJAX call on Datatable Editor when I use upload file feature
Hi Allan,
i´ve used send data function previously on AJAX call (below on code) without problems on Datatable Editor, but now I´m using upload file feature on v.1.5.4. appear an error:
"Notice: Undefined index: site in /home/tripntry/www/x.samples/datateditor154/examples/php/upload.php on line 12"
If I remove the function - call to ajax without data values - it works , but I need pass the data value "site". Same error on v.1.5.1. Also I´ve used other way to send data , but same error (sintax in code) .You can to see live example on : http://tripntry.com/x.samples/datateditor154/examples/advanced/upload.v1.html
Any idea?. Thank you in advance!!. Eduardo
function id_establecimiento(results){
var id_estblecmto = localStorage.getItem('establecimiento');
return id_estblecmto
};
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/upload.php",
ajax: {
url:"../php/upload.php",
type: "POST",
//data: {site : '342800010'}, //same index error
data: function ( d ) {
d.site = id_establecimiento(); //get id (site) after login
}
},
table: "#example",
fields: [
{
label: "Nombre (establecimiento):",
name: "nom_estbl",
status: "This field is required"
},
{
label: "Telefono:",
name: "telefono",
status: "This field is required"
},
{
label: "E-mail (establecimiento):",
name: "email_estbl",
status: "This field is required"
},
{
label: "Nº de Plazas:",
name: "num_plaz",
status: "This field is required"
},
{
label: "Precio medio:",
name: "prec_med"
},
{
label: "Site (ID):",
name: "site",
type: "readonly",
def: id_establecimiento,
},
{
label: "Image:",
name: "image",
type: "upload",
display: function ( file_id ) {
return '<img src="'+table.file( 'files', file_id ).web_path+'"/>';
},
clearText: "Clear",
noImageText: 'No image'
}
]
} );
var table = $('#example').DataTable( {
dom: "Bfrtip",
//ajax: "../php/upload.php",
ajax: {
url:"../php/upload.php",
type: "POST",
//data: {site : '342800010'}, //same index error
data: function ( d ) {
d.site = id_establecimiento(); //get id (site) after login
}
},
columns: [
{ data: "nom_estbl" },
{ data: "telefono" },
{ data: "email_estbl" },
{ data: "num_plaz" },
{ data: "prec_med" },
{
data: "image",
render: function ( file_id ) {
return file_id ?
'<img src="'+table.file( 'files', file_id ).web_path+'"/>' :
null;
},
defaultContent: "No image",
title: "Image"
}
],
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
} );
Server side (upload.php)
// DataTables PHP library
include( "../../php/DataTables.php" );
//$site="342800010";
$site=$_POST['site']; //here point the error!!!
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Join,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'r_clientes' )
->fields(
Field::inst( 'nom_estbl' ),
Field::inst( 'telefono' ),
Field::inst( 'email_estbl' ),
Field::inst( 'num_plaz' ),
Field::inst( 'prec_med' ),
Field::inst( 'site' ),
Field::inst( 'image' )
->setFormatter( 'Format::ifEmpty', null )
->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/upload/__ID__.__EXTN__' )
->db( 'files', 'id', array(
//'site' =>$site,
'filename' => Upload::DB_FILE_NAME,
'filesize' => Upload::DB_FILE_SIZE,
'web_path' => Upload::DB_WEB_PATH,
'system_path' => Upload::DB_SYSTEM_PATH
) )
->validator( function ( $file ) {
return$file['size'] >= 3500000 ?
"Files must be smaller than 3500K o 3,5 Mb" :
null;
} )
//delete orphan files. INICIO
->dbClean( function ( $data ) {
// Remove the files from the file system
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
unlink( $data[$i]['system_path'] );
}
// Have Editor remove the rows from the database
return true;
} )
//delete orphan files. FIN
->allowedExtensions( array( 'png', 'jpg', 'gif' ), "Please upload an image" )
)
)
->where( 'site', $site)
->process( $_POST )
->json();
How to make 'error' display visible?
I have successfully received fieldErrors
at the browser and displayed them, but have been unable to get error
to work.
When the server transmits json {data: [], error: "Unknown error occurred: invalid id detected", fieldErrors: []}
, the create page just sits there without displaying the error message.
I'm not quite sure how to create this situation in a codepen, jsbin, etc.
But on review, this appears to be happening because of two settings.
Within editor.jqueryui.css, the footer is not being displayed.
div.DTE div.DTE_Footer {
display: none;
}
And opacity: 0
within the div
<div data-dte-e="form_error" class="DTE_Form_Error" style="opacity: 0; display: block;">Unknown error occurred: invalid id detected</div>
I assume I have to set some option to see the errors, but am not sure which one. Please advise.