free jqgrid 4.8.0 colModel editoptions - dynamic values from query - jqgrid

I am working with Coldfusion and jqgrid.
Is there a way to populate the colModel editoptions dynamically from query results?

If you need to set dynamically the options like 1:female;2:male, then I suppose that you fill grid with data which contains 1 or 2 in the specified column. So you have to use formatter: "select" (see the documentation). Thus you should be able to set the properties like below
{name: "sex", formatter: "select", editoptions: { value: "1:female;2:male" }}
If you need to set such options dynamically, that you want to load the information about editoptions.value from the server.
The most native callback which you can use for it is beforeProcessing. The callback will be processed before the data returned from the server will be displayed using the formatter. So one can make any changes of formatoptions or editoptions.
If the server response looks now like
{
"rows": [
{"id": 123, "name": "John", "sex": "2"},
{"id": 456, "name": "Mary", "sex": "1"}
]
}
then you can extend the data of the server response to the following
{
"rows": [
{"id": 123, "name": "John", "sex": "2"},
{"id": 456, "name": "Mary", "sex": "1"}
],
"colModelExtentions": {
"sex": {"formatter": "select", "editoptions": {"value": "1:female;2:male"}}
}
}
In the way you specify some changes of specific items of the colModel directly inside of the server response. The implementation of the beforeProcessing callback which process such data can looks like
beforeProcessing: function (data) {
var cmName, cmExt = data.colModelExtentions, $self = $(this),
p = $self.jqGrid("getGridParam");
for (cmName in cmExt) {
// enumerate properties of colModelExtentions like sex
if (cmExt.hasOwnProperties(cmName)) {
$self.jqGrid("setColProp", cmName, cmExt[cmName]);
}
}
}
and to define the "sex" columns in colModel like
{name: "sex", width: 50}
You will find more details about the scenario in the answer and this one. You can extend the information which return the server. In the case you can need to call setColWidth or setLabel additionally to apply dynamically the column width and the text of the column header.

Related

How to Generate DataTable with Json Data

I have API Call abd which will be returning Json like below
{
"status": true,
"message": "Data Sent",
"data": [
{
"id": 9,
"name": "North",
"colType": 7,
"userID": 0,
"isVisible": false
}
]
}
And below i have JavaScript Ajax Call but it is returning Empty datatable please do help
$('#myTable').DataTable({
destroy: true,
responsive: true,
"ajax": {
"url": url+'/api/CommonMasters/7/GetByUserID/'+#ViewBag.UID,
"type": "GET",
"datatype": "json",
},
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"columns": [
{ "data": "name", "autoWidth": true },
{
"render": function (data, type, full, meta) { return "<a id='Edit' class='btn btn-info' onclick='editRefUser(" + full.id + ")' ;>Edit</a>"; }
},
]
});
In the ajax section, you need to define your data source: "dataSrc": "data".
"ajax": {
"url": url+'/api/CommonMasters/7/GetByUserID/'+#ViewBag.UID,
"type": "GET",
"datatype": "json",
"dataSrc": "data"
},
Why is this needed? Your JSON data structure does not have a "name" item at the top level. Names are nested inside the top-level "data" object. This extra directive tells DataTables to look only at the JSON's "data" object as its starting point.
See here for the related documentation:
The ajax option basically inherits all of the options made available by jQuery.ajax, but we provide the extra option of dataSrc to provide the ability to alter what data DataTables will read from the JSON returned from the server...
Also, on an unrelated note, I don't think you need this: destroy: true - try removing it. It probably does not make sense to try to destroy the table object while you are initializing it.

Dojox/app keeping models synchronized with store

I am currently using dojox/app to create a SPA, and I am starting now to add stores and models. I have been able to create a store from a json object, to create a model from the store, and to bind fields to the model using dojox mvc. However, I have something that I have not yet been able to do: update a 2nd model that is binded to the same store as the 1st one.
I will give an example. I have this store:
win.global.modelApp = {};
modelApp.names = {
identifier: "id",
items: [{
"id": 1,
"First": "John",
"Last": "Doe",
},{
"id": 2,
"First": "John2",
"Last": "Doe",
}]
}
and then I create two models using this store in the config.json file:
"stores": {
"namesStore":{
"type": "dojo/store/Memory",
"params": {
"data": "modelApp.names"
}
}
},
"models": {
"namesXUnused": {
"modelLoader": "dojox/app/utils/mvcModel",
"type": "dojox/mvc/EditStoreRefListController",
"params":{
"store": {"$ref":"#stores.namesStore"}
}
},
"namesXUnused2": {
"modelLoader": "dojox/app/utils/mvcModel",
"type": "dojox/mvc/EditStoreRefListController",
"params":{
"store": {"$ref":"#stores.namesStore"}
}
}
}
Then, in my HTML file, I have a field binded to namesXUnused (property First), and another binded to namesXUnused2 (property First). When I edit the first field, I then have a button that commits these changes to the store. I can see via debugger that the store data has been correctly updated. However, I cannot get the second field to reflect the changes. Is there a way to refresh or recreate the model from the store?
Thank you,
I think you need to set "observable": true, on the store to use an Observable store since you want to have updates to the store be reflected back to the models. There are examples in the dojox/app/tests (and the dojox/mvc/tests) if you have problems, but just adding:
"observable": true, to your namesStore should do it.
"stores": {
"namesStore":{
"type": "dojo/store/Memory",
"observable": true,
"params": {
"data": "modelApp.names"
}
}
},
Regards,
Ed

Can't get Kendo UI TreeView to read children in JSON data correctly

