Error: cannot call methods on tabulator prior to initialization; attempted to call method 'addRow' - asp.net-mvc

I have a page with a table:
<table id="myTable">
<thead>
<tr>
<th>Description</th>
<th>Qty</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
#Html.EditorFor(model => item);
}
</tbody>
</table>
And I then initialise Tabular like so:
$("#myTable").tabulator({
layout: "fitColumns",
addRowPos: "bottom",
columns: [
{ title: "Description", field: "Description", editor: "input" },
{ title: "Qty", field: "Quantity", sorter: "number", editor: "number", editorParams: { min: 0, step: 1, } },
{ title: "Cost", field: "Cost", sorter: "number", editor: "number", editorParams: { min: 0, step: 0.1, }, align: "right", formatterParams: { decimal: '.', thousand: '.', symbol: "R" }, bottomCalc: "sum", bottomCalcFormatter: "money", bottomCalcFormatterParams: { decimal: '.', thousand: '.', symbol: "R" } },
{ formatter: "buttonCross", width: 30, align: "center", cellClick: function (e, cell) { cell.getRow().delete(); } },
],
});
This all works pretty nicely, but I attempted to add:
$("#add-row").click(function () {
$("#myTable").tabulator("addRow", {}, true);
});
clicking on my button to add a new row results in: Error: cannot call methods on tabulator prior to initialization; attempted to call method 'addRow'
I tried to do: var table = $("#myTable").tabulator... with table.addRow({}) but then I get an error saying addRow is not a function.
Is it supposed to work like this?

That message suggests that you havnt created your Tabulator object before you have called the addRow function.
If you are new to Tabulator then i would suggest that you dont use the jQuery wrapper. that was there more for legacy reasons from the old 3.5 version.
In this case you should use the constructor:
var table = new Tabulator("#myTable", {
layout: "fitColumns",
addRowPos: "bottom",
columns: [
{ title: "Description", field: "Description", editor: "input" },
{ title: "Qty", field: "Quantity", sorter: "number", editor: "number", editorParams: { min: 0, step: 1, } },
{ title: "Cost", field: "Cost", sorter: "number", editor: "number", editorParams: { min: 0, step: 0.1, }, align: "right", formatterParams: { decimal: '.', thousand: '.', symbol: "R" }, bottomCalc: "sum", bottomCalcFormatter: "money", bottomCalcFormatterParams: { decimal: '.', thousand: '.', symbol: "R" } },
{ formatter: "buttonCross", width: 30, align: "center", cellClick: function (e, cell) { cell.getRow().delete(); } },
],
});
And then you can add rows like this:
table.addRow({}, true);
You just need to make sure that when you assign it to the table variable it is in a scope where it can be accessed by all functions that need it

I was initialising a Tabulator onto an existing table targetting the <table id="myTable"> element. Although this works great initially, trying other stuff (like in my question) kept on resulting in 'Error: cannot call methods on tabulator prior to initialization'.
I ended up scraping the predefined <table> and went with initialising on <div id="myTable"> and getting the data via ajax.
Now it all works as expected/documented. Dunno if this is a bug/supposed to work like this/my own incompetence, but at least I can move on.

Related

Call knockout method inside kendo grid

