jqGrid does not selects cell value as a selected dorp down value In edit mode - jqgrid

I am using jqGrid v 4.0 in my application to display tabuler data with Inline edit feature. One of the column in the Grid is a type of "Select". I have populated this select with following server side code:
//get all Departments
HRDept = $.ajax({
url: '../../PerformanceReview/GetHRDepartments/',
async: false,
success: function(data, result) {
if (!result)
alert('Failure to retrieve the HR Departments.');
}
}).responseText;
I have populated the Grid column with following sysntax:
name: 'HRDepartment', index: 'Department', align: 'left', editable: true, edittype: 'select', editoptions: {value: HRDept}
But on click of edit button (inline), it shows dropdown on on top of cell but the value is not equal to current cell value. it is always first value of drop down. I had compared the text which i am populating while loading Grid with the text of Dropdown and they are matching.
Could some one help me to set dropdown value similar as cell value.

Your edit options look wrong, it should be "value:text;" and the value should match your data results.
{ ... editoptions: {value: "HRDept:HR Department;" }}
You can checkout the demo of Row Edition -> Input Types at the jqGrid Demo site., which includes a dropdown list edit cell.

If you get the select values from the server you should use dataUrl option of the editoptions instead of value. Then the jqGrid will make the Ajax request at the beginning of the editing and fill the select element with the server response. It is important to understand that the server response should be in another form:
<select>
<option value='101 - Equity Partners'>101 - Equity Partners</option>
…
</select>
If you have already the code on the server which provide the information in another format and you can't change the server code you can define additional buildSelect function which get as the parameter the server response and should return the data in the above format ('...'). See UPDATED part of the answer for the code example.

Related

Jqgrid - Compare value of two columns in jqgrid. One of them is a textbox and other is non editable column.

There is a textbox control in one column in my jqgrid. When value is entered in this textbox in a row , it should compare that value from another column (which is non editable) and show error when the values are not equal.
From the wiki in Here
You can see the solution I created in JsFiddle
To see it working try to edit lastname cell and it will throw an error if it does not match firstname in the row (unrealistic but just for illustration purposes)
Use beforeSaveCell
afterSaveCell: function(rowid,name,val,iRow,iCol) {
alert("alert1!");
},
beforeSaveCell: function(rowid,name,val,iRow,iCol) {
// Just to get the current row b/se it is not available in custom_func
currentRow= rowid;
},
AND add editrules to your cell to be edited and validated
{name:'lastname', index:'lastname', width:90, editable: true , "editrules":{"custom":true,"custom_func":validateText}},

Jquery-Jqgrid in MVC

I have a Jqgrid, and I am trying to show some fields on the grid, but when I Form Editing it, and show all Fields, which is having more columns than showing on the Grid.
For Example: I have a Document table, which have ID, Name,Size, Description, Date
on the Grid I only show ID, Name, and Size
when user click on the Edit, which is Form Editing, then let the users Edit all the Columns.
How can I do it?
well first you gotta put some code here, from what i can understand here, you have a grid with lets say 5 columns and when you want to go with form editing then you want to edit and show only 3 columns, right? so what you need to do, put editable:false with your colModal
for example
{ name: 'Id', index: 'Id', align: 'right', editable: false, hidden: true}
this will hide the Id column in grid and if you try to go for form editing Id will not be editable and it will not be there in edit form dialogue..

while the select editoption posts the value (or id) of the selected list item, autocomplete posts the label - i need id posted

