dynamic data is fetched through Js-grid, but filtering is not working? - filtering

Here is my JS code for JS Grid
$(function() {
$.ajax({
type : "GET",
url : "/Final/Reports?value=2016-03-03&value2=2017-03-03"
}).done(function() {
$("#jsGrid").jsGrid({
height : "auto",
width : "100%",
filtering: true,
sorting : true,
paging : true,
autoload : true,
pageSize : 3,
controller : {
loadData : function(filter) {
return $.ajax({
type : "GET",
url : "/Final/Reports?value=2016-03-03&value2=2017-03-03",
data : filter
});
},
},
fields : [ {
name : "patientId",
type : "text",
width : 150
}, {
name : "patientName",
type : "text",
width : 150
}, {
name : "genderId",
type : "number",
width : 150
}, {
name : "mobile",
type : "number",
width : 150
}, {
type : "control"
} ]
});
});
});
I am new to JS grid and I fetched the data using servlet and it is shown in the grid. But I don't know how to filter the data.
Any ideas?

Client-side filtering and server-side filtering are completely on
shoulders of developer. Client-side filtering implemented in loadData
method of controller. Server-side apparently implemented with server
script that receives filtering parameters, and uses them to fetch
data, and pass to client.
That's why you can use client-side and
server-side filtering at the same time. Here is how your
controller.loadData method could look like in this case:
loadData: function(filter) {
var d = $.Deferred();
// server-side filtering
$.ajax({
type: "GET",
url: "/items",
data: filter,
dataType: "json"
}).done(function(result) {
// client-side filtering
result = $.grep(result, function(item) {
return item.SomeField === filter.SomeField;
});
d.resolve(result);
})
return d.promise();
}
The source issue: https://github.com/tabalinas/jsgrid/issues/32

Related

Xpages : cannot get parm when consuming a delete call on a rest service

