Ignited Datatables for Codeigniter returns invalid SQL query when used with mysql's date_format function - codeigniter

When i use date_format, it returns invalid sql query
$this->load->library('Datatables');
$this->datatables->from('events');
$this->datatables-select('id,event_name,event_location,DATE_FORMAT(event_start_date,"%b %d %Y, %h:%i %p") as evs,event_type_id,event_status'); echo
$this->datatables->generate();
It returns
SELECT `id`, `event_name`, `event_location`, DATE_FORMAT(event_start_date, `"%b` %d %Y, `%h:%i` %p") as evs, `event_type_id`, `event_status` FROM (`events`) ORDER BY `event_name` asc LIMIT 10

$this->datatables-select('id,event_name,event_location,DATE_FORMAT(event_start_date,"%b %d %Y, %h:%i %p") as evs,event_type_id,event_status',FALSE);
Looking ate the github Library, he added a second parameter
The second parameter are optional whether to add backticks or not. Set it to false so that backticks ` are disabled.

There is another problem in this,
var oTable = $('#dTableEvents').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/" + PROJECT_NAME + "events/get_all_events",
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"iDisplayStart ": 20,
"bAutoWidth": false,
"oLanguage": {
"sProcessing": "<img src='/" + PROJECT_NAME + "public/images/ajax-loader.gif'>",
"sLengthMenu": "Show _MENU_ Entries per Page",
"sInfo": "Showing _START_ to _END_ of _TOTAL_ Entries per Page",
"sInfoEmpty": "Showing 0 to 0 of 0 Entries per Page",
"sInfoFiltered": "(filterred from _MAX_ total Entries per Page)"
},
"aoColumns": [
{
"mDataProp": "name",
"bSearchable": true,
"bSortable": true,
},
{
"mDataProp": "start_date",
"bSearchable": true,
"bSortable": true,
},
{
"mDataProp": "location",
"bSearchable": true,
"bSortable": true,
},
{
"mDataProp": "type",
"bSearchable": true,
"bSortable": true,
},
{
"fnRender": function (oObj) {
return '<img alt="" src="/' + PROJECT_NAME + 'public/images/seven-rating.png">';
},
"mDataProp": "status",
"bSearchable": false,
"bSortable": true,
},
{
"fnRender": function (oObj) {
return '<input type="button" value="Edit" class="edit-btn" onclick="location=\'/'+PROJECT_NAME+'events/edit/' + oObj.aData['id'] + '\'"> <input type="button" value="View" class="edit-btn" onclick="location=\'/'+PROJECT_NAME+'events/view/' + oObj.aData['id'] + '\'">';
},
"mDataProp": "__action",
"bSearchable": false,
"bSortable": false,
}
],
"fnInitComplete": function () {
//oTable.fnAdjustColumnSizing();
},
'fnServerData': function (sSource, aoData, fnCallback) {
$.ajax({
'dataType': 'json',
'type': 'POST',
'url': sSource,
'data': aoData,
'success': fnCallback
});
},
"fnDrawCallback": function()
{
$('#dTableEvents tbody td:not(:nth-last-child(-n+1))').addClass('cont-grid bdr-rt-white');
$('#dTableEvents tbody td:nth-last-child(-n+1)').addClass('cont-grid');
}
});
When i use aoColumns in this, then searching and sorting gets disabled, when i remove aaColumns, then it again starts working.

Related

KendoUI populate dropdown

I am new to kendoUI and I need some assistance with getting the data that is returned from a function to populate into the dropdown. I am currently getting [object HTMLSelectElement] - you can see in the image attached. Any help is appreciated.
data is returned in function
dropdown is not showing the years returned
LoadAcceptedSubmissionsGrid: function (module) {
// Grid for "Accepted" tab
var isAccepted = "true";
gridAcceptedSubmissions = $("#gridAcceptedSubmissions").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
serverSorting: true,
serverFiltering: true,
allowUnsort: true,
transport: {
read: function (options) {
var strFilter = JSON.stringify(options.data.filter);
var strSort = JSON.stringify(options.data.sort);
var pageSize = options.data.pageSize === undefined && gridAcceptedSubmissions !== null ?
gridAcceptedSubmissions.dataSource.total() :
options.data.pageSize;
var acceptedSubmissionsUrl = commonUrl + "/Forms/Submissions/"
+ upacsSessionId + "/" + userId + "/" + form + "/" + isAccepted + "/"
+ options.data.page + "/" + pageSize + "/" + options.data.skip;
$.ajax({
type: "POST",
url: acceptedSubmissionsUrl,
xhrFields: {
withCredentials: true
},
data: {
filter: strFilter,
sort: strSort
},
success: function (response) {
options.success(response);
},
error: function (result) {
options.error(result);
}
});
}
},
pageSize: 10,
batch: false,
schema: {
total: function (response) {
return response.total;
},
data: function (response) {
return response.values;
},
model: {
id: "submissionId",
fields: {
state: { editable: false, type: "string", sort: "asc" },
fipsCode: { editable: false, type: "number", sort: "asc" },
year: { editable: false, type: "number", sort: "desc" },
name: { editable: false, type: "string" },
createdBy: { editable: false, type: "string" },
createdOn: { editable: false, type: "date" },
lastModifiedBy: { editable: false, type: "string" },
lastModifiedOn: { editable: false, type: "date" },
isEditable: { editable: false, type: "boolean" },
isReviewable: { editable: false, type: "boolean" }
}
}
}
},
groupable: false,
sortable: {
showIndexes: true,
mode: "multiple"
},
resizable: true,
selectable: "row",
scrollable: true,
filterable: true,
navigatable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 10
},
dataBound: this.GridDataBound,
columns: [
{
field: "submissionId",
title: "Id",
},
{
field: "state",
title: "State",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("state", "name", true)
},
sort: "ascending"
},
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("year", null, true)
},
sort: "descending"
},
{
field: "status",
title: "Status",
filterable: {
multi: true,
dataSource: this.BuildMultiCheckboxDataSource("status", null, true)
}
},
{
field: "createdBy",
title: "Initiated By",
filterable: {
ui: this.FormCreatedByAcceptedFilter
}
},
{
field: "createdOn",
title: "Initiated On",
format: "{0:g}",
},
{
field: "lastModifiedBy",
title: "Modified By",
filterable: {
ui: this.FormLastModifiedByAcceptedFilter
}
},
{
field: "lastModifiedOn",
title: "Modified On",
format: "{0:g}"
},
{
title: "Action",
headerTemplate: "<div class='headerTemplate'><span class='headerText'>Action</span>" +
"<button class='clearAllFilters' id='clearAllFiltersAcceptedSubmissions' tabindex=0> Clear All Filters</button></div>",
command: [
{
name: "View",
text: " ",
visible: function (dataItem) { return !dataItem.isEditable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-View' title='View Form' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-eye'><span class='sr-only'>View form</span></i></a>";
return tmpl;
},
click: function (e) {
e.preventDefault();
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-existing-form", module);
}
},
{
name: "View History",
text: " ",
visible: function (dataItem) { return !dataItem.isReviewable },
template: function () {
var tmpl = "<a role='button' class='k-button k-button-icontext k-grid-ViewHistory' title='View Form History' tabindex=0>" +
"<i aria-hidden='true' class='fa fas fa-history'><span class='sr-only'>View form history</span></i></a> ";
return tmpl;
},
click: function (e) {
var data = this.dataItem($(e.target).closest("tr"));
$("#submissionId").val(data.submissionId);
commonFormsModule.UpdateFormMetadata(data, "from-grid")
gridSubmissionStatusHistory.dataSource.read();
commonFormsModule.SwitchTo("view-status-history", module);
}
}
],
},
]
}).data("kendoGrid");
gridAcceptedSubmissions.hideColumn(0);
$("#clearAllFiltersAcceptedSubmissions").click(function () {
gridAcceptedSubmissions.dataSource.filter({});
});
},
Without seeing what BuildMultiCheckboxDataSource is doing, I can only make assumptions.
However, since you have declared year as an IEnumerable<int> then the datasource does not need to be anything elaborate. Simply set it to the collection being returned by the server:
{
field: "year",
title: "Year",
filterable: {
multi: true,
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/my-endpoint-to-fetch-years-here"
}
}
})
},
sort: "descending"
}

jqgrid - filter not working on some columns

In the below grid, filtertooblar works for few columns and does not for few other.
I have verified that index and name for colModel is same for the columns for which filtering is not working.
The filters are coming through correctly when I check it in beforesearch event.
Here is one of the colModels that does not filter:
7:
formoptions: {label: 'If Yes to previous question, would your familiari… affect how you view this case or those involved?'}
frozen: false
index: "ifyestopreviousquestionwouldyourfamiliaritywiththeparticipantsaffecthowyouviewthiscaseorthoseinvolved"
name: "ifyestopreviousquestionwouldyourfamiliaritywiththeparticipantsaffecthowyouviewthiscaseorthoseinvolved"
search: true
sortable: true
And the filter is coming as below
{"groupOp":"AND","rules":[{"field":"ifyestopreviousquestionwouldyourfamiliaritywiththeparticipantsaffecthowyouviewthiscaseorthoseinvolved","op":"cn","data":"Yes"}]}
Can you please help? Thank you very much
var grid = $("#list-grid").jqGrid({
datatype: "local",
height: 'auto',
colNames: colNames,
colModel: colModels,
data: rows,
gridview: true,
sortable: true,
autowidth: true,
shrinkToFit: false,
editable: true,
scrollOffset: true,
ExpandColClick: true,
viewsortcols: [true, 'vertical', true],
loadonce: true,
onSelectRow: function() {
return false;
},
search:
{
caption: "Search...",
Find: "Find",
Reset: "Reset",
odata: ['equal', 'not equal', 'less', 'less or equal', 'greater', 'greater or equal', 'begins with', 'does not begin with', 'is in', 'is not in', 'ends with', 'does not end with', 'contains', 'does not contain'],
groupOps: [{ op: "AND", text: "all" }, { op: "OR", text: "any" }],
matchText: " match",
rulesText: " rules"
},
caption: '<h4>Report</h4>',
regional: 'en',
ondblClickRow: function(rowid) {
jQuery(this).jqGrid('viewGridRow', rowid);
},
loadComplete: function() {
var $this = $(this), ids = $this.jqGrid('getDataIDs'), i, l = ids.length;
for (i = 0; i < l; i++)
{
$this.jqGrid('editRow', ids[i], true);
}
},
sortable:
{
update: function(permutation) {
}
},
pager: "#pager"
}).navGrid('#pager', { view: true, del: false, edit: false, add: false, search: false, refresh: false,width: 800 },
{view:false}, // Edit Options
{ view: false}, // Add Options
{}, // Del Options
{ width: 800 }, // Search Options
{
closeOnEscape: true,
width: 1000,
beforeShowForm: function($form)
{
console.log('form', $form);
$form.find("td.DataTD").each(function() {
var html = $(this).html(); // <span> </span>
if (html.substr(0, 6) === " ")
{
$(this).html(html.substr(6));
}
});
}
} // View Options
).filterToolbar({
groupOp: 'AND',
defaultSearch: 'cn',
searchOnEnter: true,
searchOperators: false,
stringResult: true,
ignoreCase: true,
beforeSearch: function () {
var postData = $("#list-grid").jqGrid('getGridParam', 'postData');
console.log(postData);
}
});
//grid.data = row; // replace the data array to another data
//$("#list-grid").trigger("reloadGrid", { current: true });
//$("#list-grid").jqGrid('setFrozenColumns');
},
});
$("#list-grid").on("jqGridToolbarBeforeSearch", function (e) {
var filters = $(this).jqGrid("getGridParam", "postData").filters;
console.log(filters);
if (typeof filters === "string") {
filters = $.parseJSON(filters);
}
return e.result; // forward the result of the last event handler
});
</text>
}
});

Why my JqGrid is shrinking while i change the question type?

My Question Type contains options: Option, Textual and Value. I have added a functionality in JavaScript that whenever I choose Option in Question Type I get table below the form. When I am retrieving data directly from the database with Question Type = Option then it is showing table that is fine but when I change my Question Type from Textual or Value to Option for other data, then JqGrid is getting shrinked automatically.
function QuestionTypeChoice() {
if($("#dropdownQuestionType").val()=="Option")
{
$(".GridDiv").show();
}
else
{
$(".GridDiv").hide();
}
$("#tblSurveyOption").jqGrid({
type: "GET",
url: "/Survey/GetSurveyOptions",
datatype: "json",
async: false,
postData: {
questionId: $('#SurveyQuestionsId').val(),
},
colNames: [
"Id", "SurveyQuestionId", "Sequence", "Option", "Description"
],
colModel: [
{ key: true, name: "SurveyOptionId", index: "SurveyOptionId", editable: false, hidden: true },
{ key: false, name: "SurveyQuestionId", index: "SurveyQuestionId", editable: false, hidden: true },
{ key: false, name: "Sequence", index: "Sequence", editable: true, width: 10 },
{ key: false, name: "OptionValue", index: "OptionValue", editable: true, width: 40 },
{ key: false, name: "Description", index: "Description", editable: true, width: 50 },
],
pager: jQuery("#divSurveyOption"),
rowNum: -1,
scroll: 0,
height: $(window).innerHeight() - 450,
width: '100%',
viewrecords: true,
caption: "Question List Options",
emptyrecords: "No records",
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false
},
autowidth: true,
loadonce: false,
gridview: true,
multiselect: false,
autoencode: true,
ajaxGridOptions: { cache: false },
gridComplete: function () { },
ondblClickRow: function () { }
}).navGrid("#divSurveyOption", { edit: false, add: true, del: true, search: false, refresh: false },
{},
{
// add options
zIndex: 100,
url: "/Survey/CreateOption",
mtype: 'Post',
closeOnEscape: true,
closeAfterAdd: true,
width: 400,
reloadAfterSubmit: true,
serializeEditData: function (data) {
data["SurveyQuestionId"] = $("#SurveyQuestionsId").val();
return $.param(data);
},
beforeSubmit: function (posdata, obj) {
if ($('#Sequence').val() == '' || $('#Sequence').val() == undefined) {
return [false, "Please enter a sequence"];
}
else if ($('#OptionValue').val() == '' || $('#OptionValue').val() == undefined) {
return [false, "Please enter a option"];
}
else if ($('#Description').val() == '' || $('#Description').val() == undefined) {
return [false, "Please enter a description"];
}
else if (CheckSequence(posdata.Sequence)) {
return [false, "Sequence number already exists"];
}
else {
return [true, ""];
}
},
afterComplete: function (response) {
if (response.responseText) {
var isSuccess = response.responseText.split('~')[0];
if (isSuccess == '1') {
toastr.success(response.responseText.split('~')[1]);
} else {
toastr.error(response.responseText.split('~')[1]);
}
}
}
},
{
// delete options
zIndex: 100,
url: "/Survey/DeleteOption?questionId=" + $('#SurveyQuestionsId').val(),
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete this?",
afterComplete: function (response) {
if (response.responseText) {
var isSuccess = response.responseText.split('~')[0];
if (isSuccess == '1') {
toastr.success(response.responseText.split('~')[1]);
} else {
toastr.error(response.responseText.split('~')[1]);
}
}
}
});
ReloadOptionGrid();
}
function CheckSequence(sequence) {
var data = $("#tblSurveyOption").jqGrid("getCol", "Sequence");
if (data != null && data.length > 0 && data.indexOf(sequence) != -1) {
return true;
}
else {
return false;
}
}
function ReloadOptionGrid() {
$("#tblSurveyOption").jqGrid('clearGridData');
//Reload grid trigger
$("#tblSurveyOption").setGridParam(
{
url: "/Survey/GetSurveyOptions" + "?questionId=" + $('#SurveyQuestionsId').val()
}).trigger("reloadGrid");
}

Datatable Search Filter Column problem "mb_strtolower() expects parameter 1 to be string, array given"

I want to make a Prescription management system with laravel. so need to patient list. i loaded patient information in Datatable. this is loaded successfully but when i use Datatable Search Filter Column then this error message come "mb_strtolower() expects parameter 1 to be string, array given"
var table = $('#patient-data-table').DataTable( {
"processing": true,
"serverSide": true,
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false,
"aoColumnDefs": [{ "bVisible": false, "aTargets": [1] }],
"ajax": {
"url": "{{URL::to('/')}}/patientList",
"type": "GET",
"dataType": "json",
},
"columns": [
{
"render": function (data, type, JsonResultRow, meta) {
return '<img src="{{asset('patient_image')}}/'+JsonResultRow.image+'" style="height:30px; width:30px; border-radius: 30px;"/>';
}
},
{ "data": "fullName" },
{
data: {fullName : "fullName", email : "email", address : "address"},
mRender : function(data, type, full) {
return "Name: "+data.fullName+' <br> '+"Email: "+data.email+' <br> '+"Address: "+data.address;
}
},
{ "data": "contact_number" },
{ "data": "gender" },
{ "data": "Link", name: 'link', orderable: false, searchable: false}
],
"order": [[1, 'asc']]
} );
How can i solve this problem?
Try change:
{
data: {fullName : "fullName", email : "email", address : "address"},
mRender : function(data, type, full) {
return "Name: "+data.fullName+' <br> '+"Email: "+data.email+' <br> '+"Address: "+data.address;
}
},
For:
{
data: {fullName : "fullName", email : "email", address : "address"},
mRender : function(data, type, full) {
return "Name: "+data.fullName+' <br> '+"Email: "+data.email+' <br> '+"Address: "+data.address;
}
searchable: false, //add this line
},

DataTables Searching Option is not working

If i search "Hossain" datatable is not getting sorted. Though this data is available in datatable. How can i solve this problem?
var table = $('#list_table').DataTable( {
"processing": true,
"serverSide": true,
"destroy": true,
"searching": true,
"ordering": true,
"bInfo": true,
"paging": true,
"ajax": {
"url": "{{URL::to('/')}}/current_employeelist",
"type": "POST",
"headers":{'X-CSRF-TOKEN': '{{ csrf_token() }}'},
"data": {location: $("#location").val()}
},
"columns": [
{
"render": function (data, type, JsonResultRow, meta) {
return '<img src="{{asset('employee_image')}}/'+JsonResultRow.Images+'" style="height:30px; width:30px; border-radius: 30px;"/>';
}
},
{ "data": "Link",
"mRender": function (data, type, full) {
return '<a target="_blank" href="{{URL::to('/')}}/employeeinfo/'+full.id+'">'+full.employee_name+'</a>';
}
},
{ "data": "location_name" },
{ "data": "depertment_name" },
{ "data": "designation_name" },
{ "data": "contact_number" },
{ "data": "joining_date" },
#permission('EditEmployeeInfo')
{ "data": "Link", name: 'action', orderable: false, searchable: false},
#endpermission
],[enter image description here][1]
"order": [[0, 'asc']]
});
I want to get searching actual data from datatable.
Image is here

Resources