Displaying Form details in slickgrid on submit - javascript

In my JSP page I have a form with many details to be entered, once the user click the submit then I want to display the results in a grid below the form as an item.
I am fetching each details using JSP Scriptlet and assigning it to slickgrid, here is the code for doing that
<script>
var grid;
dataView = new Slick.Data.DataView();
var columns = [
{id: "SlNo", name: "SlNo", field: "SlNo"},
{id: "ItemName", name: "ItemName", field: "ItemName"},
{id: "PartNo", name: "PartNo", field: "PartNo"},
{id: "BatchNo", name: "BatchNo", field: "BatchNo"},
{id: "UnitRate", name: "UnitRate", field: "UnitRate"},
{id: "Quantity", name: "Quantity", field: "Quantity"},
{id: "Discount", name: "Discount", field: "Discount"},
{id: "NetAmount", name: "NetAmount", field: "NetAmount"},
{id: "TaxRate", name: "TaxRate", field: "TaxRate"},
{id: "TaxAmount", name: "TaxAmount", field: "TaxAmount"},
{id: "TotalAmount", name: "TotalAmount", field: "TotalAmount"}
];
var options = {
enableCellNavigation: true,
enableColumnReorder: false
};
grid = new Slick.Grid("#myGrid", dataView, columns, options);
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
grid.render();
});
$('#btnSubmit').click(function() {
var data = [];
var i=0;
<%ERPConnectionManager erpConn = (ERPConnectionManager) session.getAttribute("erpCon");
ConfirmFunction(request, erpConn);
ArrayList<SalesRecCdty> listSalesRec = (ArrayList<SalesRecCdty>) session.getAttribute("listval");
Iterator itrn = listSalesRec.iterator();
while (itrn.hasNext()) {
SalesRecCdty salesrec = (SalesRecCdty) itrn.next();
String itemName = salesrec.getCommName().toString();
String partNo = "";
String batchNo = salesrec.getBatchNo();
String unitRate = String.valueOf(salesrec.getUnitrate());
String quanity = String.valueOf(salesrec.getReqQty());
String discount = String.valueOf(salesrec.getDiscount());
String netAmount = String.valueOf(salesrec.getNetValue());
String taxRate = String.valueOf(salesrec.getTaxpercent());
String taxAmount = String.valueOf(salesrec.getTaxtotal());
String totAmount = String.valueOf(salesrec.getTotalvalue());
%>
data[i]={
SlNo: i+1,
ItemName:"<%= itemName%>",
PartNo:"<%= partNo%>",
BatchNo:"<%= batchNo%>",
UnitRate:"<%= unitRate%>",
Quantity:"<%= quanity%>",
Discount:"<%= discount%>",
NetAmount:"<%= netAmount%>",
TaxRate:"<%= taxRate%>",
TaxAmount:"<%= taxAmount%>",
TotalAmount:"<%= totAmount%>"
};
i++;
<%
}
%>
// grid = new Slick.Grid("#myGrid", data, columns, options);
dataView.beginUpdate();
dataView.setItems(data);
dataView.endUpdate();
});
e.preventDefault();
var ajaxdata = $('#cbobxOffice').val();
$.ajax({
cache: false,
success: function(data) {
}
});
</script>
I am able to fetch the data to the data array.. but the rows are not displayed in the grid, please help

Related

Cascading dropdowns in DataTables