I have simple kendo UI grid
$("#Grid").kendoGrid({
dataSource: {
serverPaging: true,
transport: {
read: "Course/Read",
dataType: "json"
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
pageSize: 10
},
pageable: true,
columns:
[
{ field: "CourseName", title: "Name", width: 100 },
{ field: "SpecialtyName", title: "Specialty", width: 100, filterable: false },
{ title: "Edit", template: '<span class="EditIcon"><i data-bind="click:Edit(#: Id#)" class="fa fa-edit"></i></span>', width: 50 },
]
});
the problem is when I am using:
data-bind="click:Edit(#: Id#)"
when click on edit calling function not work inside kendo grid notice that both the grid and function inside knockout viewmodel
function viewmodel() {
var self = this;
self.Load = function () {
$("#Grid").kendoGrid({
dataSource: {
type: "aspnetmvc-ajax",
serverPaging: true,
transport: {
read: "Course/Read",
dataType: "json"
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
pageSize: 10
},
pageable: true,
columns:
[
{ field: "CourseName", title: "Name", width: 100 },
{ field: "SpecialtyName", title: "Specialty", width: 100, filterable: false },
{ title: "Edit", template: '<span class="EditIcon"><i data-bind="click:Edit(#: Id#)" class="fa fa-edit"></i></span>', width: 50 },
]
});
}
self.Load();
self.Edit= function (Id) {
////////my code////////
}
}
everything work fine the binding retrieve data, extra except call knockout method inside kendo grid, appreciate any help thanks.
if anyone looking for answer or open this post, this is not related to kendo, this is because the grid render rows after knockout binding done, so you can take viewmodel object in temp var in javascript and use it like tempvar.callfunction().

Kendo Filter is Not Working on the Date Column

I have an grid with date column in which I applied a filterable option and i did not get any results when I filter.
My grid:
var element = $("#grid").kendoGrid({
dataSource: {
data: gridDataSource,
schema: {
model: {
fields: {
Date: { type: "date", editable: false },
}
}
}
},
scrollable: true,
filterable : true,
columns: [
{
"field": "Date", "title": "Date", "format": "{0:MM/dd/yyyy}", filterable : {ui: function (e) {e.kendoDatePicker({format: "MM/dd/yyyy"})}}, width: "100px" }],
});
Probably is missing .data("kendoGrid"); in end of kendogrid() declaration.
For convinience I did an working example.
Hope this help
ps: Filter by 1966/01/27 in example to check.

in jqgrid : I want to show an empty grid with no pagination and display a message "no records found" if no records

I need to show an empty grid with no pagination and display a message "You have no records found" if empty results in jqGrid.i'm pretty new to this jqgrid.
I have added the code as below. Please Find the Oleg Demo1, Demo2
$(function () {
var $grid = $("#oversight-sample"),
//mydata = [{actions: "a", url: "http://stackoverflow.com/q/24609566/315935", created: "7/7/2014"}];
mydata = [];
emptyMsgDiv = $("<div><span style='color:red;font-size:24px'>You have no records found</span></div>");
$grid.jqGrid({
//autowidth: true,
caption: "Evaluated URLs",
colNames: ["Actions", "URL", "Fetch Date"],
colModel: [
{ name: "actions", align: "center", title: false, width: 60, resizable: false, sortable: false },
{ name: "url", width: 400 },
{ name: "created", align: "center", width: 125, sorttype: "date" }
],
data: mydata,
datatype: "local",
emptyrecords: "0 records found",
localReader: {
page: function (obj) {
return (obj.page === 0 || obj.page === undefined) ? "0" : obj.page;
}
},
loadComplete: function () {
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
},
height: "auto",
sortname: "created",
toppager: true,
pager: "#url-pager",
viewrecords: true
});
// place div with empty message insde of bdiv
emptyMsgDiv.insertAfter($grid.parent());
});
<table id="oversight-sample"><tbody><tr><td></td></tr></tbody></table>
<div id="url-pager"></div>
Here is the link to fiddler with the 'No records found' message. I hope it will give you an idea on how to create a basic jqgrid and what library references are required.
https://jsfiddle.net/99x50s2s/2/
<table id="sg1"></table>
<div id="psg1"></div>
jQuery("#sg1").jqGrid({
datatype: "local",
gridview: true,
loadonce: true,
shrinkToFit: false,
autoencode: true,
height: 'auto',
viewrecords: true,
sortorder: "desc",
scrollrows: true,
loadui: 'disable',
emptyrecords: 'No records found',
pager: '#psg1',
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:60, sorttype:"int"},
{name:'invdate',index:'invdate', width:90, sorttype:"date"},
{name:'name',index:'name', width:80},
{name:'amount',index:'amount', width:80, align:"right",sorttype:"float"},
{name:'tax',index:'tax', width:80, align:"right",sorttype:"float"},
{name:'total',index:'total', width:80,align:"right",sorttype:"float"},
{name:'note',index:'note', width:150, sortable:false}
],
caption: "Test Grid"
});
var mydata = [];//pass empty data
for(var i=0;i<=mydata.length;i++)
jQuery("#sg1").jqGrid('addRowData',i+1,mydata[i]);

