datatable yadcf plugin init() not working - filter

i am using datatable with bootstrap3. i want to apply filter after button is clicked. but when i clicked button it gives me TypeError: oTable.settings is not a function error. my datatable version is 1.10.6 and yadcf version is 0.8.7
here is my code
function init_datatable(table_id, records) {
// console.log('init table',$.parseJSON(records));
var oTable = $(table_id).dataTable({
aaData: $.parseJSON(records),
"sPaginationType": "bootstrap",
"bFilter": false,
"bInfo": false,
"sPageButtonActive": "active",
"aaSorting": [[0, 'desc']],
"bDeferRender": true,
"sDom": '<"top"if>rt<"bottom"lp><"clear">',
"aLengthMenu": [
[10, 20, 30, 50, -1],
[10, 20, 30, 50, "All"] // change per page values here
],
"iDisplayLength": 10,
"oLanguage": {
"sEmptyTable": "No data available"
},
"aoColumnDefs": [{
"aTargets": [0],
"bVisible": false,
"bSearchable": false
},
{
"bSortable": false,
"aTargets": [-1], // <-- gets last column and turns off sorting
"mData": null,
"mRender": function(data, type, full) {
return '<a data-original-title="Edit" id="edit_' + full[0] + '" data-placement="top" class="btn btn-xs btn-teal tooltips edit" href="javascript:void(0)"><i class="fa fa-edit"></i> Edit</a>';
}
}]
});
// .yadcf([
// {column_number: 1}
// ]);
$(table_id + '_wrapper .dataTables_length select').addClass("m-wrap");
$(table_id + '_wrapper .dataTables_length select').select2();
return oTable;
}
here is code for apply column filter
var pTable = init_datatable('#tbl_sample', data);
function apply_column_filter() {
yadcf.init(pTable, [
{column_number: 1}
]);
}
commented code in "init_datatble function is working. but when i use init it gives me error

yadcf.init should be use only for the new API with the capital D and since you are not using the new API, you should use the following way to init yadcf
$(table_id).dataTable({
......
}).yadcf([......]);
See comments in the code snippets on the showcase
//----------------------------------------------
//Example on how to define a custom filter function
//this function is goinf to be passesd to yadcf as custom_func parameter value
//and going to be tested against each value in the column
//----------------------------------------------
b.t.w if you want to filter some column pragmatically you should use the
exFilterColumn function , see docs

You can still use "yadcf.init" by getting the table reference. And this is how can get the reference of a table:
var api = new jQuery.fn.dataTable.Api(settings);
var oTable = api.table();
yadcf.init(oTable, [ {}]);

Related

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

Updating value in jqGrid doesn't work when two columns use same field