I have defined my datatables editor as follows :
editor = new $.fn.dataTable.Editor({
ajax: "./DataServlet",
table: "#example",
legacyAjax: true,
idSrc: "rowID",
fields: [{
label: "Data Id",
name: "dataId",
type: "readonly"
},{
label: "Name",
name: "name",
type: "readonly"
},{
label: "Field L1",
name: "fieldL1",
type: "selectize",
options: getFieldL1()
},{
label: "Field L2",
name: "fieldL2",
type: "selectize",
options: getFieldL2()
},{
label: "Field L3",
name: "fieldL3",
type: "selectize",
options: getFieldL3()
},{
label: "User Name",
name: "userName",
type: "readonly"
}],
});
The fieldL3 value is dependent on fieldL2 which is dependent on fieldL1.
The dependency is as shown in the table below :
So, initially the fieldL1 dropdown values would be [A,B,C] and if value I select is 'A', then fieldL2 dropdown values should only be [Q,W,R] and if I select 'Q' for fieldL2, the fieldL3 dropdown should only have [T,U].
So, far I have tried the following :
$("#DTE_Field_fieldL1").on('change', function(data) {
let c1_value = data.currentTarget.value;
let c2_opts = $(".DTE_Field_Name_fieldL2 .selectize-dropdown-content")[0].children;
let valid_c2_opts = Object.keys(json[c1_value]);
for(let i = 0; i < c2_opts.length; i++) {
if(valid_c2_opts.includes(c2_opts[i].dataset.value))
{
c2_opts[i].className = "option";
}
else {
c2_opts[i].className = "option d-none";
}
}
editor.enable('fieldL2');
});
$("#DTE_Field_fieldL2").on('change', function(data) {
let c1_value = $("#DTE_Field_fieldL1")[0].value;
let c2_value = data.currentTarget.value;
let c3_opts = $(".DTE_Field_Name_fieldL3 .selectize-dropdown-content")[0].children;
let valid_c3_opts = Object.values(json[c1_value][c2_value]);
for(let i = 0; i < c3_opts.length; i++) {
if(valid_c3_opts.includes(c3_opts[i].dataset.value ))
{
c3_opts[i].className = "option";
}
else {
c3_opts[i].className = "option d-none";
}
}
editor.enable('fieldL3');
});
So, the json has the data separated in JSON format and I am trying to hide/show the values based on what is selected.
The issue I am facing with the above approach is whenever I try to change a value, the onChange function doesn't get called.
How do I achieve it in the datatables editor?

Loop in Grid EXTJs