How to pass form data and jqGrid (editUrl) data to Controller at same time

I have an asp.net MVC3 app with various bits of form data and a jqGrid.
When I edit a row in the jqGrid I need to post the grid data as well as some of the form pieces to the editUrl controller.
I can post the jqGrid edited data to my controller through the editUrl just fine.
Is there a way to do this?
Im not sure how to send the other form elements and how to receive them in my controller.
Any help will be greatly appreciated.
Below is my jqGrid:
$("#jqTable").jqGrid({
// Ajax related configurations
url: '#Url.Action("_CustomBinding")',
datatype: "json",
mtype: "POST",
postData: {
programID: function () { return $("#ProgramID option:selected").val(); },
buildID: function () { return $('#Builds option:selected').val(); }
},
// Specify the column names
colNames: ["Actions", "Assembly ID", "Assembly Name", "Assembly Type", "Cost", "Order", "Budget Report", "Partner Request", "Display"],
// Configure the columns
colModel: [
{ name: 'myac', width: 80, fixed: true, sortable: false, resize: false, formatter: 'actions', formatoptions: { keys: true} },
{ name: "AssemblyID", key: true, index: "AssemblyID", width: 40, align: "left", editable: false },
{ name: "AssemblyName", index: "AssemblyName", width: 100, align: "left", editable: true, edittype: 'select',
editoptions: {
dataUrl: '#Url.Action("_Assemblies")',
buildSelect: function (data) {
var response = jQuery.parseJSON(data);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
var ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + "</select>";
}
}
},
{ name: "AssemblyTypeName", index: "AssemblyTypeName", width: 100, align: "left", editable: false, edittype: 'select' },
{ name: "AssemblyCost", index: "AssemblyCost", width: 50, align: "left", formatter: "currency", editable: true },
{ name: "AssemblyOrder", index: "AssemblyOrder", width: 50, align: "left", editable: true },
{ name: "AddToBudgetReport", index: "AddToBudgetReport", width: 100, align: "center", formatter: "checkbox", editable: true, edittype: 'checkbox' },
{ name: "AddToPartnerRequest", index: "AddToPartnerRequest", width: 100, align: "center", formatter: "checkbox", editable: true, edittype: 'checkbox' },
{ name: "Show", index: "Show", width: 50, align: "center", formatter: "checkbox", editable: true, edittype: 'checkbox'}],
// Grid total width and height and formatting
//width: 650,
//height: 220,
altrows: true,
// Paging
//toppager: true,
pager: $("#jqTablePager"),
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true, // Specify if "total number of records" is displayed
emptyrecords: 'No records to display',
// Default sorting
sortname: "AssemblyID",
sortorder: "asc",
// Grid caption
caption: "Build Template",
// grid command functionality
editurl: '#Url.Action("_AjaxUpdate")',
onSelectRow: function (AssemblyID) {
if (AssemblyID && AssemblyID !== lastsel) {
$('#jqTable').jqGrid('restoreRow', lastsel);
$("#jqTable").jqGrid('editRow', AssemblyID, true);
lastsel = AssemblyID;
}
}
}).navGrid("#jqTablePager",
{ refresh: false, add: false, edit: false, del: false },
{}, // settings for edit
{}, // settings for add
{}, // settings for delete
{sopt: ["cn"]} // Search options. Some options can be set on column level
);
You can customize what is being sent to the server using onclickSubmit option:
.navGrid("#jqTablePager",
{ refresh: false, add: false, edit: false, del: false },
{ // settings for edit
onclickSubmit: function(params, postdata)
{
postdata.extraParam = 'value'
}
},
{}, // settings for add
{}, // settings for delete
{sopt: ["cn"]} // Search options. Some options can be set on column level
);
The controller will receive a JSON object containing all edited properties + extraParam. It is up to you how you handle this on the server side.
I see you use already programID and buildID properties defined as functions. The functions will be called during every request to get the data for the grid. In the same way you can use inlineData or extraparam parameter of the editRow which you call explicitly inside of your onSelectRow callback.
Try to call the demo which has the following jqGrid options:
inlineData: {
myParam: function () {
alert("inlineData is calling!!!");
return "OK";
}
},
onSelectRow: function (id) {
if (id && id !== lastSel) {
$(this).jqGrid('restoreRow', lastSel);
$(this).jqGrid('editRow', id, true, null, null, null, {
myNextParam: function () {
alert("extraparam of 'editRow' is calling!!!");
return "Fine";
}
});
lastSel = id;
}
}
You will see two alerts if you would save the data of the editing row. In my demo I used editurl: 'myDummyUrl' which has no code on the server side and you will see an error at the end, but if you examine the HTTP traffic (with respect of Fiddler or Firebug) you will see that the following additional parameters will be send to the editurl:
myParam=OK&myNextParam=Fine
I think it is what you need.
inlineData:{}
is working fine for getting work before goes to controller while editing.
But in case of delete how to get event like before to pass control to controller to make json , after click on delete.

