Adding mask in jqGrid colum on editing line - javascript

I need to create a phone mask for some columns when I add or edit a record using jqGrid (my jqGrid version is 4.5.4).
Below my code:
this.montarGRID = function (p_gridName, p_dados, p_header, p_descriptor, p_contentName, p_primaryKey, p_filtroGrid) {
jQuery("#" + p_gridName).jqGrid( {
data : p_dados,
datatype : "local",
sortable : true,
colNames : p_header,
colModel : p_descriptor,
...
This grid is generated dynamically. I pass a json with the content of colModel.
[
{"formatter":"integer","index":"id","hidden":true,"sortable":true,"sorttype":"integer","width":75,"align":"center","name":"id"},
{"formatter":"telefone","index":"TELCONTATO01","search":true,"hidden":false,"sorttype":"text","sortable":true,"width":0,"align":"right","name":"TELCONTATO01","editoptions":{"text":true,"required":false,"dataInit":"function (elem) { return mostra_telefone(elem); }"},"editrules":{"text":true,"required":false,"dataInit":"function (elem) { return mostra_telefone(elem); }"},"editable":true},
{"formatter":"telefone","index":"TELCONTATO02","search":true,"hidden":false,"sorttype":"text","sortable":true,"width":0,"align":"right","name":"TELCONTATO02","editoptions":{"text":true,"required":false,"dataInit":"function (elem) { return mostra_telefone(elem); }"},"editrules":{"text":true,"required":false,"dataInit":"function (elem) { return mostra_telefone(elem); }"},"editable":true}
]
the method that generates the phone mask ...
(function($) {
'use strict';
$.extend($.fn.fmatter, {
mostra_telefone : function (elem) {
$(elem).mask("(99)9999-9999?");
}
});
})(jQuery);
But it is never invoked when I select, change or add the record.

Here is a pice of code which do the desired behavior. For this purpose we use inputpask plugin.
$("#jqGrid").jqGrid({
...
colModel :[
{
name: 'Telephone',
width: 100,
formatter: function(cellvalue, options, rowObject) {
var re = new RegExp("([0-9]{3})([0-9]{3})([0-9]{4,6})", "g");
return cellvalue.replace(re, "($1) $2-$3");
},
unformat : function(cellvalue, options, rowObject) {
return cellvalue.replace("(",'').replace(") ",'').replace("-",'');
},
editable: true,
edittype: "custom",
editoptions :{
custom_element : function(value, options) {
var el = document.createElement("input");
el.type="text";
el.value = value;
$(el).addClass('inline-edit-cell ui-widget-content ui-corner-all').inputmask({"mask": "(999) 999-9999"});
return el;
},
custom_value : function(elem, operation, value) {
if(operation === 'get') {
return $(elem).val().replace("(",'').replace(") ",'').replace("-",'').replace(/\_/g,'');;
} else if(operation === 'set') {
$(elem).val(value);
}
}
},
editrules : {
requiered : true,
custom : true,
custom_func : function(val, name) {
// special replace mask at end
var cel = val.replace("(",'').replace(") ",'').replace("-",'').replace(/\_/g,'');
if(cel.length !== 10) {
return [false,"Please, enter correct phone number"];
}
return [true,""];
}
}
},
....
],
....
});
This code should work in you version too.
Also here is a link to the demo.

I solved the problem with this:
function custom_element_telefone(value, options){
var el = document.createElement("input");
el.type="text";
el.value = value;
$(el).addClass('inline-edit-cell ui-widget-content ui-corner-all').inputmask({"mask": "(99)9999-9999#"});
return el;
};
this.montarGRID = function (p_gridName, p_dados, p_header, p_descriptor, p_contentName, p_primaryKey, p_filtroGrid) {
p_descriptor.forEach(col => {
if (!col.editoptions) return;
if (!col.editoptions.custom_element) return;
switch (col.editoptions.custom_element) {
case "custom_element_telefone":
col.editoptions.custom_element = custom_element_telefone;
break;
}
});
jQuery("#" + p_gridName).jqGrid( {
data : p_dados,
datatype : "local",
sortable : true,
colNames : p_header,
colModel : p_descriptor,
...

Related

Datatables select first row after first load and reload

I'm using datatables and I have to select the first row of table.
The problem is select the first row when the table are reload (the table show the rooms of a building, so user can change the building).
This is my code:
function showRoom(idBuilding){
document.getElementById("roomTable").removeAttribute("style");
if ( ! $.fn.DataTable.isDataTable( '#roomTable' ) ) {
roomTable = $('#roomTable').DataTable({
responsive:true,
select: true,
"autoWidth": false,
"language": {
"emptyTable": "No room available!"
},
"ajax":{
"url": "/buildings/"+ idBuilding + "/rooms/",
"data": function ( d ) {
d.idRoomType = idRoomType;
},
"dataSrc": function ( json ) {
if (typeof json.success == 'undefined')
window.location.href = "/500";
else if (json.success){
return json.result.data;
}else{
notifyMessage(json.result, 'error');
return "";
}
},
"error": function (xhr, error, thrown) {
window.location.href = "/500";
}
},
"columns": [
{ "data": "name" },
{ "data": "capacity"},
{data:null, render: function ( data, type, row ) {
var string ="";
for (index = 0; index < data.accessories.length; ++index){
string = string + '<i aria-hidden="true" class="'+ data.accessories[index].icon+'" data-toggle="tooltip" title="'+data.accessories[index].name+'"style="margin-right:7px;" ></i>';
}
return string;
}
},
],
"fnInitComplete": function(oSettings, json) {
if (roomTable.rows().any()){
roomTable.row(':eq(0)').select();
selectedRoom(0);
}
initializeCalendar();
}
});
}
else {
roomTable.ajax.url("/buildings/"+ idBuilding + "/rooms/?idRoomType=" + idRoomType).load(selectFirstRow());
}
roomTable.off('select')
.on( 'select', function ( e, dt, type, indexes ) {
selectedRoom(indexes);
} );
roomTable.off('deselect').on( 'deselect', function ( e, dt, type, indexes ) {
reservationForm.room = -1;
$('#calendar').fullCalendar('option', 'selectable', false);
$("#calendar").fullCalendar("refetchEvents");
} );
}
function selectFirstRow(){
if (roomTable.rows().any()){
roomTable.row(':eq(0)').select();
selectedRoom(0);
}
initializeCalendar();
}
function selectedRoom(index){
var room = roomTable.rows( index ).data().toArray()[0];
reservationForm.room = room.idRoom;
$('#calendar').fullCalendar('option', 'minTime', room.startTime);
$('#calendar').fullCalendar('option', 'maxTime', room.endTime);
$('#calendar').fullCalendar('option', 'selectable', true);
$("#calendar").fullCalendar("refetchEvents");
}
On the first load all work fine, but when
roomTable.ajax.url("/buildings/"+ idBuilding + "/rooms/?idRoomType=" + idRoomType).load(selectFirstRow());
is called it seems to select the row before reload the table, so I have no row select (keep select the row of first load but now it is not visible).
Do you have idea how can I select on the load after?
UPDATE: the temporary solution is to use destroy: true but I would like a better solution like this:
if ( ! $.fn.DataTable.isDataTable( '#roomTable' ) ) {
roomTable = $('#roomTable').DataTable({
destroy: true, //it is useful because with standard code I have problem with first row selection, now it create the table each time
responsive:true,
select: true,
"autoWidth": false,
"language": {
"emptyTable": "No room available!"
},
"ajax":{
"url": "/buildings/"+ building.idBuilding + "/rooms/",
"data": function ( d ) {
d.idRoomType = idRoomType;
},
"dataSrc": function ( json ) {
if (typeof json.success == 'undefined')
window.location.href = "/500";
else if (json.success){
return json.result.data;
}else{
notifyMessage(json.result, 'error');
return "";
}
},
"error": function (xhr, error, thrown) {
window.location.href = "/500";
}
},
"fnDrawCallback": function(oSettings) {
if (roomTable.rows().any()){
roomTable.row(':eq(0)').select();
selectedRoom(0);
}
},
"fnInitComplete": function() {
initializeCalendar();
},
"columns": [
{ "data": "name" },
{ "data": "capacity"},
{data:null, render: function ( data, type, row ) {
var string ="";
for (index = 0; index < data.accessories.length; ++index){
string = string + '<i aria-hidden="true" class="'+ data.accessories[index].icon+'" data-toggle="tooltip" title="'+data.accessories[index].name+'"style="margin-right:7px;" ></i>';
}
return string;
}
},
],
});
}
else {
roomTable.ajax.url("/buildings/"+ idBuilding + "/rooms/?idRoomType=" + idRoomType).load(selectFirstRow());
}
But fnDrawCallback is called before ajax so I don't have the value, datatables keep on loading...
The fnInitComplete callback is called only when the datatable is initialized, so only once. You can use the fnDrawCallback, which is called every time the datatables redraws itself.
Just change fnInitComplete to fnDrawCallback. More about datatable callbacks (legacy version) here.

kendo grid inline edit dropdown will not expand on tab navigation

I'm having an issue with Kendo Grid in Angular where the custom drop down I've implemented will not open when tab navigating to that column. The built in text and number editor fields are editable on tab navigation but my custom drop down will not expand. I have to click on it to get the drop down effect.
My goal here is to allow the user to log an an entire row of data without having to take their hands off the keyboard.
My column is defined like so:
gridColumns.push({
field: currentField.FieldName.replace(/ /g, "_"),
title: currentField.FieldName,
editor: $scope.dropDownAttEditor,
template: function (dataItem) {
return $scope.dropDownTemplate(dataItem, currentField.FieldName);
}
});
My gridOptions are defined as follows:
$scope.gridOptions = {
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleInterval',
type: 'POST',
contentType: 'application/json'
},
update: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleIntervalUpdate',
type: 'POST',
contentType: 'application/json'
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.DrillHoleId = $scope.entity.Id;
data.DrillHoleIntervalTypeId = $stateParams.ddhinttypeid;
// convert the parameters to a json object
return kendo.stringify(data);
}
if (operation === 'update') {
// build DrillHoleIntervalDto object with all ATT/CMT values to send back to server
var drillHoleInterval = { Id: data.Id, Name: data.Name, From: data.From, To: data.To };
drillHoleInterval.Attributes = [];
drillHoleInterval.Comments = [];
var attributeFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalAttribute });
$.each(attributeFields, function (idx, attributeField) {
drillHoleInterval.Attributes.push({
Id: attributeField.AttributeDto.Id,
LookupId: data[attributeField.FieldName.replace(/ /g, "_")]
});
});
var commentFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment });
$.each(commentFields, function (idx, commentField) {
drillHoleInterval.Comments.push({
Id: commentField.CommentDto.Id,
Value: ((data[commentField.FieldName.replace(/ /g, "_")] != "") ? data[commentField.FieldName.replace(/ /g, "_")] : null)
});
});
return kendo.stringify(drillHoleInterval);
}
// ALWAYS return options
return options;
}
},
schema: { model: { id : "Id" }},
serverPaging: false,
serverSorting: false,
serverFiltering: false
//,autoSync: true
}),
columns: gridColumns,
dataBound: onDataBound,
autoBind: false,
navigatable: true,
scrollable: false,
editable: true,
selectable: true,
edit: function (e) {
var grid = $("#ddhintgrid").data("kendoGrid");
//grid.clearSelection();
grid.select().removeClass('k-state-selected');
// select the row currently being edited
$('[data-uid=' + e.model.uid + ']').addClass('k-state-selected');
e.container[0].focus();
}
};
Here is a custom event to handle the 'Tab' keypress. The point of this is I want a new record automatically added to the grid if the user presses 'Tab' at the end of the last line:
$("#ddhintgrid").keydown(function (e) {
if (e.key == "Tab") {
var grid = $("#ddhintgrid").data("kendoGrid");
var data = grid.dataSource.data();
var selectedItem = grid.dataItem(grid.select());
var selectedIndex = null
if (selectedItem != null) {
selectedIndex = grid.select()[0].sectionRowIndex;
if (selectedIndex == data.length - 1) { // if the bottom record is selected
// We need to manually add a new record here so that the new row will automatically gain focus.
// Using $scope.addRecord() here will add the new row but cause the grid to lose focus.
var newRecord = { From: grid.dataSource.data()[selectedIndex].To };
var currentCmtFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment; });
$.each(currentCmtFields, function (idx, currentCmtField) {
newRecord[currentCmtField.FieldName.replace(/ /g, "_")] = null;
});
grid.dataSource.insert(data.length, newRecord);
// edit the new row
grid.editRow($("#ddhintgrid tr:eq(" + (data.length) + ")"));
}
}
}
});
Here is my template for the drop down column:
$scope.dropDownTemplate = function (dataItem, fieldName) {
var currentLookups = $.grep($scope.currentFields, function (e) { return e.FieldName == fieldName; })[0].AttributeDto.Lookups;
var selectedLookup = $.grep(currentLookups, function (e) { return e.Id == dataItem[fieldName.replace(/ /g, "_")]; })[0];
// With the custom dropdown editor when going from null to a value the entire lookup object (id, name) is placed in the
// dataItem[field_name] instead of just the id. We need to replace this object with just the id value and return the name of
// the lookup to the template.
if (typeof selectedLookup == 'undefined' && dataItem[fieldName.replace(/ /g, "_")] != null) {
selectedLookup = angular.copy(dataItem[fieldName.replace(/ /g, "_")]);
dataItem[fieldName.replace(/ /g, "_")] = selectedLookup.Id;
}
if (selectedLookup != null && selectedLookup != '') {
return selectedLookup.Name;
}
else {
return '';
}
};
And finally here is the custom editor for the drop down column:
$scope.dropDownAttEditor = function (container, options) {
var editor = $('<input k-data-text-field="\'Name\'" k-data-value-field="\'Id\'" k-data-source="ddlDataSource" data-bind="value:' + options.field + '"/>')
.appendTo(container).kendoDropDownList({
dataSource: $.grep($scope.currentFields, function (e) { return e.FieldName == options.field.replace(/_/g, ' '); })[0].AttributeDto.Lookups,
dataTextField: "Name",
dataValueField: "Id"
});
};
I know this is a lot to take in but if you have any questions just let me know.
My ultimate goal is that I want the user to be able to navigate the grid using the 'Tab' key and edit every field without having to use the mouse.

