How to display multiple values in same column in jqgrid - 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.

Related

How to get row ID by row Data in jqgrid (Not by selected row)

I want to get the row id by content of cell in jqGrid (Not by selected row).
By PRODUCTID, I can get the row id.
e.g. for PRODUCTID is ABCD, I can get 2.
The column PRODUCTID is unique.
Please give me some advices.
Thanks a lot.
My code sample:
$("#project_jqGrid").jqGrid({
url: 'project/projectQuery.php',
mtype: "POST",
datatype: "json",
page: 1,
colModel: [
{ label : "PRODUCTLINE",
//sorttype: 'integer',
name: 'PRODUCTLINE',
//key: true,
width: 100,
editable:true,
editoptions:{readonly:'readonly'}
},
{ label : "GPOWNER",
//sorttype: 'integer',
name: 'GPOWNER',
//key: true,
width: 150,
editable:true,
editoptions:{readonly:'readonly'}
},
{ label : "PRODUCTID",
//sorttype: 'integer',
name: 'PRODUCTID',
key: true,
width: 100,
editable:true,
editoptions:{readonly:'readonly'}
},
],
loadComplete: function() {
$.ajax({
dataType: 'json',
url : "project/projectDifferQuery.php", // your php file
type : "GET", // type of the HTTP request
success : function(data){
// I can get PRODUCTID from mysql database
// I want to get rowid to change cells color by PRODUCTID
// ........
// Change Cells Color(I need to get '5' by position of PRODUCTID)
//$('#project_jqGrid').jqGrid('setCell',5,"GPOWNER","",{'background-color':'#FF4545'});
}
});
},
loadonce: true,
viewrecords: true,
width: 'auto',
height: 'auto',
rowNum: 20,
pager: "#project_jqGridPager"//,
});
> Versions: - jqGrid 5.1.1
If the ProductID is unique and the grid contains ProductID as the column name in colModel, then it's recommended to add key: true to the column definition. It forces jqGrid to use the value from ProductID as the rowid.
It's important to understand that the code of jqGrid require to set unique id attribute to every row (<tr> element) of jqGrid. See here. Thus the input data of jqGrid have to contain rowid information. There are many alternative formats for the input data of jqGrid. In the most common way, the input data should contain id property. If your input data uses ProductID as the unique id of the row, then you can add the option jsonReader: { id: "ProductID" } to inform jqGrid about that. In that case you will not need to include ProductID as the column in colModel.
It is little difficult to understand what you want to get - I think you mean rowIndex, so here are some methods which can help.
Methods
getGridRowById( string rowid)
Return the row with id = rowid as document object
getInd(string rowid, [boolean rowcontent])
Returns the index of the row in the grid table specified by grid id row - rowid. If rowcontent is set to true it returns the row document object
If you have the row as document object you can get the index and id. Suppose the rowdata is the document row, then
rowdata.rowIndex is the index
rowdata.id is the id

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.

Set default value in 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>

jqgrid inlinenav - custom row id and delete