My Xpage application has a Kendo UI grid. The grid is populated by a call to a custom rest service backed my a managed bean hooked to a java class.
The read works great, but I am having trouble with getting a delete to work. It was working and then something changed (cannot figure out what) and now it simply does not. I am not sure if the error is in the Kendo UI part or the Rest service part, so I will post both here.
I am able to debug the Java and can see that I am getting to the doDelete method, but I just cannot get the parm (UNID) necessary to grab the document and delete it.
The java part is as follows:
package com.scoular.rest;
import java.io.IOException;
import java.io.Writer;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openntf.domino.Database;
import org.openntf.domino.Document;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewNavigator;
import org.openntf.domino.utils.Factory;
import com.ibm.commons.util.io.json.JsonException;
import com.ibm.commons.util.io.json.util.JsonWriter;
import com.ibm.domino.services.ServiceException;
import com.ibm.domino.services.rest.RestServiceEngine;
import com.ibm.xsp.extlib.component.rest.CustomService;
import com.ibm.xsp.extlib.component.rest.CustomServiceBean;
import com.scoular.cache.CacheBean;
public class restPC extends CustomServiceBean {
#SuppressWarnings("unused")
private Database appData;
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
try {
HttpServletRequest request = engine.getHttpRequest();
HttpServletResponse response = engine.getHttpResponse();
response.setHeader("Content-Type", "application/json; charset=UTF-8");
String method = request.getMethod();
if (method.equals("GET")) {
this.doGet(request, response);
} else if (method.equals("DELETE")) {
this.doDelete(request, response);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Map prmMap = request.getParameterMap();
// String id = prmMap.get("id").toString();
String prmUNID = request.getParameter("id");
Database DB = this.getAppData();
// String t = request.getParameter("unid");
Document tmpDoc = DB.getDocumentByUNID(prmUNID);
if (tmpDoc != null) {
tmpDoc.remove(true);
} else {
}
}
I only posted the relevant parts of the java code.
Here is the script part (Kendo Grid) of the Xpage where the delta is called.
<!--The Grid-->
<div class="row" id="grid" style="margin-top:15px"></div>
<!--The Grid-->
</div>
<!--The Container-->
<xp:scriptBlock id="scriptBlock1">
<xp:this.value><![CDATA[ $( document ).ready( function () {
// Setup Rest Service
var loc = ( location.href );
var url = loc.substring( 0, loc.lastIndexOf( "/" ) ) + "/xpRest.xsp/custom/";
var searchInput = XSP.getElementById("#searchInput");
var crudServiceBaseUrl = "xpRest1.xsp",
dataSource = new kendo.data.DataSource({
autoSync : true,
transport : {
read : {
url : url + "get?status=All",
dataType : "json",
type : "GET"
},
destroy : {
url: function (e) {
return "delete?" + e.id;
},
//url : url + "delete?id=", I HAVE ALSO TRIED THIS
dataType : "json",
type :"DELETE"
}
},
batch: true,
pageSize : 15,
scrollable : false,
height : 600,
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models[0].id)};
}},
schema : {
model : {
id : "unid",
fields : {
serialNumber : {
type : "string",
editable : false
},
statusDescription : {
type : "string",
editable : false
},
lastActionDate : {
type : "date",
editable : false
},
lastActionUser : {
type : "string",
editable : false
},
lastActionLocation : {
type : "string",
editable : false
},
assetTag : {
type : "string",
editable : false
},
model : {
type : "string",
editable : false
},
unid : {
type : "string",
nullable : false
}
}
}
}
});
// Grid
grid = $("#grid").kendoGrid( {
excel:{
fileName: "PC Inventory All.xlsx",
filterable:true,
allPages:false
},
dataSource : dataSource,
dataBound: onDataBound,
columns : [
//define template column with checkbox and attach click event handler
{width: "30px",
template: "<input type='checkbox' class='checkbox' />" },
{
width : "150px",
field : "serialNumber",
title : "Serial Number",
template : "<a href=xpFormPC.xsp?action=openDocument?&key=#=unid#><h5><b>#=serialNumber#</b></h5></a>"
}, {
width : "150px",
field : "statusDescription",
title : "Status",
template :"#=status#&nbsp#=statusDescription#"
}, {
width : "150px",
field : "lastActionDate",
title : "Last Action Date",
template: "#= (lastActionDate == null) ? ' ' : kendo.toString(kendo.parseDate(lastActionDate, 'yyyy-mm-dd'), 'MM/dd/yyyy') #"
}, {
width : "150px",
field : "lastActionUser",
title : "Last Action User"
}, {
width : "200px",
field : "lastActionLocation",
title : "Last Action Location"
}, {
width : "150px",
field : "assetTag",
title : "Asset Tag"
}, {
//width : "150px",
field : "model",
title : "Model"
}, {
hidden: false,
width : "50px",
template : "<button type='button' class='btn btn-danger k-grid-delete'>X</button>"
}
],
editable : {mode:"inline"},
pageable : {
refresh : true,
pageSizes : true,
buttonCount : 5
},
groupable : true,
reorderable : true,
filterable : true,
selectable : true,
sortable : true,
resizable : true,
columnMenu : true
});
]]></xp:this.value>
</xp:scriptBlock>
Solution from OP.
I figured out what I was doing wrong. I was sending a Parameter map and I needed to get a Parameter Map.
So my code in the Java agent changed to this:
private void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException, NotesException {
Map<String, String[]> prmMap = request.getParameterMap();
String[] prmID = prmMap.get("unid");
Database DB = this.getAppData();
Document tmpDoc = DB.getDocumentByUNID(prmID[0]);
if (tmpDoc != null) {
tmpDoc.remove(true);
}
}

Setting params in Kendo UI Grid when calling a rest service [Workaround]