Cannot reload data in Fuelux Datagrid

I have tried to reload the data populated by an ajax call but I cant get it to work, it shows the old data even after using the reload method. The thing is that if I change some variables to populate a different data and try to call the following code without refreshing the page it does not reload the updated data =/ Here is my code:
function populateDataGrid() {
$.ajaxSetup({async: false});
var gridinfo="";
$.post("lib/function.php",{activity: activity, shift: shift, date: date},
function (output){
gridinfo = JSON.parse(output);
});
$.ajaxSetup({async: true});
// INITIALIZING THE DATAGRID
var dataSource = new StaticDataSource({
columns: [
{
property: 'id',
label: '#',
sortable: true
},
{
property: 'date',
label: 'date',
sortable: true
},
....
],
formatter: function (items) {
var c=1;
$.each(items, function (index, item) {
item.select = '<input type="button" id="select'+c+'" class="select btn" value="select" onclick="">';
c=c+1;
});
},
data: gridinfo,
delay:300
});
$('#grid').datagrid({
dataSource: dataSource
});
$('#grid').datagrid('reload');
$('#modal-fast-appointment-results').modal({show:true});
}
I found a solution... I had to create a new DataSource (lets call it "AjaxDataSource") and add the ajax request functionality within the data constructor:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore'], factory);
} else {
root.AjaxDataSource = factory();
}
}(this, function () {
var AjaxDataSource = function (options) {
this._formatter = options.formatter;
this._columns = options.columns;
this._delay = options.delay || 0;
this._data = options.data;
};
AjaxDataSource.prototype = {
columns: function () {
return this._columns;
},
data: function (options, callback) {
var self = this;
setTimeout(function () {
var data;
$.ajax({
url: 'getdata.php',
type: 'POST',
data: 'param1:param1,param2,param2,...,paramN:paramN', // this is optional in case you have to send some params to getdata.php
dataType: 'json',
async: false,
success: function(result) {
data = result;
},
error: function(data){
//in case we want to debug and catch any possible error
// console.log(data);
}
});
// SEARCHING
if (options.search) {
data = _.filter(data, function (item) {
var match = false;
_.each(item, function (prop) {
if (_.isString(prop) || _.isFinite(prop)) {
if (prop.toString().toLowerCase().indexOf(options.search.toLowerCase()) !== -1) match = true;
}
});
return match;
});
}
var count = data.length;
// SORTING
if (options.sortProperty) {
data = _.sortBy(data, options.sortProperty);
if (options.sortDirection === 'desc') data.reverse();
}
// PAGING
var startIndex = options.pageIndex * options.pageSize;
var endIndex = startIndex + options.pageSize;
var end = (endIndex > count) ? count : endIndex;
var pages = Math.ceil(count / options.pageSize);
var page = options.pageIndex + 1;
var start = startIndex + 1;
data = data.slice(startIndex, endIndex);
if (self._formatter) self._formatter(data);
callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
}, this._delay)
}
};
return AjaxDataSource;
}));
After defining the new DataSource, we just need to create it and call the datagrid as usual:
function populateDataGrid(){
// INITIALIZING THE DATAGRID
var dataSource = new AjaxDataSource({
columns: [
{
property: 'id',
label: '#',
sortable: true
},
{
property: 'date',
label: 'date',
sortable: true
},
....
],
formatter: function (items) { // in case we want to add customized items, for example a button
var c=1;
$.each(items, function (index, item) {
item.select = '<input type="button" id="select'+c+'" class="select btn" value="select" onclick="">';
c=c+1;
});
},
delay:300
});
$('#grid').datagrid({
dataSource: dataSource
});
$('#grid').datagrid('reload');
$('#modal-results').modal({show:true});
}
So now we have our datagrid with data populated via ajax request with the ability to reload the data without refreshing the page.
Hope it helps someone!

