jqGrid inline-edit POST without editurl? - javascript

I am trying to find the information about editurl. Currently, i am working on the framework which does not permit editurl. The calls must go through javascript function which in-turn invokes the component on serverside.
Question is it possible to POST the data to javascript function instead of editurl?
I am experimenting with following:
$(document).ready(function () {
console.log(">>>1");
//--
action.setCallback(this, function(a) {
if (a.getState() === "SUCCESS") {
result = a.getReturnValue();
console.log(result);
//---=
var editActionOptions = {
keys: true,
url:null,
oneditfunc: function (rowid) {
console.log("row with rowid=" + rowid + " is editing.");
},
aftersavefunc: function (rowid, response, options) {
console.log("row with rowid=" + rowid + " is successfuly modified.");
}
};
//-------------------------------------------------------------------------------------------------------
$("#jqGrid").jqGrid({
editurl: 'clientArray',
datatype: "local",
data:result,
colModel: [
{
label: "Edit Actions",
name: "actions",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{
labe: 'ID',
name: 'empid',
width: 75
},
{
label : 'Name',
name: 'Name',
width: 140,
editable: true // must set editable to true if you want to make the field editable
},
{
label: 'dob',
name: 'dob',
width: 100,
editable: true
},
{
label: 'dln',
name: 'dln',
width: 120,
editable: true
}
],
sortname: 'empid',
loadonce: true,
onSelectRow: editRow,
onSave:onSaveRow,
editParams: editActionOptions,
width: 780,
height: 400,
rowNum: 150,
pager: "#jqGridPager"
});
//------------------------------------------------------------------------------------------------------
} else if (a.getState() === "ERROR") {
$A.log("Errors", a.getError());
}
});
$A.enqueueAction(action);
var lastSelection;
function editRow(id) {
console.log(id);
if (id && id !== lastSelection) {
var grid = $("#jqGrid");
grid.jqGrid('restoreRow',lastSelection);
grid.jqGrid('editRow',id, {keys: true} );
lastSelection = id;
}
};
function onSaveRow(id){
console.log(id);
}

Related

jqgrid modify post data in upload image row

I just make functional on my application in order to upload image, convert it to base64 and send to server as base64 string.
I found function to convert image to base64. It works fine. I use jqgrid standart forms to create and edit data. Image uploads but I need to change post data before post to add base64 string to param value.
I use serializeEditData but it works faster than my function converts image to string. I used callback function and it doesn't work.
serializeEditData: function (postData) {
var fileContainer = document.getElementById('photo').files;
var reader = new FileReader();
reader.readAsDataURL(fileContainer[0]);
reader.onload = function () {
postData.image = reader.result;
};
/* I used this too
var fileContainer = document.getElementById('photo').files;
getBase64(fileContainer[0], function (result) {
postData.image = result;
});*/
return postData;
},
If I console log formData before return statement it shows me postData with image base64 string. But problem what return statement works faster than postData.image set string.
My getBase64 function code:
function getBase64(file, callback) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
callback(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
And my full code:
jQuery(function ($) {
var quiz_table_id = $("#quiz_table_id");
var quiz_pager_id = "#quiz_pager_id";
var colNames = ['id', 'title', 'description', 'section', 'section', 'image', 'image'];
var postDataGlobal;
var template = {width: 160, fixed: true, align: 'center', editable: true, stype: 'text'};
var colModel = [
{
name: 'id',
index: 'id',
sortname: 'id',
editable: true,
sorttype: 'number'
},
{
name: 'title',
index: 'title',
sortname: 'title',
template: template,
sorttype: 'number'
},
{
name: 'description',
index: 'description',
sortname: 'description',
width: 120,
fixed: true, align: 'center', editable: true,
template: "number",
sorttype: 'number'
},
{
name: 'section.name',
sortname: 'section.name',
formatter: null,
sorttype: 'number',
editable: false
},
{
name: 'section.id',
sortname: 'section.id',
formatter: 'select',
edittype: "select",
hidden: true,
editable: true,
editrules: {edithidden: true, required: true},
editoptions: {value: "1:Java"}
/*editoptions: {
dataInit: function (elem) {
$.get("http://localhost:8080/section/get-all-map", function (data, status) {
$(elem).empty();
Object.keys(data).map(function (key, index) {
console.log(data[key] + " " + key);
$(elem).append("<option value=" + key + ">" + data[key] + "</option>")
});
});
}
}*/
},
{
name: 'image',
index: 'image',
sortname: 'image',
template: template,
sorttype: 'number',
editable: true
},
{
name: 'photo',
index: 'photo',
search: false,
editable: true,
edittype: 'file',
editoptions: {
enctype: "multipart/form-data"
},
align: 'center',
}
];
quiz_table_id.jqGrid({
url: 'http://localhost:8080/quiz/get-all',
datatype: "json",
jsonReader: {
repeatitems: true
},
height: 'auto',
colNames: colNames,
colModel: colModel,
shrinkToFit: false,
forceFit: true,
pager: quiz_pager_id,
toppager: true,
rowNum: 10,
rowList: [5, 10, 15, 20, 25, 30],
loadonce: true,
colMenu: true,
menubar: true,
viewrecords: true,
storeNavOptions: true,
editurl: 'http://localhost:8080/quiz/save',
loadComplete: function () {
},
gridComplete: function () {
}
});
//navButtons
quiz_table_id.jqGrid('navGrid', quiz_pager_id,
// the buttons to appear on the toolbar of the grid
{
edit: true,
add: true,
del: true,
search: true,
refresh: true,
view: true,
position: "left",
cloneToTop: false
},
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
recreateForm: true,
checkOnUpdate: true,
checkOnSubmit: true,
closeAfterEdit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
},
serializeEditData: function (postData) {
var fileContainer = document.getElementById('photo').files;
var reader = new FileReader();
reader.readAsDataURL(fileContainer[0]);
reader.onload = function () {
postData.image = reader.result;
};
/* I used this too
var fileContainer = document.getElementById('photo').files;
getBase64(fileContainer[0], function (result) {
postDataGlobal.image = result;
});*/
return postData;
},
beforeSubmit: function (data) {
return [true, ''];
}
},
// options for the Add Dialog
{
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
{
multipleSearch: true,
showQuery: true
} // search options - define multiple search
);
$(window).triggerHandler('resize.jqGrid');
quiz_table_id.triggerHandler("jqGridAfterGridComplete");
});
function getBase64(file, callback) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
callback(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}

Kendo UI grid comboBox undefined on focus out?

I have working on Keno UI grid and I have added a comboBox as a column in the grid which also supports autocomplete feature. Apparently, comboBox is working fine but when I type half of world and focus out of the comboBox cell then it shows undefined. I have tried to handle it on combobox change event, but it is still showing undefined value? Below is my code for combobox and grid.
function productDropDownEditor(container, options) {
$('<input id="ProductDropDown" style="width:250px;" data-bind="value:' + options.field + '"/>')
.appendTo(container).kendoComboBox({
dataSource: dataSource,
autoBind: false,
dataTextField: 'ProductName',
dataValueField: 'ProductID',
filter: "contains",
suggest: true,
index: 3,
change: function (e) {
debugger;
var cmb = this;
// selectedIndex of -1 indicates custom value
if (cmb.selectedIndex < 0) {
cmb.value(0); // or set to the first item in combobox
}
},
close: function (e) {
debugger;
var cmb = this;
}
});
And here is following code for kendo grid.
$(function () {
$("#grid").kendoGrid({
columns: [
{
field: "Products", width: "250px",
editor: productDropDownEditor,
title: "Product",
template: "#=Products.ProductName#",
attributes: {
"class": "select2_single"
}
},
{ field: "PurchasePrice", width: "150px" },
{ field: "PurchaseQuantity", width: "150px" },
{ field: "SaleRate", title: "Sale Rate", width: "150px" },
{ field: "Amount", title: "Amount", width: "150px" },
{ command: "destroy", title: "Delete", width: "110px" },
],
editable: true, // enable editing
pageable: true,
navigatable: true,
sortable: true,
editable: "incell",
toolbar: ["create"], // specify toolbar commands
edit: function (e) {
//debugger;
//// var parentItem = parentGrid.dataSource.get(e.model.PurchaseID);
////e.model.set("ShipCountry", parentItem.Country);
//if (e.model.isNew()) {
// // set the value of the model property like this
// e.model.set("PropertyName", Value);
// // for setting all fields, you can loop on
// // the grid columns names and set the field
//}
},
//editable: "inline",
dataSource: {
serverPaging: true,
requestStart: function () {
kendo.ui.progress($("#loading"), true);
},
requestEnd: function () {
kendo.ui.progress($("#loading"), false);
},
serverFiltering: true,
serverSorting: true,
batch: true,
pageSize: 3,
schema: {
data: "data",
total: "Total",
model: { // define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
PurchaseID: { editable: false, nullable: true },
PurchasePrice: { nullable: true },
PurchaseQuantity: { validation: { required: true, min: 1 } },
SaleRate: { validation: { required: true, min: 1 } },
Amount: { type: "number", editable: false },
Products: {
nullable: false,
validation: { required: true},
defaultValue: {ProductID:1, ProductName:"Googo" },
//from: "Products.ProductName",
parse: function (data) {
debugger;
if (data == null) {
data = { ProductID: 1};
}
return data;
},
type: "object"
}
}
}
},
batch: true, // enable batch editing - changes will be saved when the user clicks the "Save changes" button
change: function (e) {
debugger;
if (e.action === "itemchange" && e.field !== "Amount") {
var model = e.items[0],
type = model.Type,
currentValue = model.PurchasePrice * model.PurchaseQuantity;//formulas[type](model);
if (currentValue !== model.Amount) {
model.Amount = currentValue;
$("#grid").find("tr[data-uid='" + model.uid + "'] td:eq(4)").text(currentValue);
}
//if (e.field == "Products") {
// $("#grid").find("tr[data-uid='" + model.uid + "'] td:eq(0)").text(model.Products);
//}
}
},
transport: {
read: {
url: "#Url.Action("Read", "Purchase")", //specify the URL which should return the records. This is the Read method of the HomeController.
contentType: "application/json",
type: "POST", //use HTTP POST request as by default GET is not allowed by ASP.NET MVC
},
parameterMap: function (data, operation) {
debugger;
if (operation != "read") {
// post the products so the ASP.NET DefaultModelBinder will understand them:
// data.models[0].ProductID = data.models[0].Product.ProductID;
var result = {};
// data.models[0].ProductID = $("#ProductDropDown").val();
for (var i = 0; i < data.models.length; i++) {
var purchase = data.models[i];
for (var member in purchase) {
result["purchaseDetail[" + i + "]." + member] = purchase[member];
}
}
return result;
} else {
var purchaseID = $("#hdnPurchaseId").val();
//output = '{ purchaseID: ' + purchaseID + '}';
data.purchaseID = purchaseID; // Got value from MVC view model.
return JSON.stringify(data)
}
}
}
},
}).data("kendoGrid");

Unable to bind the data to dropdown in jqgrid when it is editing getting data using web api

$j(document).ready(function () {
$j.ajax({
type: "GET",
url: "http://localhost:9611/api/Master/GetBackendUsersList",
contentType: "json",
dataType: "json",
success: function (data) {
var dataList;
var StatusList = '';
$j('#list2').jqGrid({
caption: "Users Details",
data: data,
datatype: "local",
height: '100%',
width: '100%',
colNames: ["UserName", "RoleId", "Name", "RoleName", "LoginId"],
colModel: [
{ name: "UserName", index: 'UserName', editable: true },
{ name: 'RoleId', index: "RoleId", hidden: true, width: 150, editable: true },
{ name: "Name", index: "Name", editable: true },
{
name: "RoleName", index: "RoleName", editable: true, edittype: 'select', editoptions: {
dataInit: function (element)
{
$j.ajax({
type: "GET",
url: "http://localhost:9611/api/Master/GetRoles",
contentType: "json",
dataType: "json",
success: function (mydata) {
dataList = mydata;
for (var i = 0; i < dataList.length; i++) {
//if (StatusList == "")
// StatusList = dataList[i].RoleId + ":" + dataList[i].RoleName;
//else
StatusList = StatusList + dataList[i].RoleId + ":" + dataList[i].RoleName+ ';' ;
}
}
});
},
value: "0:Select;" + StatusList,
}
},
{ name: 'LoginId', index: "LoginId", hidden: true, width: 150 }
],
gridview: true,
rowNum: 5,
rowList: [5, 10, 15],
pager: '#jQGridDemoPager',
sortname: "UserName",
viewrecords: true,
sortorder: "desc",
//width: '100%',
//height: '100%',
shrinkToFit: false,
editurl: SiteUrl + "api/Master/UpdateBackendUserDetails/" ,
});
$j.extend(true, $j.jgrid.edit, {
recreateForm: true,
beforeShowForm: function ($jform) {
$jform.closest(".ui-jqdialog").position({
of: window, // or any other element
my: "center center",
at: "center center"
});
}
});
$j('#list2').jqGrid('navGrid', '#jQGridDemoPager',
{
add: false,
search: false,
recreateForm: true,
beforeShowForm: function ($jform) {
$jform.find(".FormElement[readonly]")
.prop("disabled", true)
.addClass("ui-state-disabled")
.closest("LoginId")
.prev(".CaptionTD")
.prop("disabled", true)
.addClass("ui-state-disabled");
},
},
{ recreateForm: true }
);
}
});
});
Dropdown data from api is like:
[{"RoleId":1,"RoleName":"Administrator"},{"RoleId":2,"RoleName":"Sales"},{"RoleId":3,"RoleName":"Secretory/President"},{"RoleId":4,"RoleName":"Apartment Owner"},{"RoleId":5,"RoleName":"Apartment User"}]
Use this way :
editoptions:{value: getData()}
and then create one method
function getData(){
var states = [{"RoleId":1,"RoleName":"Administrator"},{"RoleId":2,"RoleName":"Sales"},{"RoleId":3,"RoleName":"Secretory/President"},{"RoleId":4,"RoleName":"Apartment Owner"},{"RoleId":5,"RoleName":"Apartment User"}];
return states;
}
In your case you need to add ajax call in getData() and return values/array which has been created by the result.

JQGrid date sorting and search

I am currently displaying a particular set of data in jqgrid. I want to sort and search the column Job Date, but it does not work.
The date is being displayed as 2015-08-26 but neither sorting nor search works.
Am I missing something.
var gridSelector = "#tblist";
var emptyMsgDiv = $("<div style=\"text-align:center\"><span style='color:red;font-size:24px'>No records found</span></div>");
jQuery(gridSelector).jqGrid({
url: '#Url.Action("ListActivities", "DailyActivity")',
loadonce: true,
datatype: 'json',
shrinkToFit: true,
autowidth: true,
mtype: 'GET',
ignoreCase: true,
colNames: ['Edit', 'ActivityID', 'Job No', 'Job Date',...],
colModel: [
{ name: 'Edit', index: 'Edit', formatter: EditBind, width: '50px', search: false, sortable: false },
{ name: 'ActivityID', index: 'ActivityID', hidden: true },
{ name: 'DOWJobNumber', index: 'DOWJobNumber', align: 'left', width: '100px' },
{
name: 'DOWJobDate', index: 'DOWJobDate', width: '70px',
formatter: 'date',
sorttype: 'date',
formatoptions: {srcformat:'ISO8601Long', newformat: 'ISO8601Short' },
datefmt: 'ISO8601Short',
searchoptions: {
sopt: ['eq', 'gt', 'ge'],
dataInit: function (el) {
$(el)
.datepicker({ dateFormat: "yy-mm-dd" })
.change(function () {
$(gridSelector)[0].triggerToolbar();
});
}
}
},
{ ... },...
],
height: 'auto',
pager: '#gridpager',
rowNum: 20,
rowList: [5, 10, 20, 50, 100],
sortname: 'ActivityID',
sortorder: 'desc',
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
loadError: function (xhr, st, err) {
bootbox.alert("Error retrieving data!");
},
emptyrecords: 'No Records found',
loadComplete: function () {
emptyMsgDiv.insertAfter($('#tblist').parent());
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
}
})
.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
Edit: It looks like the search is being made on the JSON format(/Date(1430937000000)/). How can this be changed to search and sort using the specified date format
I had to format the date time as text in the controller and processed it in the JQGrid as below
{
name: 'DOWJobDateText', index: 'DOWJobDateText', width: '80px',
formatter: 'date',
sorttype: 'date',
formatoptions: { srcformat: 'd/m/Y', newformat: 'd/m/Y' },
datefmt: 'd/m/Y',
searchoptions: {
dataInit: function (el) {
$(el)
.datepicker({ dateFormat: "dd/mm/yy" })
.change(function () {
$(gridSelector)[0].triggerToolbar();
});
}
}
}

jqGrid doesn't rise ondblClickRow event when filter applied

This is event calling filtering while typing:
$("#txtPickItem").change(function (e) { doSearchPick(); });
This is my jqGrid:
$("#gridChooseItems").GridUnload();
jQuery("#gridChooseItems").jqGrid({
url: 'MyURL', datatype: "JSON",
colNames: ['id', 'Group', 'Source order'...],
colModel: [
{ name: 'del', index: ' ', width: 28, hidden: true },
{ name: 'id', index: 'id', hidden: true },
{ name: 'Group', index: 'Group', hidden: true },
{ name: 'Code', index: 'Code', width: 180 }...
],
loadComplete: function () { if ($("#txtPickItem").val()) { setTimeout('doSearchPick();', 100); } },
rowNum: 25, rowList: [10, 25, 50, 100, 200],
pager: '#pagerChooseItems',
sortname: 'id',
ondblClickRow: function (id) { AddItem(id); },
height: 580,
width: 1050,
ignoreCase: true,
loadonce: true,
viewrecords: true,
sortorder: "desc",
caption: "Available items"
});
My filtering function:
function doSearchPick() {
var grid = $("#gridChooseItems");
var filter = {
"groupOp": "AND", "rules":
[
{ "field": "Supplier", "op": "cn", "data": $("#txtPickItem").val() }
]
};
grid.jqGrid('setGridParam', { search: true, postData: { filters: filter } });
grid.trigger("reloadGrid", [{ page: 1 }]);
}
I have to reload grid after doubleclick and apply filter so previously double clicked item is not in grid anymore (many things happens in between).
When $("#txtPickItem") is empty, ondblClickRow and everything works fine, filtering works fine too.
Problem is that when some text is contained in txtPickItem, ondblClickRow doesn't fire and I don't understand why. I need this ondblClickRow event desperately.
EDIT:
AddItem function works fine as everything else if $("#txtPickItem") is empty
function AddItem(id) {
pData = {}
pData["ItemID"] = id;
jQuery.ajax({
url: 'URL',
type: "POST",
dataType: "JSON",
data: pData,
success: function (data) {
if (data == "msg1") {
PopulatePickGridItems(); //fill some other grid
}
else if (data == "msg2") {
$("#divMsg").html("<ul><li>err1. msg.</li></ul>")
$('#dlgMsg').dialog('open');
}
else {
$("#divMsg").html("<ul><li>err2. msg.</li></ul>")
$('#dlgMsg').dialog('open');
}
}
});
}

Categories

Resources