I have some store, which is formed data. On panel it looks how "fieldName" and text field (in depension from invoked form). For example, on one form is displayed "name document" and field, on another: date of selling and date field. Data is formed dynamicly
Here is store:
tableTempStore = new Ext.data.JsonStore({
url: objectUrlAddress,
baseParams: {
'objectID': objectID
},
root: 'Fields',
fields: [{
name: 'Type',
type: 'int'
}, {
name: 'Value'
}, {
name: 'IsRequired',
type: 'bool'
}, {
name: 'Identifier'
}, {
name: 'Data'
}],
listeners: {
load: function(obj, records) {
Ext.each(records, function(rec) {
var item = null;
switch (rec.get('Type')) {
case 0:
item = new Ext.form.NumberField();
item.id = rec.get('Identifier');
item.fieldLabel = rec.get('Hint');
var isRequired = rec.get('IsRequired');
item.anchor = '100%';
item.allowBlank = !isRequired;
item.disabled = editDisabled;
item.value = rec.get('Data');
break;
case 1:
item = new Ext.form.NumberField();
item.id = rec.get('Identifier');
item.fieldLabel = rec.get('Hint');
var isRequired = rec.get('IsRequired');
item.anchor = '100%';
item.allowBlank = !isRequired;
item.allowDecimals = true;
item.disabled = editDisabled;
item.value = rec.get('Data');
break;
}
if (item != null) {
templateGrids.add(item);
columnsTable = item.__proto__.constructor.xtype;
source[item.fieldLabel] = '';
var s = null;
if (columnsTable == 'textfield')
{
s = 'textfield';
colm = {
xtype: s,
id: item.id,
allowBlank: item.allowBlank,
format: item.format,
value: item.value,
editable: true,
emptyText: item.emptyText,
disabled: item.disabled
};
}
else if (columnsTable == 'combo')
{
s = 'combo';
colm = {
xtype: s,
id: item.id,
allowBlank: item.allowBlank,
format: item.format,
value: item.value,
editable: true,
emptyText: item.emptyText,
disabled: item.disabled
};
}
else if (columnsTable == 'datefield')
{
s = 'datefield';
colm = {
xtype: s,
id: item.id,
allowBlank: item.allowBlank,
format: item.format,
value: item.value,
editable: true,
emptyText: item.emptyText,
disabled: item.disabled
};
}
});
for (var i = 0; i < templateGrids.getStore().data.length; i++) {
templateGrids.getColumnModel().setConfig([
{header: 'Name', id:'name', width:200},
{header:'Value', id:'val', dataIndex: rec.get('Value'), editable:true, width:200, editor: colm}]);
};
}
}
});
This code had worked in a form, but I need to use Grid (or Editor Grid). I know, how displayed field name ("document name" and etc.), but I don't understand, how displayed text field or etc. I try use loop, but on second column in xtype displayed last type in store. How i can resolve this problem?!
Here is a grid:
var templateGrids = new Ext.grid.EditorGridPanel({
id: 'tableId',
height:300,
width: '100%',
clicksToEdit:1,
frame: true,
store: tableTempStore,
columns: [
{header: 'Name'},
{header: 'Value'}]
});

Slickgrid - how to modify id value

I'm just getting to grips with Slickgrid (with an asp.net MVC back end) as a simple start I want to us it as an editing grid for a Key/Value pair of systems settings. I have it working OK for Add, but update works OK unless we edit the key.
Because we have changed the key value it always looks like a new Key/Value pair rather than modifying the existing item. So my question is, how do I let the backend know what item I am modifying ?
I figure I could add an extra field (holding the original id) to the dataview, but I am kind of wondering if I a missing some functionality that makes this easier.
$(function() {
var grid;
var columns = [{
id: "id",
name: "Name",
field: "id",
editor: Slick.Editors.Text
}, {
id: "Value",
name: "Value",
field: "Value",
editor: Slick.Editors.Text
}, ];
var options = {
enableColumnReorder: false,
editable: true,
enableAddRow: true,
enableCellNavigation: true,
autoEdit: false
};
var dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.onCellChange.subscribe(function(e, args) {
var row = dataView.getItem(args.row);
var value = row[grid.getColumns()[args.cell].field];
var id = row[grid.getColumns()[0].field];
var data = {
value: value,
id: id
};
var url = "#Url.Action("Update", "SystemSettings")";
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(a) {
if (a.status != "ok") {
alert(a.msg);
undo();
} else {
alert(a.msg);
}
return false;
}
});
});
grid.onAddNewRow.subscribe(function(e, args) {
var item = {
"id": dataView.length,
"value": "New value"
};
$.extend(item, args.item);
dataView.addItem(item);
});
dataView.onRowCountChanged.subscribe(function(e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function(e, args) {
grid.invalidateRows(args.rows);
grid.render();
});
$.getJSON('#Url.Action("GetAll", "SystemSettings")', function(data) {
dataView.beginUpdate();
dataView.setItems(data);
dataView.endUpdate();
});
});
My requirement is for a grid that allows users to be able to perform all the basic CRUD functions on a database table. So am I going in the right direction with this or should I be doing something different.
So, I guess I hadn't quite grasped how the data view is disconnected from the grid. So I decided to store the key field twice in there once as a (non editable) Id field and once as an editable name field.
Once I realised that I could detect the old & new versions of the key field:
$(function () {
var grid;
var columns = [
{ id: "name", name: "Name", field: "name", editor: Slick.Editors.Text },
{ id: "value", name: "Value", field: "value", editor: Slick.Editors.Text },
];
var options = {
enableColumnReorder: false,
editable: true,
enableAddRow: true,
enableCellNavigation: true,
autoEdit: false
};
var dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.onCellChange.subscribe(function (e, args) {
var row = dataView.getItem(args.row);
var id = row["id"];
var value = row["value"];
var name = row["name"];
var data = { value: value, id: id, name: name };
var url = "#Url.Action("Update", "SystemSettings")";
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function (a) {
if (a.status != "ok") {
alert(a.msg);
undo();
} else {
alert(a.msg);
}
return false;
}
});
});
grid.onAddNewRow.subscribe(function (e, args) {
var item = { "id": args["name"], "value": "New value" };
$.extend(item, args.item);
dataView.addItem(item);
});
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
grid.render();
});
$.getJSON('#Url.Action("GetAll", "SystemSettings")', function (data) {
dataView.beginUpdate();
dataView.setItems(data);
dataView.endUpdate();
});
});

Adding items to a Kendo multiSelect