how to nest directives created as separate modules

i like to compartmentalize my files and modules. so gist of what's going on with the code below is i'm using an angular directive to create a datatable that will list departments. what i'm trying to get to happen is be able to nest another directive in the datatable for each row that displays some buttons that will get wired up to some events and be fed some parameters. right now doesn't load/respond/do anything. can i accomplish this nesting of directives declared in separate modules? additionally, is the directive going to call forth the template for every row, and is this a bad design?
primary module file. houses the controller
angular.element(document).ready(function () {
"use strict";
var deptApp = angular.module('deptApp', ['possumDatatablesDirective','EditDeleteRowControls']);
function DepartmentCtrl(scope, http) {
scope.depts = [];
scope.columnDefs = [
{ "mData": "Id", "aTargets": [0], "bVisible": false },
{ "mData": "Name", "aTargets": [1] },
{ "mData": "Active", "aTargets": [2] },
{ "mDataProp": "Id", "aTargets": [3], "mRender": function (data, type, full) {
return '<row-controls></row-controls>';
}
}
];
http.get(config.root + 'api/Departments').success(function (result) {
scope.depts = result;
});
};
DepartmentCtrl.$inject = ['$scope', '$http'];
deptApp.controller('DepartmentCtrl', DepartmentCtrl);
angular.bootstrap(document, ['deptApp']);
});
second module
// original code came from here http://stackoverflow.com/questions/14242455/using-jquery-datatable-with-angularjs
// just giving credit where it's due.
var possumDTDirective = angular.module('possumDatatablesDirective', []);
possumDTDirective.directive('possumDatatable', ['$compile', function ($compile) {
"use strict";
function Link(scope, element, attrs) {
// apply DataTable options, use defaults if none specified by user
var options = {};
if (attrs.possumDatatable.length > 0) {
options = scope.$eval(attrs.possumDatatable);
} else {
options = {
"bStateSave": true,
"iCookieDuration": 2419200, /* 1 month */
"bJQueryUI": false,
"bPaginate": true,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bDestroy": true,
"bProcessing": true,
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$compile(nRow)(scope);
}
};
}
// Tell the dataTables plugin what columns to use
// We can either derive them from the dom, or use setup from the controller
var explicitColumns = [];
element.find('th').each(function (index, elem) {
explicitColumns.push($(elem).text());
});
if (explicitColumns.length > 0) {
options["aoColumns"] = explicitColumns;
} else if (attrs.aoColumns) {
options["aoColumns"] = scope.$eval(attrs.aoColumns);
}
// aoColumnDefs is dataTables way of providing fine control over column config
if (attrs.aoColumnDefs) {
options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);
}
// apply the plugin
scope.dataTable = element.dataTable(options);
// if there is a custom toolbar, render it. will need to use toolbar in sdom for this to work
if (options["sDom"]) {
if (attrs.toolbar) {
try {
var toolbar = scope.$eval(attrs.toolbar);
var toolbarDiv = angular.element('div.toolbar').html(toolbar);
$compile(toolbarDiv)(scope);
} catch (e) {
console.log(e);
}
}
if (attrs.extraFilters) {
try {
var filterBar = scope.$eval(attrs.extraFilters);
var filterDiv = angular.element('div.extraFilters').html(filterBar);
$compile(filterDiv)(scope);
} catch (e) {
console.log(e);
}
}
}
// this is to fix problem with hiding columns and auto column sizing not working
scope.dataTable.width('100%');
// watch for any changes to our data, rebuild the DataTable
scope.$watch(attrs.aaData, function (value) {
var val = value || null;
if (val) {
scope.dataTable.fnClearTable();
scope.dataTable.fnAddData(scope.$eval(attrs.aaData));
}
}, true);
if (attrs.selectable) {
// respond to click for selecting a row
scope.dataTable.on('click', 'tbody tr', function (e) {
var elem = e.currentTarget;
var classes = foo.className.split(' ');
var isSelected = false;
for (i = 0; i < classes.length; i++) {
if (classes[i] === 'row_selected') {
isSelected = true;
}
};
if (isSelected) {
scope.dataTable.find('tbody tr.row_selected').removeClass('row_selected');
scope.rowSelected = false;
}
else {
scope.dataTable.find('tbody tr.row_selected').removeClass('row_selected');
elem.className = foo.className + ' row_selected';
scope.selectedRow = scope.dataTable.fnGetData(foo);
scope.rowSelected = false;
}
});
}
};
var directiveDefinitionObject = {
link: Link,
scope: true, // isoalte the scope of each instance of the directive.
restrict: 'A'
};
return directiveDefinitionObject;
} ]);
third module
var EditDeleteRowControls = angular.module('EditDeleteRowControls', []);
function EditDeleteRowControlsDirective() {
"use strict";
var ddo = {
templateUrl: config.root + 'AngularTemplate/RowEditDeleteControl',
restrict: 'E'
};
return ddo;
};
EditDeleteRowControls.directive('rowControls', EditDeleteRowControlsDirective);