I used the solution mentioned in How to update value of data in jqgrid to update data locally. It worked for me as shown in the first fiddle. In the "Action" column, there is button added conditionally, based on the data in "IsActive" column. If it is "true", a "Retire" button gets added as an action. If it is false, "Activate" button gets added. When the javascript function is called, the button changes to "Activate".
Fiddle 1
Now, I added another column to display the status value as text. Now, both "Status" column and "Action" column are utilizing the same data column - IsActive. After adding this column, the javascript function is not changing the button from "Retire" to "Activate".
Fiddle 2
What is the best way to fix this issue?
CODE
$(document).ready(function () {
function updateActiveStatus(rowid, isToActive) {
alert('function');
// first change the cell in the visible part of grid
$("#list").jqGrid('setCell', rowid, 'firstname', 'A');
// now change the internal local data
$("#list").jqGrid('getLocalRow', rowid).firstname = 'A';
$("#list").jqGrid('setCell', rowid, 'IsActive', false);
$("#list").jqGrid('getLocalRow', rowid).IsActive = false;
}
var myData = [
{ "id": "35", "firstname": null, "codeval": "G", "note": "xx7866", "amount": "23", "IsActive": true },
{ "id": "73", "firstname": null, "codeval": "W", "note": "dd1047", "amount": "34", "IsActive": true },
{ "id": "75", "firstname": "LORA", "codeval": "H", "note": "rr7323", "amount": "56", "IsActive": true },
{ "id": "95", "firstname": "EST", "codeval": "M", "note": "gg574", "amount": "55", "IsActive": true }
],
myGrid = $("#list");
myGrid.jqGrid({
datatype:'local',
data: myData,
colNames: ['ID', 'FirstName', 'Code', 'Amount', 'Note', 'Action'],
colModel:[
{name:'id',width:70,align:'center',sorttype: 'int'},
{name:'firstname',width:80, align:'center'},
{ name: 'codeval', width: 70 },
{name:'amount',width:100, formatter:'number'},
{name:'note',index:'note',width:100,sortable:false},
{
name: 'IsActive',
width: 100,
formatter: function (cellvalue, options, rowObject) {
if (cellvalue == true) {
return '<div style="padding-left:5px;"><button class="ui-button ui-widget ui-state-default app-custom-button-retire" >' +
'<span title="" class="ui-button-icon-primary ui-icon ui-icon-scissors"></span>Retire' +
'</button></div>';
}
else {
return '<div style="padding-left:5px;"><button class="ui-button ui-widget ui-state-default app-custom-button-activate" >' +
'<span title="" class="ui-button-icon-primary ui-icon ui-icon-check"></span>Activate' +
'</button></div>';
}
}
}
],
rowNum:10,
pager: '#pager',
gridview:true,
ignoreCase:true,
rownumbers:true,
viewrecords: true,
sortorder: 'desc',
height: '100%',
beforeSelectRow: function (rowid, e) {
var $self = $(this),
$td = $(e.target).closest("tr.jqgrow>td"),
rowid = $td.parent().attr("id"),
//rowData = $self.jqGrid("getLocalRow", rowid),
rowData = $self.jqGrid("getRowData", rowid)
iCol = $td.length > 0 ? $td[0].cellIndex : -1,
colModel = $self.jqGrid("getGridParam", "colModel");
celValue = $self.jqGrid('getCell', rowid, 'FirstName');
if (iCol >= 0 && colModel[iCol].name === "IsActive") {
if ($(e.target).hasClass("app-custom-button-retire")) {
updateActiveStatus(rowid,false);
return false;
}
if ($(e.target).hasClass("app-custom-button-activate")) {
updateActiveStatus(rowid, true);
return false;
}
}
//Avoid selection of row
return false;
}
});
myGrid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
});
I seem multiple misunderstanding in your code. First of all you have some source data, which are the array of item. Every item is object with multiple properties, like:
{ "id": "75", "firstname": "LORA", "codeval": "H", "note": "rr7323",
"amount": "56", "IsActive": true }
or, which is the same,
{ id: "75", firstname: "LORA", codeval: "H", note: "rr7323",
amount: "56", IsActive: true }
It should be clear that such item can't have multiple properties with the same name. The object
{ "id": "75", "firstname": "LORA", "codeval": "H", "note": "rr7323",
"amount": "56", "IsActive": true, "IsActive": true }
would be wrong even if some web browser could ignore the error. Even if you specify the same value true for both "IsActive" properties.
In the same way you can't use colModel with multiple columns with the same name property. Your second demo https://jsfiddle.net/LijoCheeran/rqab1veh/11/ have two columns with the same property name: 'IsActive'. It's wrong. You can fix the code by usage, for example, name: 'IsActive1' in the second column. The formatter of IsActive1 can use rowObject.IsActive instead of cellvalue to access to the required data. The corresponding code will be the follwing
{
name: 'IsActive1',
width: 75,
formatter: function (cellvalue, options, rowObject) {
return rowObject.IsActive == true ? 'Active' : 'Retired';
}
},
{
name: 'IsActive',
width: 100,
formatter: function (cellvalue, options, rowObject) {
return cellvalue == true ? retireButton : activeButton;
}
}
where retireButton and activeButton contains HTML fragments of the buttons.
Now it's important to understand, that jqGrid hold the data array. The method $("#list").jqGrid('getLocalRow', rowid) get you the reference to the data item which corresponds the data of the row. The method getRowData will get the data from HTML representation of the cells (from <td> elements) and unformat there. The type of the fields of returned object will be strings.
Because you need to update not only the data, but the cell content of firstname, IsActive1 and IsActive columns then you have to call setCell on every the field or better call one setRowData:
function updateActiveStatus (rowid, isToActive) {
alert('calling the function');
$("#list").jqGrid('setRowData', rowid, {
firstname: 'A',
IsActive1: false,
IsActive: false
});
var item = $("#list").jqGrid('getLocalRow', rowid);
// delete unneeded IsActive1 property created in the item
delete item.IsActive1;
}
The only small disadvantage of the setRowData call is creating new property IsActive1 in the item of data. Old jqGrid 4.6 have no possibility to save the data "virtually" in some another place as the item.IsActive1. Free jqGrid allows to specify saveLocally callback, which can make custom "saving" of the data of the column in the local item. It's not real large problem in your case and you need just delete unneeded property by delete item.IsActive1
You can see the results on the modified demo https://jsfiddle.net/OlegKi/rqab1veh/12/

CodeIgniter with DataTable Server Side

I just want to ask how can I add DATA ID on the buttons EDIT/DELETE here is my javascript for rendering datatable rows
I wanted to put Data ID on ROW_ID like for example delete?id=1 (CI: delete/1)
$('#data').dataTable({
"sScrollY": "400px",
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"sAjaxSource": "<?php echo base_url(); ?>pages/datatable",
"iDisplayLength": 10,
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"aaSorting": [[0, 'asc']],
"aoColumns": [ null, null, null,
{
"mData": null,
"sClass": "center",
"sDefaultContent": 'Edit / Delete',
}
]
}).fnSetFilteringDelay(700);
Assuming you're returning the ID value in your ajax, you can use mRender
...
"sClass": "center",
"mRender": function ( data, type, full ) {
return 'Edit / Delete';
}
full[0] is the data row with the ID parameter. If this is in a different column, obviously you'll to change the index accordingly

