Set default value in jqgrid - jqgrid

I need to display 0 for some columns if there is no data coming from DB. So is it possible to define a default value for a column in the colModel so that I don't need to check for empty values and making them zeros in the array.

There is no any direct way to define default value for any column but you can do this by some way.like
using Custom Formatter
You can define your own formatter for a particular column. Usually this is a function.In that function you can check for column value if it is null or empty and return some default value.
For Example :
<script>
jQuery("#grid_id").jqGrid({
...
colModel: [
...
{name:'price', index:'price', width:60, align:"center", editable: true,
formatter:currencyFmatter},
...
]
...
});
function currencyFmatter (cellvalue, options, rowObject)
{
// do something here to check value and return default value
if(cellvalue == "" || cellvalue == "null")
return new_format_value
}
</script>

Related

saving select 'text' not 'value' when saveRow is executed in jqgrid

editable:true,edittype: "select",
editoptions: {
dataUrl : '/test.do?cd=abc',
cacheUrlData: true,
buildSelect : function(data) {
var data = ($.parseJSON(data)).list;
var s='<select>';
for(d of data){
s += '<option value=' + d.comCd + '>' + d.comNm + '</option>';
}
s += '</select>';
return s;
},
},
When I checked the data after saving,
it contained d.comNm, which is text, not d.comCd, which is the value of the option.
var gridData = grid.jqGrid('getRowData');
console.log(gridData);
It is jqgrid 5.2.1 version, and it is an old project using java 1.7.
Can someone please help me?
Expected this
Result
I have no problem with it appearing on the grid.
The biggest problem is that the value is not stored in the data (getRowData).
As far as understand you want to display in grid the value, but when inline edit if on, you display select with value=> text on it, but when saved to save and display the value.
To do this the trick is to define custom formatter only, which return the cellvalue. For that field in colModel do
colModel : [
....
{
name: 'name1',
editable:true,
edittype: "select",
editoptions : {...},
formatter : function(cellval) {
return cellval;
}
}
...
]

jqgrid colmodel editoptions to load json result

I want to load my server data in the DropDown of my jqgrid. My code,
UPDATED CODE:
public ActionResult GetUnit()
{
List<UnitModel> getUnitValues = new List<UnitModel>();
//ToDo db code
Dictionary<int, string> unitValues = new Dictionary<int, string>();
unitValues = getUnitValues.ToDictionary(x => x.UnitID, x => x.UnitDesc);
unitValues.Add(4, "Unit2/3");
unitValues.Add(1, "Unit1");
unitValues.Add(2, "Unit2");
unitValues.Add(3, "Unit3");
return Json(unitValues, JsonRequestBehavior.AllowGet);
}
My jqgrid:
colModel: [...
{
name: 'UnitID', index: 'UnitID', editable: true, edittype: 'select', width: "200",
formatter: 'select', editoptions: { value: unitslist},
editrules: { custom: true, custom_func: dupicateRecordValidation
}
},
...],
beforeProcessing: function () {
$.ajax({
url: '/Home/GetUnit/',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$.map(data, function (value, key) {
unitsList += '"' + value + '"' + ':' + '"' + key + '"' + ',';
});
unitsList += '}';
alert(unitsList);
}
});
},
But, this isn't working. The jqgrid DropDown column loaded with empty cell. Am I missing something? Is this the correct way to do? Please suggest if any alternate way to load the dropdown of jqgrid with server data with default value of that row being selected. Thanks.
Note:I'm using Jquery jqgrid v4.4.4 Visual Studio
First of all, it's important to understand when you should use formatter: 'select', which you currently use. It's required if you want to fill the grid with id information in UnitID, but you need to display the text, which correspond the ids. For example, the JSON data, which you get from the server could contain the property language, with the content "de", "en", "fr" and so on, but you want to display in the column "German" instead of "de", "English" instead of "en" and "French" instead of "fr". In the case you should define
formatter: 'select', editoptions: { value: 'de:German;en:English;fr:French' },
editable: true, edittype: 'select'
If you really need to use formatter: 'select', and you need to load the editoptions.value via Ajax from the server, then the editoptions.value have to be set before the main data of the grid returned from url will be processed. In the case, I would recommend you to extend the standard data returned from url with the data required for the editoptions.value. One can use beforeProcessing callback (which is supported even in the retro version 4.4.4, which you use) and to set editoptions.value dynamically with respect of setColProp method. See the answer for more details and the code example.
If you don't need to use formatter: 'select' (if ids and the values, used in select, are the same), then you can change the format of data returned from GetUnit action to the serialized array:
["Unit1", "Unit2", "Unit2/3"]
and to use dataUrl with buildSelect properties of editoptions instead of value. The value of dataUrl should be URL of GetUnit action, which return array of strings with all utits. The callback buildSelect should convert the JSON array to HTML fragment, which represent <select> with all the options. See the old answer, for more implementation details and code examples.
Finally, you should fix width: "200px" to width: 200. The value of width property should be the number or the string which could be converted to the number. The usage of px or and other suffix is wrong. The next recommend fix would be removing index: 'UnitID' and all other index properties from colModel, if the value of index property is the same as the value of name property.