How to set default values if row is added using inline add button in jqgrid

Code below sets default values for new row if row is added using form.
If row is added using jqGrid inline add button from toolbar, those methods are not called and
default values are not set.
How to force inline add to perform same logic as code below ?
var lastSelectedRow;
$grid.navGrid("#grid_toppager", {
del: true,
add: true,
view: true,
edit: true
},
{},
{
addedrow: 'beforeSelected',
url: '/Grid/Add?_entity=Desktop',
beforeInitData: function () {
// todo: how to call this method from inline add
var rowid = $grid.jqGrid('getGridParam', 'selrow');
if (rowid === null) {
alert( 'Select row before adding');
return false;
}
},
afterShowForm: function(formID) {
// todo: how to set default values as this method sets from inline add
var selRowData,
rowid = $grid.jqGrid('getGridParam', 'selrow');
$('#' + 'Recordtype' + '.FormElement').val('Veerg');
$('#' + 'Nait2' + '.FormElement')[0].checked = true;
selRowData = $grid.jqGrid('getRowData', rowid);
$('#' + 'Baas' + '.FormElement').val(selRowData.Baas);
$('#' + 'Liigid' + '.FormElement').val(selRowData.Liigid);
}
);
$grid.jqGrid('inlineNav', '#grid_toppager', {
addParams: {
position: "beforeSelected",
rowID: '_empty',
useDefValues: true,
addRowParams: {
keys: true,
onEdit : onInlineEdit
}
},
editParams: {
editRowParams: {
onEdit : onInlineEdit
}
},
add: true,
edit: false,
save: true,
cancel: true
});
function onInlineEdit(rowId) {
if (rowId && rowId !== lastSelectedRow) {
cancelEditing($grid);
lastSelectedRow = rowId;
}
}
Update
I tried code
$grid.jqGrid('inlineNav', '#grid_toppager', {
addParams: {
position: "beforeSelected",
rowID: '_empty',
useDefValues: true,
addRowParams: {
keys: true,
extraparam: { _dokdata: FormData },
onSuccess : function (jqXHR) {
alert('addp oncuss');
jqXHRFromOnSuccess=jqXHR;
return true;
},
afterSave: function (rowID) {
alert('afeesave addp ');
cancelEditing($grid);
afterDetailSaveFunc(rowID,jqXHRFromOnSuccess);
jqXHRFromOnSuccess=null;
},
onError: errorfunc,
afterRestore : setFocusToGrid,
oneditfunc : function (rowId) {
var selRowData, selRowId ;
if (rowId && rowId !== lastSelectedRow) {
cancelEditing($grid);
selRowId = $grid.jqGrid('getGridParam', 'selrow');
if (selRowId ) {
selRowData = $grid.jqGrid('getRowData', selRowId );
$('#' + rowId + '_Reanr' ).val(selRowData.Reanr);
}
lastSelectedRow = rowId;
}
}
}
}
);
Only oneditfunc func is called. How to force onSuccess, afterSave, onError etc methods to be called also ?
Update 2
I added patch to jqGrid from github recommended in answer and tried
$.extend( jQuery.jgrid.inlineEdit, {
addParams: {
position: "beforeSelected",
rowID: '<%= EntityBase.NewRowIdPrefix %>',
useDefValues: true,
addRowParams: {
keys: true,
extraparam: { _dokdata: FormData },
onSuccess : function (jqXHR) {
jqXHRFromOnSuccess=jqXHR;
return true;
},
afterSave: function (rowID) {
cancelEditing($grid);
<% if (Model is RowBase ) { %>
afterDetailSaveFunc(rowID,jqXHRFromOnSuccess);
<% } else { %>
afterGridSaveFunc(rowID,jqXHRFromOnSuccess);
<% } %>
jqXHRFromOnSuccess=null;
},
onError: errorfunc,
afterRestore : setFocusToGrid,
oneditfunc : function (rowId) {
if (rowId && rowId !== lastSelectedRow) {
cancelEditing($grid);
lastSelectedRow = rowId;
}
}
}
}
} );
I this case enter does not terminate inline add. All parameters from this code are ignored.
You should use defaultValue property of the editoptions to set default values for the new added row. In the current documentation you can find that the option is valid only in Form Editing module:
The option can be string or function. This option is valid only in
Form Editing module when used with editGridRow method in add mode. If
defined the input element is set with this value if only element is
empty. If used in selects the text should be provided and not the key.
Also when a function is used the function should return value.
but if you examine the code of new addRow method you will see that
the default value of the useDefValues option is true
the method do use (see here) the defaultValue property of the editoptions.
UPDATED: OK! Now I see your problem. You used just wrong properties in editRowParams and addRowParams parts of the settings. Correct will be:
$grid.jqGrid('inlineNav', topPagerSelector, {
addParams: {
position: "beforeSelected",
rowID: '_empty',
useDefValues: true,
addRowParams: {
keys: true,
oneditfunc : onInlineEdit
}
},
editParams: {
keys: true,
oneditfunc: onInlineEdit
},
add: true,
edit: false,
save: true,
cancel: true
});
Moreover you can use new $.jgrid.inlineEdit feature to set keys, oneditfunc or other parameters of inline editing. The implementation of the feature is not full correct, but you can examine the current version from github (see here) and do the same modification in your version of jquery.jqGrid.src.js. In any way I would recommend to use the $.jgrid.inlineEdit feature after publishing the next version of jqGrid. The advantage is that you can easy set options of editRow independent from where the function will be called (from inlineNav, 'actions' formatter or any other way).
New jqGridInlineEditRow event feature (see here for more information) will allow you to implement actions like what you do now inside of onInlineEdit event without the usage of oneditfunc which can be set only one time.

Categories

Resources