Each row has an id in our db different to the jqgrid row id. How can I send this lineid when saving a row?
Also, is there a way to delete a row?
This is my code so far:
var mydata = [
{
lineItemId: "785",
productSku:"n123",
productName:"hello there",
pieces:"123",
value:"23.00",
line:"123"
}
,
{
lineItemId: "803",
productSku:"n1234",
productName:"hello there",
pieces:"123",
value:"23.00",
line:"123"
}
];
var colNames = ['SKU','Product Name', 'Pieces','Total Value','Line Number'];
var colModel = [
{name:'productSku', index:'productSku', width:10, sorttype: 'text', editable:true},
{name:'productName', index:'productName', width:60, editable:true},
{name:'pieces', index:'pieces', width:10, sorttype: 'int', editable:true, formatter: 'integer'},
{name:'value', index:'value', width:10, sorttype: 'int', editable:true, formatter: 'number'},
{name:'line', index:'line', width:10, sorttype: 'int', editable:true, formatter: 'integer', formatoptions:{thousandsSeparator: ""}}
];
initOrdersJqGrid("orderContent", mydata, '<xsl:value-of select="$datapath/OrderId"/>', colNames, colModel, "sku", "desc");
var orderLineOptions = {
keys: true,
aftersavefunc: function (rowid, response, options) {
// only update page if orderis is nil i.e. a new order
if($('#orderidlabel').text() == "") {
log('saving order line item from order with no id yet.');
var dummy = $('<div />').html(response.responseText);
var id = dummy.find('#orderId').val();
$('#orderidlabel').text(id);
$('#orderId').val(id);
$('button[value="Save Order"]').trigger('click');
}
}
}
function initOrdersJqGrid(id, data, orderid, colNames, colModel, defaultSortColumn, defaultSortOrder) {
$("#" + id + "Table")
.jqGrid({
datatype: "local",
data: data,
colNames: colNames,
colModel: colModel,
localReader: { id: "lineItemId"},
pager: '#' + id + 'Pager',
autowidth: true,
gridview: true,
autoencode: true,
height: "auto",
forceFit: true,
shrinkToFit: true, //Width of columns should be expressed in integers which add to 100
sortname: defaultSortColumn,
sortorder: defaultSortOrder,
url: "fs/servlet/CS",
editurl: "CS?action=com.agistix.webinterface.controllers.OrderIC,saveLineItems&orderId=" + orderid
})
.jqGrid('navGrid',"#" + id + "Pager",{edit:false,add:false,del:false,search: false, refresh: false})
.jqGrid('inlineNav',"#" + id + "Pager", { addParams: { addRowParams: orderLineOptions }, editParams: orderLineOptions});
}
If you use datatype: "local" then the items from the array of input data specified by data parameters should have additional property id which specify the value of id attribute of every row (<tr>) of the grid. If you prefer to have another name of the rowsid property you can use localReader to specify it. For example localReader: { id: "Id" } option inform jqGrid to get value of id attribute of rows (rowids) from the Id property. In the case the items of your data should bi like below
{
Id: 76453
productSku:"n123",
productName:"hello there",
pieces:"123",
value:"23.00",
line:"123"
}
The value of id property need be unique.
If you have already some column in the grid which contains id from some database table you don't need to add the same value with id property. Instead of that you can just key: true in the column. jqGrid allows to place key: true in only one item of colModel.
One more common problem with ids of rows it's important to understand. If you need to place more as one grid on a page or if you need to use Subgrid as Grid then you can still have one problem. The ids in database are unique in a table, but one can have the same ids in multiple tables. On the other side the ids of HTML elements (inclusive <tr> elements used for rows) must be unique over the whole page.
To solve the problem one can use idPrefix option of jqGrid. For example you have INT IDENTITY column in the database for the primary key of the table in the database. In the case you will have integers as native ids for rowids. The values can be for example 3, 5, 40 in the first grid. By usage idPrefix: "g1_" the ids assigned to the rows (to <tr> elements) will be "g1_3", "g1_5", "g1_40". So usage of idPrefix: "g1_" for the first grid and another value like idPrefix: "g2_" can solve the problem with potential id duplicates. It's important that jqGrid automatically strip the prefix idPrefix from rowid if it sends some data to the server (if you use editing in the grid for example). One can distinguish "id" and "rowid" names. The "rowids" will be always with prefix. You can use $.jgrid.stripPref function to cut the prefix.

JQGrid Group Text Custom Formatter with Button inside and passing RowData

I have a requirement to provide a button on a grouped row , when onclick of that button , I should capture rowData. I've tried to implement this with custom formatter , grid.SetCell option, but didn't work.
Here is Sample code:
grid.jqGrid({
datatype: 'local',
colNames: ['Id', 'Order Id', 'Name', 'OrderName'],
colModel : [
{ name: 'ID', index: 'ID', editable: true}, //// I grouped by this column
{ name: 'OrderID', index: 'OrderID', width: 30, align: 'center'},
{ name: 'Name', index: 'Name', width: 30, align: 'center'},
{ name: 'OrderName', index: 'OrderName', width: 30, align: 'center'}
],
groupingView: {
groupField: ['ID'],
groupCollapse: true,
groupColumnShow: [false],
groupText: ['<b>{0}</b></div><input type = "button" class = "button" value = "NEW" id = "btnNew" style = "width:100px; hieght:10px" onclick = "javascript:AddNew({OrderID})" /><<b>{1} Orders</b>']
function AddNew(orderId)
{
//// DO SOME THING
}
In above example my grid will be grouped by Id , on each grouped row I need to create a button which onclick event should consist of Order Id. (Order Id is same for all the rows under each group). I need to show Count here also.
I was not able to pass order Id in group Text above, then I use custom formatter on ID column like this .
var html ;
formatter: function(cellValue, options, rowObject)
{
if ((options.rowId.toString()).indexOf("listghead") === -1) {
html = cellvalue + "<input type = "button", value = "New" onclick = AddNew(' +rowObject[1] +')
}
return html;
}
rowObject value has been passed but grouping was broken. If I don't use the above if condition grouping works fine, but onclick event is breaking.
Help me .
Thanks in Advance.
You can get the row value through rowObject so:
html = rowObject.childNodes[1].childNodes[0].wholeText;
This code return a string with the content of rowObject to that columm
You can just pass the rowObject when it comes to group header , and it is not undefined or null when it comes to groupheader.
Just test it using alert(rowObject) when you detect it's group header.

Resources