I have a Kendo UI Grid that is calling a rest service. It works fine, as long as I do not try to use any params.
I know the the rest service is correct, as I can call it from a browser, and get correct results [depending on the param I send]. Also, when I look the server log I see that it is calling the rest service with no params.
My code is below:
document).ready( function() {
var crudServiceBaseUrl = "rsPC.xsp",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/PCByStatus",
filter: {field: "status", value: "2" }
dataType: "json",
update: {
url: crudServiceBaseUrl + "/PC/Update",
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl + "/PC/Destroy",
dataType: "json"
},
create: {
url: crudServiceBaseUrl + "/PC/Create",
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
scrollable: {
virtual: true
},
height: 543,
schema: {
model: {
id: "PCId",
fields: {
PCId: {type:"string"},
serialNumber: {type: "string"},
officeLoc: {type: "string"},
unid: {type:"string"},
model: {type:"string"},
checkInDate: {type: "string"}
}
}
}
});
// Grid
grid = $("#grid").kendoGrid( {
dataSource: dataSource,
columns : [ {
field : "serialNumber",
title : "Serial Number"
}, {
field : "model",
title : "Model"
}, {
field : "officeLoc",
title : "Office Location"
}, {
field : "checkInDate",
title : "Check In Date",
template: "#= kendo.toString(kendo.parseDate(checkInDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
} ],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataBound : addExtraStylingToGrid,
reorderable : true,
filterable : true,
scrollable : true,
selectable : true,
sortable : true,
});
I still cannot get this to work and am a bit stumped.
I have two rest services, one returns all data, one takes "status" as a part and return a subset of the data that equals the parm.
The URL is:
http://localhost/scoApps/PC/PCApp.nsf/rsPC.xsp/PCByStatus?status=2
When entered into browser I get the correct number of records.
So I changed the code (see below). I have included all of the code for the CSJS:
$(document).ready( function() {
// Double Click On row
$("#grid").on(
"dblclick",
" tbody > tr",
function() {
var grid = $("#grid").data("kendoGrid");
var row = grid.dataItem($(this));
window.location.replace("xpFormPC.xsp" + "?key=" + row.unid + "target=_self");
});
// Add hover effect
addExtraStylingToGrid = function() {
$("table.k-focusable tbody tr ").hover( function() {
$(this).toggleClass("k-state-hover");
});
};
// Search
$("#search").keyup( function() {
var val = $('#search').val();
$("#grid").data("kendoGrid").dataSource.filter( {
logic : "or",
filters : [ {
field : "serialNumber",
operator : "contains",
value : val
}, {
field : "officeLoc",
operator : "contains",
value : val
}, {
field : "model",
operator : "contains",
value : val
} ]
});
});
var crudServiceBaseUrl = "rsPC.xsp",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/PCByStatus",
dataType: "json"
},
update: {
url: crudServiceBaseUrl + "/PC/Update",
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl + "/PC/Destroy",
dataType: "json"
},
create: {
url: crudServiceBaseUrl + "/PC/Create",
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation == "read"){
options.field = "status"
options.value = "2"
return options;
}
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
scrollable: {
virtual: true
},
height: 543,
schema: {
model: {
id: "PCId",
fields: {
PCId: {type:"string"},
serialNumber: {type: "string"},
officeLoc: {type: "string"},
unid: {type:"string"},
model: {type:"string"},
checkInDate: {type: "string"}
}
}
}
});
// Grid
grid = $("#grid").kendoGrid( {
dataSource: dataSource,
columns : [ {
field : "serialNumber",
title : "Serial Number"
}, {
field : "model",
title : "Model"
}, {
field : "officeLoc",
title : "Office Location"
}, {
field : "checkInDate",
title : "Check In Date",
template: "#= kendo.toString(kendo.parseDate(checkInDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
} ],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataBound : addExtraStylingToGrid,
reorderable : true,
filterable : true,
scrollable : true,
selectable : true,
sortable : true
});
// Edit
function onEdit(e) {
}
// Change
function onChange(args) {
var model = this.dataItem(this.select());
ID = model.ID;
}
;
});
What am I doing wrong?
=========================================
I have a workaround. Or possibly this is the way it is supposed to be done.
var crudServiceBaseUrl = "rsPC.xsp", dataSource = new kendo.data.DataSource(
{
transport : {
read : {
url : crudServiceBaseUrl
+ "/PCByStatus?status=2",
dataType : "json"
},
Now I just construct the URL I want. Not so elegant I suppose, but it works.
I have a workaround. Or possibly this is the way it is supposed to be done.
var crudServiceBaseUrl = "rsPC.xsp", dataSource = new kendo.data.DataSource(
{
transport : {
read : {
url : crudServiceBaseUrl
+ "/PCByStatus?status=2",
dataType : "json"
},
Filter is used for client side data unless you set serverFiltering to true.
Here is the filter kendo documentation and the serverFiltering documentation.
I use parameterMap when I need to send parameters that are not created by filtering the control that I'm using. The kendo documentation provides an example using parameterMap.
Here is an example of how I've used it in the past:
var appsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "App"
},
parameterMap: function (data, action) {
if (action === "read") {
data.lobid = lobId;
data.parent = isParent;
return data;
} else {
return data;
}
}
}
});
Try changing the parameterMap:
parameterMap: function(options, operation) {
if (operation == "read"){
options.field = "status";
options.value = "2";
return options;
}
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
and update the read definition to remove filter. One thing to consider is that you are not returning anything from the read method if it doesn't meet the criteria of not being a read and options is not null. That leaves out any other combination that isn't obviously handled in your existing code.

Custom control Openui5

sap.ui.core.Element.extend("custom.barNlineChartControl", { metadata : {
properties : {
"Job" : {type : "string", group : "Misc", defaultValue : null},
"Threshold" : {type : "int", group : "Misc", defaultValue : null},
}
}});
sap.ui.core.Control.extend("control.barNlinechart", {
/* the control API */
metadata : {
aggregations : {
"items" : { type: "custom.barNlineChartControl", multiple : true, singularName : "item"}
},
events: {
"select" : {},
"selectEnd": {}
}
},
//D3 Code below:
onAfterRendering: function() {
var that = this;
/* get the Items aggregation of the control and put the data into an array */
var aItems = this.getItems();
var data = [];
for (var i=0;i<aItems.length;i++){
var oEntry = {};
for (var j in aItems[i].mProperties) {
oEntry[j]=aItems[i].mProperties[j];
}
data.push(oEntry);
}
alert(JSON.stringify(data));
Code of view & control
multiBarLineGraph = new control.barNlinechart({
layoutData: new sap.ui.layout.GridData({span: "L12 M12 S12"}),
items: {
path : "/genericData",
template : new custom.barNlineChartControl({Job:"{Job}",Threshold:"{Threshold}"}),
}
}),
var multiBarData = {
"genericData":[
{
"Job": "Doctor",
"Threshold": 45,
"Hospital1": 30,
"Hospital2": 100,
"Hospital3": 90,
},
{
"Job": "Teacher",
"Threshold": 65,
"School1": 60,
"School2": 75,
},
]};
When the alert in d3 code executes I get Job & Threshold but other data from JSON array are missing which is obvious as the properties set here only accept job and threshold. As the JSON is dynamic how to write custom control so that I can pass the complete data to control everytime no matter how dynamic the data be.
You could use type: "any" for your items and dont use the element custom.barNlineChartControl at all:
Edit: as an aggregation controls the lifetime of the aggregated objects you have to use a property in this case.
sap.ui.core.Control.extend("control.barNlinechart", {
/* the control API */
metadata : {
properties : {
"items" : { type: "any" }
},
events: {
"select" : {},
"selectEnd": {}
}
},
and then in your view:
multiBarLineGraph = new control.barNlinechart({
layoutData: new sap.ui.layout.GridData({span: "L12 M12 S12"}),
items: { path : "/genericData" }
}),
this.getItems() would return an array of whatever has been been set / bound.

Correct way to return from mongo to datatable

I'm using mongoose and returning documents from a collection to be displayed using datatables. I'm having some issues though. The client-side code is
var table = $('#dataTables-example').DataTable( {
"bProcessing" : true,
"bServerSide" : true,
"ajax" : {
"url" : "/mongo/get/datatable",
"dataSrc": ""
},
"columnDefs": [
{
"data": null,
"defaultContent": "<button id='removeProduct'>Remove</button>",
"targets": -1
}
],
"aoColumns" : [
{ "mData" : "name" },
{ "mData" : "price" },
{ "mData" : "category" },
{ "mData" : "description" },
{ "mData" : "image" },
{ "mData" : "promoted" },
{ "mData" : null}
]
});
Then this handled on the server-side using the following
db.once('open', function callback ()
{
debug('Connection has successfully opened');
productSchema = mongoose.Schema({
name: String,
price: String,
category: String,
description: String,
image: String,
promoted: Boolean
});
Product = mongoose.model('Product', productSchema, 'products');
});
exports.getDataForDataTable = function (request, response) {
Product.dataTable(request.query, function (err, data) {
debug(data);
response.send(data);
});
};
If I use the above code the datatable fails to display the documents, claiming no matching records found BUT it does correctly display the number of docs Showing 1 to 2 of 2 entries. If I change the server side code to response with data.data instead of data, the documents are correctly populated in the table BUT the number of records is no longer found, instead saying Showing 0 to 0 of 0 entries (filtered from NaN total entries)
exports.getDataForDataTable = function (request, response) {
Product.dataTable(request.query, function (err, data) {
debug(data);
response.send(data.data);
});
The actual data being returned when querying mongo is
{ draw: '1', recordsTotal: 2, recordsFiltered: 2, data: [ { _id: 5515274643e0bf403be58fd1, name: 'camera', price: '2500', category: 'electronics', description: 'lovely', image: 'some image', promoted: true }, { _id: 551541c2e710d65547c6db15, name: 'computer', price: '10000', category: 'electronics', description: 'nice', image: 'iamge', promoted: true } ] }
The third parameter in mongoose.model sets the collection name which is pluralized and lowercased automatically so it has no effect in this case.
Assuming your Product variable has been declared early on and global, try this:
products = mongoose.model('products', productSchema);
Product = require('mongoose').model('products');
Did you try to remove the dataSrc field in the DataTable configuration:
"ajax" : {
"url" : "/mongo/get/datatable",
},

enhanced grid defaultly displaying only 10 rows? in dojo

i have 100000 data in my grid at first request it showing only 10 after clicking on the page selecter it showing next data............plz answer why enhanced grid displaying only 10 rows at first time
require([ "dojo/_base/lang","dojox/grid/EnhancedGrid",
"dojox/grid/enhanced/plugins/Pagination","dojo/data/ItemFileReadStore",
"dijit/form/Button","dojo/request/xhr", "dojo/dom",
"dojo/dom-construct", "dojo/json", "dojo/on", "dojox/grid/cells/dijit",
"dojo/domReady!" ],
function(lang,EnhancedGrid,Pagination,ItemFileReadStore,Button,xhr, dom, domConst, JSON, on) {
xhr("myservernameaddress/GridExample/string", {
handleAs : "json"
}).then(
function(dataa) {
/* domConst.place("<p>response: <code>"
+ JSON.stringify(dataa) + "</code></p>",
"output"); */
/* domConst.place("<p>response: <code>"
+ JSON.stringify(dataa) + "</code></p>",
"output"); */
var mydata=dataa;
var yourStore = new dojo.data.ItemFileReadStore({
data: {
identifier: "sno",
/* items: mydata.aa */
items:mydata
}
});
grid = new EnhancedGrid({
store : yourStore,
selectable:true,
query : {
sno : "*"
},
structure : [ {
name : "SNO",
field : "sno",
width : "100px"
},{
name : "SNAME",
field : "sname",
width : "100px",
editable:true
},{
name : "SALARY",
field : "salary",
width : "200px",
editable:true
} ],
rowSelector: '20px',
plugins: {
pagination: {
pageSizes: ["25","50","100"],
description: true,
sizeSwitch: true,
pageStepper: true,
gotoButton: true,
maxPageStep: 2,
position: "bottom",
search:true
}
}
});
grid.placeAt("myGrid");
grid.startup();
}, function(err) {
alert("error");
}, function(evt) {
});
});
can avoid enhanced grid default 10 rows size by this please check it
defaultPageSize: 50,.
use this in pagination plugin...
I think this might help you out:
When you define your grid you can set autoHeight
I've copied this from dojo:
autoHeight
If true, automatically expand grid’s height to fit data. If numeric,
defines the maximum rows of data displayed (if the grid contains
less than autoHeight rows, it will be shrunk).
For more informations have a look : http://dojotoolkit.org/reference-guide/1.7/dojox/grid/DataGrid.html#datagrid-options
Update1
Maybe this former Post makes it clearer: DataGrid's rowsPerPage attribute not working
Regards, Miriam