Apply Custom Formatter after Sort Function with jqGrid

I am using a custom control on an Xpage to build a table with jqGrid. The jqGrid receives the data via JSON and fills the table correctly.
My question is with the sort function of jqGrid. I apply a custom formatter to the cell value of my "docname" column when the table first builds. The issue that I am having is after sorting any of the columns this formatter becomes unusable. The format is still applied but this particular formatter builds a url that launches another Xpage and relies on the parameter "docid".
Here is my custom formatter:
function openDocument(cellvalue, options, rowObject) {
return "<a target='#{javascript:compositeData.target}' title='Open Document'
href='https://test.url.com?DocID=" +rowObject["docid"]+
"&action=#{javascript:compositeData.action}' class='doclink'>"
+ cellvalue + "</a>"; }
Is there any way to get the rowObject "docid" back into the openDocument formatter after sorting the grid?
I researched some and found the onSortCol event and have it initialized like this:
onSortCol: function(index,iCol,sortorder) {alert("Test")}
My alert that I have in the onSortCol initilization is working, I just need to find out how to set my "docid" parameter after the sort is run since it is currently set to undefined after the sort.
I have tried putting in:
{rowObject["docid"]}
But this just breaks the sorting all together.
I have also read these posts:
onSortCol Event
JQGrid Sorting - how to trigger onSortCol event
jqGrid - Is it possible to set onSortCol after init?
Thanks for your help.
Edit:
jqGrid Definition:
$().ready(function(){
jQuery("#listxGrid").jqGrid({
url:'#{javascript:compositeData.url}',
datatype: "json",
colNames:#{javascript:compositeData.colNames},
colModel:#{javascript:compositeData.colModel},
shrinkToFit: false,
jsonReader: {
repeatitems: false,
id: '#{javascript:compositeData.colID}',
root: function (obj) {
if ($.isArray(obj)) return obj;
if ($.isArray(obj.items)) return obj.items;
return [];
},
page: function () { return 1; },
total: function () { return 1; },
records: function (obj) {
if ($.isArray(obj)) return obj.length;
if ($.isArray(obj.items)) return obj.items.length;
return 0;
}
},
gridview: true,
loadonce: true,
ignoreCase: #{javascript:compositeData.ignoreCase},
rowNum: #{javascript:compositeData.rowNum},
rowList: #{javascript:compositeData.rowList},
rownumbers: #{javascript:compositeData.showRowNumbers},
height: #{javascript:compositeData.height},
caption: '#{javascript:compositeData.caption}',
pager: '#pagerxGrid',
viewrecords: true,
emptyrecords: '#{javascript:compositeData.emptyRecords}',
sortable: true,
onSortCol: function(index,iCol,sortorder) {alert(index)},
grouping: #{javascript:compositeData.grouping},
groupingView : {
groupField : #{javascript:compositeData.groupField},
groupDataSorted : true,
groupColumnShow : #{javascript:compositeData.showGroupCol}
}
});
Have a look at this answer which suggests the use of isArray to determine whether to use rowObject["docid"] or rowObject[integer]:
jqGrid - rowObject inconsistencies?
I ended up solving the problem this way. On the jqGrid it was receiving the "docid" param from the remote data on the first load just fine but as soon as the sort function called it would be set to "undefined."
As #PerHenrikLausten pointed out with his link, after the onload function completes this remote data type is then switched to local data. By loading in the docid into a hidden column, this is then available as a parameter for my formatter after the data type is switched.
By adding:
'Docid' as a colName & {name:'docid', index:'docid', hidden: true} to the colModel
It allows me to sort the jqGrid from any of my columns that I have sortable set to true with the docid parameter as what it should be not "undefined."
Thanks everyone for your input.

How to display multiple values in same column in jqgrid

I would like to know how to display multiple values in a single column in jqGrid
Here is a sample of my current grid definition.
$("#grid1").jqGrid({
url: 'Default.aspx/getGridData',
datatype: 'json',
...
colModel: [
...
//contains the input type ('select', etc.)
{ name: 'InputType', hidden:true },
...
//may contain a string of select options ('<option>Option1</option>'...)
{
name: 'Input',
editable:true,
edittype:'custom',
editoptions:{
custom_element: /* want cell value from InputType column here */ ,
custom_value: /* want cell value from Input column here */
}
},
...
]
});
You can do this easily by using a Custom Formatter on your column model.
A custom Formatter is a javascript function with the following parameters:
cellvalue - The value to be formatted
options - { rowId: rid, colModel: cm} where rowId - is the id of the
row colModel is the object of the properties for this column getted
from colModel array of jqGrid
rowObject - is a row data represented in the format determined from
datatype option
So a function can be declared like so:
function myformatter ( cellvalue, options, rowObject )
{
// format the cellvalue to new format
return new_formated_cellvalue;
}
And is defined on your column like this:
{name:'price', index:'price', width:60, align:"center", editable: true,
formatter:myformatter },
So in your case you can use the rowObject parameter in the custom formatter to populate your additional values.
For Example.
Column Model
{name:'employee_id', index:'employee_id', width:60, align:"center", editable: true,
formatter:myformatter, label:'Employee' }
Formatter
function myformatter ( cellvalue, options, rowObject )
{
return cellvalue + ' ' + rowObject.email + ' ' + rowObject.user_name;
}
And if this is defined on your employee_id column it would display in the cell:
employee_id email username
Here is a jsFiddle example showing it working.

Get Images in a column of Jqgrid based on id value in another column of the grid

I have a JQGrid with 4 columns as below
<script type="text/javascript">
$(function(){
jQuery("#toolbar").jqGrid({
url:'<%=request.getContextPath()%>/TestServlet?q=1&action=fetchData',
datatype: "xml",
mtype: 'POST',
height: '100%',
width: '100%',
colNames:['LocationImage','City','State','LocationID'],
colModel:[
{name:'LocationImage',index:'LocationImage',align: 'center', formatter: imageFormatter},
{name:'City',index:'City', width:200,fixed:true,sortable:true,align:'center',editable:true, editoptions:{readonly:false,size:500}},
{name:'State',index:'State', width:200,fixed:true,sortable:true,align:'center',editable:true, editoptions:{readonly:false,size:50}},
{name:'LocationID',index:'LocationID',width:60,align:'center',hidden:true,editable:false, editoptions:{readonly:true,size:30}
],
paging: true,
rowNum:16,
rowTotal:2000,
rownumbers: true,
rownumWidth: 25,
rowList:[16,32,48],
viewrecords: true,
loadonce: true,
gridview: true,
pager: $("#ptoolbar"),
sortname: 'Name',
sortorder: "asc",
caption: "Test Grid"
})
jQuery("#toolbar").jqGrid('navGrid','#ptoolbar',{del:false,add:false,edit:false});
jQuery("#toolbar").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});
});
function imageFormatter(el, cval, opts) {
var num = '2';
return ("<center><img src='../gd/images/" + num+".png' height='180px' width='180px' /></center>")
}
Here I have hardcoded num as '2' and so displaying 2.png in the first column i.e. LocationImage, what i need is that the value for num should be from the 4th column i.e. LocationID (note its a hidden column).
Please let me know how to do this.
Thanks,
Deepna
You should change your imageFormatter function to be like this:
function imageFormatter(cellvalue, options, rowObject){
var num = $("#" + options.rowId).find("td[aria-describedby='toolbar_LocationID']").text();
return "<center><img src='../gd/images/" + num + ".png' height='180px' width='180px' /></center>";
}
okay, I'm not rally sure about it, I can't test now. but here's what you can do
From the options parameter you can get the row id, check here and then you can get Location Id with that row Id using getCell or getGridParam. and you can use this value for setting the image.
If this doesn't work for custom formatter, you can use setCol method in gridComplete property of JqGrid.
Now this is going to work for only one id. If you want to set image for all rows, get row ids using getDataIDs method in a variable and t hen go with for loop and use setCol.
I Hope this helps
I was able to fix the issue in the below way
Changed the first column in the Grid to Location ID
Now in the formatter - when I say "cellvalue", it actually
returns the location id
This location id is then set into the variable num (i.e. num =
cellvalue)
Now the formatter code replaces the id value with an image based
on id.png
Thanks,
Deepna

Resources