While both autocomplete and select in jqgrid editform place the selected label into the cell, select will place the value (id) in the postdata array where autocomplete will place the label into the postdata array.
is there a way to get the editoption's autocomplete to post the item value (id) instead of the label?
here is the jqgrid code segment i'm using autocomplete in...
$('#tab3-grid').jqGrid({
colNames:['Workorder', 'wo.CUID',.....],
colModel:[
.
.
.
{name:'wo.CUID', index:'cu.LastName', width:120, fixed:true, align:'center', sortable:true, editable:true, edittype:'text',
editoptions:{dataInit:function(el){$(el).autocomplete({ source: 'php/customer-ac-script.php'
, minLength: 1
})
}
},
formoptions:{rowpos: 1, label:'Customer', elmprefix:'* '},
editrules:{required:true}
},
.
.
.
$('#tab3-grid').jqGrid('navGrid', '#tab3-pager',
{view:true, closeOnEscape:true, cloneToTop:true}, // general parameters that apply to all navigation options below.
{jqModal:true, navkeys:[true,38,40], savekey:[true,13]}, // edit options.
{jqModal:true, navkeys:[true,38,40], savekey:[true,13], reloadAfterSubmit:false, afterSubmit: addRecordID}, // add options.
{jqModal:true, afterSubmit: serverMessage}, // del options.
{jqModal:true}, // search options.
{jqModal:true, navkeys:[true,38,40]} // view options.
);
The php code segment:
// construct autocomplete select.
$i = 0;
while($row = mysql_fetch_assoc($result)) {
$output[$i][$crudConfig['id']] = $row['CUID'];
$output[$i][$crudConfig['value']] = $row['LastName'];
logMsg(__LINE__,'I','cu.CUID: '.$row['CUID'].', cu.LastName: '.$row['LastName']);
$i++;
}
// encode to json format and send output back to jqGrid table.
echo json_encode($output);
logMsg(__LINE__,'I','Send json output back to jqGrid table: '.json_encode($output));
Would it be as simple as calling a function under the autocomplete select event or the grid before or after editform submit?
Also, i noticed this note in the jqgrid doc's for datainit: that says...
Note: Some plugins require the position of the element in the DOM and
since this event is raised before inserting the element into the DOM
you can use a setTimeout function to accomplish the desired action.
Would the lack of including the settimeout function be causing the problem?
The server code which provide the JSON response on the autocomplete request has id and value properties. On the other side the standard behavior of jQuery UI Autocomplete is to use label and value properties (see "Datamodel" in the documentation). The value of label property (if any exist) will be used to display in the contextmenu. The value of value property will be placed in the <input> field after the user choose the item from the contextmenu. The value of label property can has HTML markup, but the value of value property must be the text.
So I see the problem as pure problem of the usage of jQuery UI Autocomplete independent on jqGrid. If I understand correct your question you can solve your problem by modification your server side code.
Oleg's answer clarifying the data model for jquery UI's autocomplete, has allowed me to move forward and understand that autocomplete has nothing to do with constructing and sending the postdata array to the server, jqgrid's editform handles it. With that knowledge, i was able to answer my original question and successfully integrate autocomplete into jqgrid. So, in the interest of sharing, i'd like to show you all my motivation and solution.
By default, selecting a label from the autocomplete list put's the value of the selected label/value pair into the text box. All the editform cares about when you submit is what's in the edit fields. So when you submit the editform, the cell's postdata element value will again contain the value of the autocomplete text box. But what if while wanting to post the value of the label/value pair, you want the label of the label/value pair displayed in the text box? You have a problem! How do you get the value of the label/value pair posted to the server?
Well, after spending a few days on it, it turns out to be quite simply. While i'm sure there is more than one solution, here is mine:
add a hidden id column in the grid
define the select: and focus: events in the autocomplete function
in the select: function; insert the selected label into the text box (optional), disable the default behavior of autocomplete, then set the cell of the hidden column to the value of the selected label/value pair
in the focus: function; insert the selected label into the text box(optional), disable the default behavior of autocomplete
add an "onclickSubmit:" event to the navgrid edit options with function name something like "fixpostdata"
in the "fixpostdata" function; get the cell value of the hidden column and insert it into the postdata element associated with the cell.
The following are the grid and javascript code segments i used…
grid segments
{name:'wo_CUID', index:'wo_CUID', width: 70, hidden: true},
{name:'wo.CUID', index:'cu.LastName', width:120, sortable:true, editable:true, edittype:'text',
editoptions:{
dataInit:function(el){ // el contains the id of the edit form input text box.
$(el).autocomplete({
source: 'php/customer-ac-script.php',
minLength: 1,
select: function(event, ui){event.preventDefault();
$(el).val(ui.item.label);
var rowid = $('#tab3-grid').getGridParam('selrow');
// set the hidden wo_CUID cell with selected value of the selected label.
$('#tab3-grid').jqGrid('setCell', rowid,'wo_CUID',ui.item.value);},
focus: function(event, ui) {event.preventDefault();
$(el).val(ui.item.label);}
})
}
},
formoptions:{rowpos: 1, label:'Customer', elmprefix:'* '},
editrules:{required:true}
},
.
.
$('#tab3-grid').jqGrid('navGrid', '#tab3-pager',
{view:true, closeOnEscape:true, cloneToTop:true},
{jqModal:true, navkeys:[false,38,40], onclickSubmit: fixpostdata}, // edit options.
.
.
javascript function
// define handler function for 'onclickSubmit' event.
var fixpostdata = function(params, postdata){
var rowid = $('#tab3-grid').getGridParam('selrow');
var value = $('#tab3-grid').jqGrid('getCell', rowid,'wo_CUID');
postdata['wo.CUID'] = value;
return;
}
The fixpostdata function fires when you submit the editform but befor the postdata array is sent to the server. At this point you replace the cell's postdata element value with whatever you want. In this case, the value of the label/value pair stored in the hidden column cell. When the function returns, the modified postdata array is sent to the server.
Done!

How to supply a Row ID when using jqGrid 'editGridRow' to create a new row and not the auto generated Row ID jqg1

I'm new to jqGrid, so hopefully someone can point me in the right direction.
Basically, I am using jgGrid to display a list of dates and costs that I have read in from a file that I want the user to be able to amend or add new entries or delete existing entries. Upon the user clicking an onscreen button "Apply" to post back the form , I read out the jqGrid and post back to Server in the form of a JSON string.
My problem is that when I add new rows (via 'editGridRow'), jqGrid is using it's autogenerated jqg1, jg2, jg3, etc and the new rows are being populated at the top of grid instead of at their row id position i.e at the bottom of grid.
I am able to generate RowID's as necessary, however I do not seem to be able to supply them to 'editGridRow' when creating new entries, instead it appears I have to use the keyword "new".
As you are aware the reason I am using editGridRow instead of addRowData is that editGridRow creates a modal dialog for the user to enter the data.
Any help would be appreciated.
This is what I would like to use to supply a row ID:
$("#tableGrid").jqGrid('editGridRow', gridRowID, {reloadAfterSubmit:false});
This is what I have to use to get the code to work:
$("#tableGrid").jqGrid('editGridRow', "new", {reloadAfterSubmit:false});
Here is the code snippet I use for creating the gqGrid in my JSP:
var gridRowID = ${costHistoryEntries}.length
$("document").ready(function() {
$("#tableGrid").jqGrid({
data: ${costHistoryEntries},
datatype: "local",
height: 200,
colNames:['Date', 'Cost'],
colModel:[
{name:'chdate', index:'chdate', width:110, sorttype:"date", editable:true, editrules:{date:true, required:true, custom:true, custom_func:checkDate}, datefmt:'d/m/Y'},
{name:'cost', index:'cost', width:160, align:"right", sorttype:"float", editable:true, editrules:{number:true, required:true}, formatter:'float'},
],
autowidth: true,
loadonce: true,
sortname: 'chdate',
sortorder: "desc",
rowList:[10, 20, 30],
pager: jQuery('#tablePager'),
viewrecords: true,
editurl: '/myurl',
caption: "Cost History Entries" }
);
$("#tableGrid").jqGrid('navGrid', "#tablePager", {edit:true, add:true, del:true, search:true, refresh:true});
$("#addEntry").click(function() {
gridRowID++;
$("#tableGrid").jqGrid('editGridRow', "new", {reloadAfterSubmit:false});
});
});
I also created a button and linked it to "addEntry" as an alternative way to adding a new row using the jqGrid Navigator "add/edit/delete/find/reload" bar. As you can see previous to loading the grid with data I stored the number of entries in gridRowID. What I was hoping to be able to do in the "#addEntry" click function was use the updated gridRowID as a RowID parameter.
As a FYI:
In a previous version of the code I was using the following to load the data into the grid:
var griddata = ${costHistoryEntries};
for (var i=0; i <= griddata.length; i++) {
$("#tableGrid").jqGrid('addRowData', i+1, griddata[i], "last");
}
but found that I could do that same with
data: ${costHistoryEntries},
Both versions correctly create row ID's for the supplied sample data from the server:
[{"chdate":"20/05/2011","cost":"0.111"},{"chdate":"01/06/2011","cost":"0.222"},{"chdate":"07/07/2011","cost":"0.333"}]
My problem is adding new rows of data.
Further update, On the server side, as a test I intercepted the post to /myurl and updated the id from "_empty" to "7" but the new entry in jqGrid still has an autogenerated jqGrid Row ID "jqg1":
Key = chdate, Value = 26/09/2011
Key = oper, Value = add
Key = cost, Value = 14
Key = id, Value = _empty
Updated Key = chdate, Value = 26/09/2011
Updated Key = oper, Value = add
Updated Key = cost, Value = 14
Updated Key = id, Value = 7
I am not quite understand your requirement. You get the input for the jqGrid from the server, but use datatype: "local" instead of the datatype: "json" for example which instruct jqGrid to get ajax request to the server to get the data whenever as needed. Moreover you want to save the date on the server, but use editurl: '/dummyurl' instead of the real server url. The editurl would get the input data from the $("#tableGrid").jqGrid('editGridRow', "new", {reloadAfterSubmit:false}); and should post back the id of the new generated row. Is it not what you want?
So my suggestion would be to use some server based datatype (the bast is datatype: "json") and in the same way use real editurl which save the data on the server (in the database mostly) and place in the server response the id on the new generated data item.
UPDATED: If you use reloadAfterSubmit: false option of the editGridRow you have to use afterSubmit event handler together with reloadAfterSubmit which decode the server response and return the result in the format [true,'',new_id] For example if your server just return new rowid as the data you can use
$("#tableGrid").jqGrid('editGridRow', "new",
{
reloadAfterSubmit: false,
afterSubmit: function (response) {
return [true, '', response.responseText];
}
}
);

Get the client side value of a grid cell containing a <select>

I am trying to write a jquery function that scans the whole of a jqrid to check if any of its cells have a value.
The issue I am having is that there does not seem to be a way of retrieving the selected value of a cell that contains a select box. The jqgrid docs clearly states the following for the getCell and getRowData methods.
Do not use this method when you
editing the row or cell. This will
return the cell content and not the
actuall value of the input element
Which is fair enough, but given that, how do I actually get the value?
Its not possible to parse the html that is returned from the select content, as none of the options are flagged as selected, even if they appear to be selected in the browser.
For reference here is a snippet of my code:
var colModels = this.grid.jqGrid('getGridParam', 'colModel');
for (i = 1; i < colModels.length; i++) {
var colModel = colModels[i];
if (colModel.edittype == 'select') {
var colData = this.grid.jqGrid('getCol', colModel.name, false);
for (j = 0; j < colData.length; j++) {
if (colData[j] != 0) {
//alert("select change: " + colData[j]);
//alert(j+' GridName_' + colModel.name)
//alert("select change: " + $('#GridName_' + colModel.name).val());
//return has value?;
}
}
}
}
Column definiton:
{ name: "AppleId", index: "Appled", width: 150, align: "left", resizable: false, editable: true, edittype: "select", editoptions: { value: function() { return xxx.buildAppleSelect(); } }, formatter: function(cellvalue, options, rowObject, action) { return xxx.buildAppleSelectHtml(cellvalue); } };
I also experimented with afterEditCell and other similar events - but the problem with these is that - clicking the select box does not put the sell in edit mode - you have to click the cell first and then the select.
In short - how do I get the selected value, client side - can it be done?
There are simular questions here, here and here. But none seem to tackle the issue (client side).
No. Here is some HTML that I obtained from a test grid using getRowData:
<select class="editable" size="1" name="test" id="5_test">
<option value="0">Zero</option>
<option value="1">One</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
You are right - there is not enough information in the markup to determine which value is selected. In order to get the selected value you will have to bring the row out of edit mode, for example by using grid method saveRow.
It seems to me Dan that you thy to go in a wrong way. I am not really understand why you do want to have grid cell containing of <select>, but if you'll explain me what do you want I am sure I'll find a solution of you problem.
First I explain what I find strange in your question. If you define edittype: "select", then jqGid has typically a string and not a <select> element inside. If you are in en edit mode (for example in inline edit mode), then all other rows excepting selected row has also a string and not a <select> element inside. If user make a chose and press enter, the edit mode will be ended and the modified data will be saved (or send to the server). So it is also not important which values were displayed before.
It seems to me you have some problems because of some custom building of values in buildAppleSelect and custom formatting in buildAppleSelectHtml.
If you be want see intermediate values from select you can use dataEvents with 'change' in the editoptions.
I hope now you understand what I find strange in your question. If you explain me what is your problem and why you do have more then one <select> element and want to read intermediate select values I'll try to find a solution for you.
UPDATED: I posted a code which shows how use dataEvents with 'change' in JQGrid Inline Editing : Filter subcategory dropdown list based on another category dropdown. Probably it will help you.

Resources