Add DatePicker range in single column of jqgrid filter

I’ve been able to add a datepicker into the filter toolbar of a jqgrid with the code below. However, I’m wondering if there’s a way to squeeze two datepickers into this single DateCreated column, so as to specify the range (From, To). Any ideas?
function loadGrid() {
$(tableID).jqGrid({
…
colModel: [
…
{ name: 'DateCreated', index: 'DateCreated', width: 125, searchoptions:{dataInit:datePick, att:{title:'Select Date'}} },
…
})
…
}
datePick = function(elem) {
$(elem).datepicker();
}
If you are open to adding in a plugin, I found the range picker from filament group to be very easy to work with. In under an hour, I had the 3 files downloaded and installed into my project, and the range picker working.
link:filament group daterangepicker
Being that I'm using jquery 1.8 in my project, I ended up getting an updated version from
link:Github filament group daterangepicker jquery 1.8
daterangepicker is also able to take all of the options that datepicker supports, so you shouldn't have much trouble converting. Let me know if you have questions and I'll see if I can help.
For reference, the plugin is dual licensed with MIT and GPL. This is the same license structure as jqgrid, so I assume if you are able to use jqgrid, than this plugin should not be a problem.
UPDATE: Adding Code Example
The important part of this code is in the colModel for date. You simply specify a dataInit function for the search options, then add the daterangepicker. Be careful on the capitalization. That got me more than once. The beforeSelectRow is simply some modification I did in order to make my checkboxes along the side behave as a radio button. It is not needed for daterangepicker to work.
$("#myGrid").jqGrid(
{
url:url,
datatype: "json",
colNames:['Version','Date'],
colModel:[
{name:'version', search:true, stype:'text'},
{name:'date', search:true,stype:"text",searchoptions:{dataInit:function(el){
$(el).daterangepicker({dateFormat:'yy/mm/dd'});
}
}}
],
toolbarfilter: true,
sortname: 'version',
sortorder: "desc",
pager: jQuery('#myPager'),
viewrecords: true,
gridview: true,
multiselect: true,
beforeSelectRow: function(rowId)
{
var selectedIds = jQuery('#myGrid').jqGrid().getGridParam("selarrrow");
jQuery("#myGrid").jqGrid().resetSelection();
if(selectedIds)
{
var id = selectedIds[0]
if(id != rowId)
{
jQuery("#myGrid").jqGrid().setSelection(rowId, false);
}
}
else
{
jQuery("#myGrid").jqGrid().setSelection(rowId, false);
}
}
});
I had to do the very same thing, and Joseph's answer above got me 90% of the way there. So, most of the credit is due to him. I had to modify some stuff to get it to work because the filament date range picker allows for single dates (the today option, the specific date option, etc). I also had to add some code to trigger the search after you selected your date. Here's my update...the meat of what I needed to add was in the beginRequest function:
$(document).ready(function() {
var grid = jQuery('#list').jqGrid({
url: '/myajaxurl',
datatype: 'json',
mtype: 'GET',
colNames: ['Reference #', 'CreatedOn', 'Product', 'Model Number', 'Quantity', 'Transaction Type', 'Created By'],
colModel: [
{ name: 'InventoryTransactionLogId', index: 'InventoryTransactionLogId', align: 'center', sortable: true, search: false },
{
name: 'CreatedOn',
search: true,
stype: 'text',
align: 'center',
formatter: 'date',
formatoptions: { newformat: 'm-d-y H:i' },
sortable: true,
searchoptions: {
dataInit: function(el) {
$(el).daterangepicker({ dateFormat: 'yy/mm/dd', onChange: datePick });
}
}
},
{ name: 'ProductName', index: 'ProductName', align: 'center', sortable: true, search: false },
{ name: 'ModelNo', index: 'ModelNo', align: 'center', sortable: true, search: true },
{ name: 'Quantity', index: 'Quantity', align: 'center', sortable: true, search: false },
{ name: 'Description', index: 'Description', align: 'center', sortable: true, search: false },
{ name: 'UserName', index: 'UserName', align: 'center', sortable: true, search: false }
],
loadtext: "Retrieving Inventory Transaction Log...",
rowNum: 50,
rowList: [25, 50, 100],
sortname: 'InventoryTransactionLogId',
sortorder: 'asc',
pager: '#pager',
ignoreCase: true,
viewrecords: true,
height: 450,
autowidth: true,
scrollOffset: 45,
caption: 'Inventory Transaction Log',
emptyrecords: "No records",
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
repeatitems: false,
cell: 'cell',
id: 'InventoryTransactionLogId',
userdata: 'userdata'
},
beforeRequest: function () {
var theGrid = jQuery("#list");
var postData = theGrid.jqGrid('getGridParam', 'postData');
if (postData != undefined && postData.filters != undefined) {
postData.filters = jQuery.jgrid.parse(postData.filters);
//Remove if current field exists
postData.filters.rules = jQuery.grep(postData.filters.rules, function(value) {
if (value.field != 'CreatedOn')
return value;
});
// Parse the range picker field into start/end date
var dateRangeString = $('#gs_CreatedOn').val();
if (dateRangeString.length > 0) {
var dateRange = dateRangeString.split(' - ');
if (dateRange.length == 1) {
startDate = dateRange[0] + ' 00:00:00';
endDate = dateRange[0] + ' 23:59:59.999';
} else {
startDate = dateRange[0] + ' 00:00:00';
endDate = dateRange[1] + ' 23:59:59.999';
}
var startDateFilter = { "field": "CreatedOn", "op": "ge", "data": startDate };
var endDateFilter = { "field": "CreatedOn", "op": "le", "data": endDate };
// Add new filters
postData.filters.rules.push(startDateFilter);
postData.filters.rules.push(endDateFilter);
}
} else {
jQuery.extend(postData, {
});
}
if (postData != undefined && postData.filters != undefined) {
postData.filters = JSON.stringify(postData.filters);
postData._search = true;
}
return [true, ''];
}
});
$('.date').datepicker();
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "bw" });
grid.jqGrid('navGrid', '#pager', { del: false, add: false, edit: false, search: false });
});
datePick = function() {
var grid = $("#list");
$("#list")[0].triggerToolbar();
$("#list").trigger("reloadGrid", [{ page: 1 }]);
}

Resources