Using fnReloadAjax Still not working

Using Datatables, and the fnReloadAjax plugin (see below), I am trying to reload the table's data from a server-side script using the following code:
$.fn.dataTableExt.oApi.fnReloadAjax = function(oSettings, sNewSource, fnCallback, bStandingRedraw) {
if (sNewSource !== undefined && sNewSource !== null) {
oSettings.sAjaxSource = sNewSource;
}
// Server-side processing should just call fnDraw
if (oSettings.oFeatures.bServerSide) {
this.fnDraw();
return;
}
this.oApi._fnProcessingDisplay(oSettings, true);
var that = this;
var iStart = oSettings._iDisplayStart;
var aData = [];
this.oApi._fnServerParams(oSettings, aData);
oSettings.fnServerData.call(oSettings.oInstance, oSettings.sAjaxSource, aData, function(json) {
/* Clear the old information from the table */
that.oApi._fnClearTable(oSettings);
/* Got the data - add it to the table */
var aData = (oSettings.sAjaxDataProp !== "") ?
that.oApi._fnGetObjectDataFn(oSettings.sAjaxDataProp)(json) : json;
for (var i = 0; i < aData.length; i++) {
that.oApi._fnAddData(oSettings, aData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
that.fnDraw();
if (bStandingRedraw === true) {
oSettings._iDisplayStart = iStart;
that.oApi._fnCalculateEnd(oSettings);
that.fnDraw(false);
}
that.oApi._fnProcessingDisplay(oSettings, false);
/* Callback user function - for event handlers etc */
if (typeof fnCallback == 'function' && fnCallback !== null) {
fnCallback(oSettings);
}
}, oSettings);
};
$(document).ready(function() {
$('#reloadDataBtn').click(function() {
$('#myTable').fnReloadAjax('mySource2.php');
});
$("#myTable").dataTable({ bSort: true,
"bProcessing": true,
"sAjaxSource": 'mySource1.php',
bAutoWidth: true,
"iDisplayLength": 5, "aLengthMenu": [5, 10, 25, 50, 100],
"sPaginationType": "full_numbers",
"aoColumnDefs": [{ "bSortable": false, "aTargets": [-1, 0]}]
});
});
But I still get the fnReloadAjax is not a function JS error. What am I doing wrong?
In verstion 1.10 of DataTable plugin, function fnReloadAjax is deprecated, now you need use api().ajax.reload() instead:
$(document).ready(function() {
var datatable = $('#calls_list_table').dataTable({
"iDisplayLength": 10,
"processing": true,
"serverSide": true,
"ajax": {
"url": "/calls/data/",
"type": "POST"
}
});
$('button').click(function() {
// use it instead of fnReloadAjax
datatable.api().ajax.reload();
});
});
This is because you address an element returned by jQuery, not the dataTable object itself.
Do this instead :
var dataTable; //reference to your dataTable
$('#reloadDataBtn').click(function() {
dataTable.fnReloadAjax('mySource2.php');
//NOT
//$('#myTable').fnReloadAjax('mySource2.php');
});
dataTable = $("#myTable").dataTable({
bSort: true,
"bProcessing": true,
"sAjaxSource": 'mySource1.php',
bAutoWidth: true,
"iDisplayLength": 5, "aLengthMenu": [5, 10, 25, 50, 100],
"sPaginationType": "full_numbers",
"aoColumnDefs": [{ "bSortable": false, "aTargets": [-1, 0]}]
});
Now fnReloadAjax() will be called proplerly.

Jquery resize the form "formAddNewRow"

When I click on Add button , the formAddNewRow form opens , but I want to increase the widht of this form how do I achieve this ?
Here is what I tried
$(document).ready(function () {
var r;
var oTable = $('#Lookup').dataTable({
"sPaginationType": "full_numbers",
"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"iDisplayLength": 25
}
).makeEditable({
oAddNewRowFormOptions: { title: 'Add user', width: 800 },
"aoColumns": [
{
cssclass: 'required'
},
{ tooltip: 'Click to edit',
cssclass: 'required'
},
{ tooltip: 'Click to edit',
cssclass: 'required'
}
],
fnShowError: function (message, action) {
switch (action) {
case "update":
jAlert(message, "Update failed");
break;
case "add":
jAlert(message, "Update failed");
break;
}
}
});
});
But the Addnewform stays the same , the width of the form is not increased ? Any suggestions . can you please point me in the right direction
I also had the same problem, but after some searching I found the answer: place this in your document.ready function: (if you just want to change the width as the same of your content, just change it to auto)
$("#formAddNewRow").dialog({width:'650px'})

Resources