http://jsfiddle.net/N8Svz/5/
I'm sure I must be doing something kind of dumb; this seems like a textbook usage of HeirarchicalDataSource as far as I can tell.
var domtree = [{
"id": "linear1",
"element-class": "LinearLayout",
"children": [{
"id": "static1",
"element-class": "Static"
}, {
"id": "static2",
"element-class": "Static",
"children": [{
"id": "static3",
"element-class": "Static"
}]
}, {
"id": "4",
"element-class": "Error"
}]
}];
var inline = new kendo.data.HierarchicalDataSource({
data: domtree,
schema: {
model: {
id: "id",
children: "children"
}
}
});
$("#navtree").kendoTreeView({
dataSource: inline,
dataTextField: "id"
});
A big thank you to anyone who can point out what I'm doing wrong!
I just change the field children to items.
here's a jsfiddle: http://jsfiddle.net/nn007/N8Svz/6/
If you add the schema property like this it may work. You are telling the hierarchical datasource what the key for children is. Something like this:
schema: { model: { children: "children" } }

Filter jqGrid programmatically on client?

Is there a way to filter the data currently displayed in a jqGrid programmatically (in Javascript, not server-side)? All the search examples seem to depend on using jqGrid's own search UI, which doesn't work for me. For example, I'd like to be able to filter based on user actions elsewhere on a page.
I'm imagining something like
jQuery("#grid_id").filter('CategoryID', selectedCategoryID);
where CategoryID is a column in the grid and selectedCategoryID contains, for example, a value chosen by the user in a select element.
If you want to pre-filter your data first:
$('#myGrid').setGridParam({ data: filtereddataarray }).trigger("reloadGrid");
where filtereddataarray contains only records you want to display for this view
If you want to construct your filter programmatically(I use this method, mostly):
var filters = { "groupOp": "AND", "rules": [{ "field": "id", "op": "eq", "data": "9" }, { "field": "amount", "op": "ge", "data": "10" }, { "field": "name", "op": "cn", "data": "do i"}] };
//To filter:
jqGridFilter(filters , $('#myGrid'));
//To reset:
jqGridFilter(null, $('#myGrid'));
function jqGridFilter(filtersparam, grid) {
grid.setGridParam({
postData: {
filters: filtersparam
},
search: true
});
grid.trigger("reloadGrid");
}
You could pass JSON as the data and use the setGridParam method to reload the data!
I have never tried this and not sure how you would get jqgrid to use your client data rather than hit a URL!
Have you had any luck?

Edit parsed JSON

I have a JSON file contact.txt that has been parsed into an object called JSONObj that is structured like this:
[
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
},
{
"firstName": "Mike",
"lastName": "Jackson",
"address": {
"streetAddress": "21 Barnes Street",
"city": "Abeokuta",
"state": "Ogun",
"postalCode": "10122"
},
"phoneNumbers": [
{ "type": "home", "number": "101 444-0123" },
{ "type": "fax", "number": "757 666-5678" }
]
}
]
I envision editing the file/object by taking in data from a form so as to add more contacts. How can I do this?
The following method for adding a new contact to the JSONObj's array doesn't seem to be working, what's the problem?:
var newContact = {
"firstName": "Jaseph",
"lastName": "Lamb",
"address": {
"streetAddress": "25 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "13021"
},
"phoneNumbers": [
{ "type": "home", "number": "312 545-1234" },
{ "type": "fax", "number": "626 554-4567" }
]
}
var z = contact.JSONObj.length;
contact.JSONObj.push(newContact);
It depends on what technology you're using. The basic process is to read the file in, convert it to whatever native datatypes (hash, dict, list, etc.) using a JSON parsing library, modify or add data to the native object, then convert it back to JSON and store it to the file.
In Python, using the simplejson library it would look like this:
import simplejson
jsonobj = simplejson.loads(open('contact.txt'))
#python's dict syntax looks almost like JSON
jsonobj.append({
'firstName': 'Steve',
'lastName': 'K.',
'address': {
'streetAddress': '123 Testing',
'city': 'Test',
'state': 'MI',
'postalCode': '12345'
},
'phoneNumbers': [
{ 'type': 'home', 'number': '248 555-1234' }
]
})
simplejson.dump(jsonobj, open('contact.txt', 'w'), indent=True)
The data in this example is hardcoded strings, but it could come from another file or a web application request / form data, etc. If you're doing this in a web app though I would advise against reading and writing to the same file (in case two requests come in at the same time).
Please provide more information if this doesn't answer your question.
In response to "isn't there way to do this using standard javascript?":
To parse a JSON string in Javascript you can either eval it (not safe) or use a JSON parser like this one's JSON.parse. Once you have the converted JSON object you can perform whatever modifications you want to it in standard JS. You can then use that same library to convert a JS object to a JSON string (JSON.stringify). Javascript does not allow file access (unless you're doing serverside JS), so that would prevent you from reading & writing to your contact.txt file directly. You'd have to use a serverside language (like Python, Java, etc.) to read and write the file.
Once you have read in the JSON, you just have an associative array - or rather you have a pseudo-associative array, since this is Javascript. Either way, you can treat the thing as one big list of dictionaries. You can access it by key and index.
So, to play with this object:
var firstPerson = JSONObj[0];
var secondPerson = JSONObj[1];
var name = firstPerson['firstName'] + ' ' + firstPerson['lastName'];
Since you will usually have more than two people, you probably just want to loop through each dictionary in your list and do something:
for(var person in jsonList) {
alert(person['address']);
}
If you want to edit the JSON and save it back to a file, then read it into memory, edit the list of dictionaries, and rewrite back to the file.
Your JSON library will have a function for turning JSON into a string, just as it turns a string into JSON.
p.s. I suggest you observe JavaScript conventions and use camelcase for your variable names, unless you have some other customs at your place of employment. http://javascript.crockford.com/code.html

Resources