I've got a Kendo Grid and on its DataBound event, I want to add its data source to a Kendo MultiSelect. So, when the data from the grid is loaded, the below function is fired.
Here's what I have tried so far, without success, but from the code you can see what I intend:
function addToMultiSelect() {
var multiSelect = $("#multiSelect").data("kendoMultiSelect");
var grid = $("#grid").data("kendoGrid");
var places = grid.dataSource._data;
for (var i = 0; i < places.length; i++) {
var row = instPlaces[i];
var id = row.Id;
var mediumDescription = row.MediumDescription;
alert(id + " - " + mediumDescription);
multiSelect.dataSource.insert(i, { text: mediumDescription, value: id })
}
multiSelect.dataSource.read();
}
The alert properly shows the id and description of all the datagrid's items, so, I'm getting the data from the grid right.
I add them to the multiSelect's datasource, the last line is to refresh it and show the new data, but it doesn't. The multiSelect remains empty.
Try the following:
function addToMultiSelect() {
var multiSelect = $("#multiSelect").data("kendoMultiSelect");
var grid = $("#grid").data("kendoGrid");
var places = grid.dataSource.data();
// Read original data content
var multiData = multiSelect.dataSource.data();
for (var i = 0; i < places.length; i++) {
...
// insert new element into copy of multiselect data
multiData.push({ text: mediumDescription, value: id })
}
// Write back the modified data
multiSelect.dataSource.data(multiData);
}
See the following code example:
$(document).ready(function() {
function addToMultiSelect(e) {
var grid = this;
var data = this.dataSource.data();
var multiData = [];
for (var i = 0; i < data.length; i++) {
multiData.push({ text: data[i].ShipName, value: i });
}
multi.dataSource.data(multiData);
}
var multi = $("#multi").kendoMultiSelect({
dataSource: {
data: [
{ text: "ship 1", value: 1 },
{ text: "ship 2", value: 2 },
{ text: "ship 3", value: 3 },
{ text: "ship 4", value: 4 }
]
},
dataTextField: "text",
dataValueField: "value"
}).data("kendoMultiSelect");
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: addToMultiSelect,
height: 550,
columns: [
"OrderID",
"Freight",
{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShipCity",
title: "Ship City"
}
]
});
});
html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1316/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1316/js/kendo.all.min.js"></script>
Ship Names copied from Grid DataSource: <input id="multi"/>
Grid
<div id="grid"></div>

Filtering jqGrid by multiple conditions at client side

I have a jqGrid with some records and want to filter the records based on multiple conditions.
For instance, if there are three columns, Name, Age and City and I want to filter the grid on the following condition:
Name = "Mark" and Age = 25 and City = 'NY'
the following code works fine-
var grid = jQuery("#memberDetails");
var postdata = grid.jqGrid('getGridParam', 'postData');
var filterArray = new Array();
var filterConidtion;
filterConidtion = new Object();
filterConidtion.field = "name";
filterConidtion.op = "eq";
filterConidtion.data = "Mark";
filterArray.push(filterConidtion);
filterConidtion = new Object();
filterConidtion.field = "Age";
filterConidtion.op = "eq";
filterConidtion.data = "25";
filterArray.push(filterConidtion);
filterConidtion = new Object();
filterConidtion.field = "City";
filterConidtion.op = "eq";
filterConidtion.data = "NY";
filterArray.push(filterConidtion);
jQuery.extend(postdata, {
filters: {
"groupOp": "and",
"rules": filterArray
}
});
grid.jqGrid('setGridParam', {
search: true,
postData: postdata
});
grid.trigger("reloadGrid", [{
page: 1
}]);
but I am not sure how to make the following filter work:
Name = "Mark" and Age = 25 and (City = 'NY' OR City = 'FL')
The groupOp works either on AND or on OR condition, not sure how to embed a sub condition within the groupOp
Thanks.
Format of filters are described in the documentation. To implement more complex searching criteria one can use groups property of filters. The corresponding code could be about the following:
var $grid = $("#memberDetails");
$.extend($grid.jqGrid("getGridParam", "postData"), {
filters: JSON.stringify({
groupOp: "AND",
rules: [
{ field: "Name", op: "eq", data: "Mark" },
{ field: "Age", op: "eq", data: "25" }
],
groups: [
{
groupOp: "OR",
rules: [
{ field: "City", op: "eq", data: "NY" },
{ field: "City", op: "eq", data: "FL" }
],
groups: []
}
]
})
});
$grid.jqGrid("setGridParam", {search: true})
.trigger('reloadGrid', [{current: true, page: 1}]);

Categories