jqGrid - Setting select value in edit form - jqgrid

I'm having a hard time trying to set the value of a select box in the edit form. For example I have my colModel set up like this.
colModel:[
{name:'communication_id', key: true, index:'communication_id', width:30},
{name:'communication_type_id', index:'communication_type_id', width:30},
{name:'communication_type_select',index:'communication_type_select',hidden:true,width:150, editable:true,edittype:'select',formatter:'select',editrules: {edithidden:true},
formoptions:{label:'Communication Type'},
editoptions:{dataUrl:"working_data_url",
buildSelect: function(json){
var response = $.parseJSON(json);
var s = '<select>';
$.each(response.results,function(i,com){
s += ('<option value="' + com.communication_type_id + '">'+ com.communication_type_desc + '</option>');
});
return s + "</select>";
},dataInit: function(elem){
alert(temp);
//alert($('#com_table_communication_type_id').val());
//$(elem).val($('#com_table_communication_type_id').val());
}}},
{name:'communication_send_dt', index:'communication_send_dt', width:150, sortable:true, sorttype: 'date',
firstsortorder: 'desc', datefmt:'m/d/Y', editable:true},
editoptions: {recreateForm:true},
rowNum:10,
width:'100%',
rowList:[10,20,30],
pager: '#com_pager',
sortname: 'communication_send_dt',
viewrecords: true,
sortorder: "desc",
loadonce:true,
caption: "Communication",
jsonReader: {
repeatitems : false,
root: "results"
},
height: '100%',
onSelectRow: function(communication_id){
var comtype = $(this).getRowData(communication_id);
var temp = comtype['communication_type_id'];
}
});
grid.jqGrid('navGrid','#com_pager',{edit:true,add:false,del:false});
When I click the edit button it loads the select options correctly, but I am having trouble with which one is selected. I want the value from communication_type_id to load into communication_type_select and I have tried different things to get that too happen. Basically if the id in communication_type_id is 2, then I want the select box in the edit form to be set to 2 as well when the edit form loads. Any help on this?
Update 1: I got it mostly working now by using beforeShowForm, but now I am running into a weird thing. When I have an alert in the beforeShowForm everything works, but when its commented out, it does not work! Thanks for your help #Oleg!
grid.jqGrid('navGrid','#com_pager',{edit:true,add:false,del:false},
{closeOnEscape:true, recreateForm:true,beforeShowForm: function(formid){
//alert("com type id = "+comidvar + " response id = "+comrespvar + " com form type id = "+comfrmtypevar);
$("#communication_type_select", formid).attr("value",comidvar);
$("#form_response_select", formid).attr("value",comrespvar);
$("#form_type_select", formid).attr("value", comfrmtypevar);
}},

If I understand you correct you should use ajaxSelectOptions option of jqGrid with data property. You can define some additional option like communication_type_id in the data which value you can returns by the usage of $("#list").jqGrid('getGridParam', 'selrow') and then getCell to get the value from communication_type_id column. See the answer for details.

Related

jqGrid : searchrules in single Field searching

I'm trying to validate the search field for integer data alone but unfortunately am unable to do so. I have tried all possible solutions like searchrules:{required:true,integer=true} etc..
But none of them proves fruitful.
I basically launch the search dialog with the field and without inputting any data, am hitting on the 'Find' button. As per the above options, i believe a validation message should be shown to the user asking him to enter a value in the field before hitting find.
[UPDATED] - Code Snippet
var grid = $("#list");
grid.jqGrid({
url:'/index.jsp',
datatype: 'json',
mtype: 'POST',
colNames:['Name','Age', 'Address'],
colModel :[
{name:'name', index:'name', width:55,search:true },
{name:'age', index:'age',
width:90,editable:true,search:true, stype:'text',
searchrules:{required:true,integer:true}},
{name:'address', index:'address', width:80,
align:'right', editable: true,search:false }
],
pager: '#pager',
jsonReader : {
root:"address",
page: "page",
total: "total",
records: "records",
repeatitems: false
},
rowNum:10,
rowList:[10,20,30],
sortname: 'name',
sortorder: 'desc',
viewrecords: true,
gridview: true,
autowidth: true,
toppager: true,
loadtext: "Loading records.....",
caption: 'Test Grid',
gridComplete: function(){
}
});
**grid**.jqGrid('navGrid','#pager',
{view:true,edit:true,add:true,del:true,refresh:true,
refreshtext:'Refresh',addtext:'Add',
edittext:'Edit',cloneToTop:true,
edittitle: "Edit selected row"},
{},{},{},
{caption: "Search The Grid",Find: "Find Value",Reset: "Reset"},
{});
[Updated] : Am not able to make the searchrules properly work for the single/advanced searching modes.
[Updated] : Even the 'Validation in Search' in
jqGrid Demo is not working for searchrules.
The reason of described problem is a bug in jqGrid. The line
ret = $.jgrid.checkValues(val, -1, null, colModelItem.searchrules, colModelItem.label);
initialize the third parameter of $.jgrid.checkValues to null, but the last version of checkValues implementation started (see the line) with
var cm = g.p.colModel;
but g is initialized to null. The last modification which generates the error was based on my suggestion, but I don't wrote the part of the code.
One can solve the problem in different way. I would suggest to modify the line where $.jgrid.checkValues will be called with null parameter to the following
ret = $.jgrid.checkValues(val, -1, {p: {colModel: p.columns}}, colModelItem.searchrules, colModelItem.label);
Additionally, to be sure, I would suggest to modify one more line
if(!nm) { nm = g.p.colNames[valref]; }
to
if(!nm) { nm = g.p.colNames != null ? g.p.colNames[valref] : cm.label; }
The fixed version of jquery.jqGrid.src.js one can get here. I will post my bug report with the same suggestions later ti trirand.

Editing on external file Jqgrid

I have some data displayed on a grid generated with JQgrid. I want to do the edit of a selected row on a separate PHP file. What I need is that when I click a row on the Jqgrid, I got an ID for the selected row, and send it as a parameter to that separate PHP file, which is called by pressing a button that is not part of the grid, also warn the user if he press the edit button and no row is selected on the JQGrid. Somebody know how to do this?
Below is the code of the JQgrid table that I'm creating for the JQGrid, with the button to redirect to the other file:
<div>
<h1>Manejo de alumnos</h1>
<table id="list"></table><!--Grid table-->
<div id="pager"></div> <!--pagination div-->
</div>
<br>
Editar alumno
Here is the code of my JQgrid:
$(document).ready(function (){
jQuery("#list").jqGrid({
url: 'http://localhost/ProyectoNetbeans/CodeIgniter_2.1.3/index.php/Alumnos_controller/loadData',
mtype : "post", //Ajax request type. It also could be GET
datatype: "json", //supported formats XML, JSON or Arrray
colNames:['Expediente','Primer apellido','Segundo apellido', 'Nombre','Cédula'], //Grid column headings
colModel:[
{name:'expediente',index:'expediente', width:300, editable:true, edittype:'text'},
{name:'primerApellido',index:'primerApellido', width:300, editable:true, edittype:'text'},
{name:'segundoApellido',index:'segundoApellido', width:300, editable:true, edittype:'text'},
{name:'nombre',index:'nombre', width:300, editable:true, edittype:'text'},
{name:'cedula',index:'cedula', width:300, editable:true, edittype:'text'}
],
pager: '#pager',
rowNum:10,
rowList:[15,30],
sortname: 'primerApellido',
reloadAfterSubmit: true,
sortorder: 'asc',
viewrecords: true,
postData: {expediente:"expediente"},
caption: 'Alumnos'
}).navGrid('#pager',{edit:false,add:false,del:true},
{//EDITAR
url:"http://localhost/ProyectoNetbeans/CodeIgniter_2.1.3/index.php/Alumnos_controller/deleteData"
},
{
//AGREGAR
},
{// DELETE
jqModal:false,
reloadAfterSubmit:true,
savekey: [true,13],
drag: true,
closeOnEscape:true,
closeAfterAdd:true,
url:"http://localhost/ProyectoNetbeans/CodeIgniter_2.1.3/index.php/Alumnos_controller/deleteData",
onclickSubmit:function(params, postdata){
var index=$("#list").getGridParam("selrow");
var rowId = jQuery('#list tr:eq('+index+')').attr('ID');
var dataFromTheRow = jQuery('#list').jqGrid ('getRowData', rowId);
var dataFromCellByColumnName = jQuery('#list').jqGrid ('getCell', rowId, 'expediente');
return { expediente: dataFromCellByColumnName };
}
},
{multipleSearch : false}, // enable the advanced searching
{closeOnEscape:true} /* allow the view dialog to be closed when user press ESC key*/
);
});
You can hook up an event every time a row is selected where you pass the information to your Edit Button via:
onSelectRow: function(id){
//pass id to button
and then you can test when the edit button is pressed if a row is selected by
if ($('#gridName').jqGrid('getGridParam', 'selrow')) {
...
}
else {
return false;
}
I was able to solve this using Mark's answer and doing some investigation. First, you need to pass some parameter which is going to be used by the button, this parameter will depend on the logic of your grid. The code to get the parameter is the following, you need to place this in the section which contain the ColModel:
onSelectRow: function(id)
{
var dataFromCellByColumnName="";
var index=$("#list").getGridParam("selrow");
var rowId = jQuery('#list tr:eq('+index+')').attr('ID');
var dataFromTheRow = jQuery('#list').jqGrid ('getRowData', rowId);
dataFromCellByColumnName = jQuery('#list').jqGrid ('getCell', rowId, 'expediente');
setExpediente(dataFromCellByColumnName);
}
On this particular case, I'm sending the "expediente" field of the grid to the "setExpediente" function. The setExpediente function is:
var expediente="";
function setExpediente(elExpediente)
{
expediente = elExpediente;
}
Note that the variable "expediente" is a global variable. Then, you need to create a function that will use the global variable "expediente". I made this one:
function revisarSeleccion()
{
if (expediente=="")
{
alert("Seleccione una fila")
}
else
{
alert(expediente);
}
}
This will check if the variable "expediente" is blank or not, and depending on the results you can make your decisions.
Thanks to Mark for his help on this.

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

jqGrid edit record form empty

I've implemented a jqGrid, but when I try to use the built-in form edit feature, an empty form pops up.
For every column i have set editable:true except for the table's primary key, an auto-incremented id. What am I doing wrong? Do I need to have a valid editurl, rather than clientArray? Below is the jqGrid implementation:
$.ajax({
type: "GET",
url: colUrl,
datatype: "json",
success: function(result){
result = jQuery.parseJSON( result )
var colN = result.colNames;
var colM = result.colModelList;
$("#jqTable").jqGrid({
url:dataUrl,
datatype: 'xml',
mtype: 'GET',
colNames:colN,
colModel:colM,
shrinkToFit: false,
caption: db + "." + table,
pager: '#jqPager',
rowNum:10,
rowList:[10,20,30],
sortname: 'dbid',
editurl: 'clientArray',
sortorder: 'asc',
viewrecords: true,
width: 1000,
height: 400
});
$("#jqTable").jqGrid('navGrid', '#jqPager',
{edit:true, add:false, del:false, search:true, view:false}, //options
{}, // edit options
{}, // add options
{}, // del options
{multipleSearch:true,
sopt : ['eq',//equals
'ne',//not equals
'lt',//less than
'le',//less than or equal
'gt',//greater than
'ge',//greater than or equal
'bw',//begins with
'bn',//does not begin with
'in',//in
'ni',//not in
'ew',//ends with
'en',//does not end with
'cn',//contains
'nc']//does not contain
}, // search options
{} //view options
);
},
error: function(x,e){
alert(x.readyState + " " + x.status + " " + e.msg);
}
});
and here is sample colModel and ColName string:
"colModelList": [{"name":"dbid","index":"dbid","editable":"false"},{"name":"description","index":"description","editable":"true"},{"name":"file_name","index":"file_name","editable":"true"}],"colNames": ["dbid","description","file_name"]
I suppose that the reason is because you use "editable": "true" or "editable": "false" instead of "editable": true or "editable": false.
Moreover you try to use form editing for the local data editing. The current jqGrid implementation support local data editing only for cell editing and inline editing. If you do need to use form editing to edit local data you can find my demo in the answer. The code will be longer, but it is do possible to implement this.

How to dynamically pass all of the jqgrid cell value when deleting a row

I'm very new with JQGrid, so I apologize in advance if this a very 'duh' question..
The case is when I delete a row in the grid, jqgrid only pass the parameter id to the editurl. However, there are cases when I need more than one id parameter to delete a row, for instance for grid like this:
{UserID, Message} => {(user1, "hello"),(user1, "hola"),(user2,"hi")}
If i want to only delete the (user1, "hello") row, I need JQGrid to pass the parameter UserID=user1 and Message="hello" otherwise the (user1, "hello") and (user1, "hola") will be deleted.
I alreadt tried to modify the url before deleting by using onClickSubmit parameter:
onclickSubmit: function(rp_ge, postdata){
rp_ge.url = 'RowManipulator.php?UserID='+$('#grid').getCell(postdata, 'UserID')+
'&Message='+$('#grid').getCell(postdata,'Message');
However the resulted url (after checking on firebug) is:
RowManipulator.php?UserID=user1&Message=false
instead of RowManipulator.php?UserID=user1&Message="hello". It seems that the message paramater can't be delivered.
Does anyone have any idea how to achieve what I intended to? Any help will be very appreciated
Updated:
Here is the jquery code:
jQuery(document).ready(function(){
jQuery("#list").jqGrid(
{ url:'DataFetcher.php',
datatype: 'xml',
mtype: 'GET',
colNames:['UserId','Message'],
colModel:[
{name:'UserId',index:'UserId',width:75, editable:false,align: 'left'},
{name:'Message',index:'Message',width:200, editable:true,align: 'left'}
],
pager: jQuery('#pager'),
rowNum:10,
rowList:[10,20,30],
sortname:'UserId',
sortorder: "asc",
viewrecords: true,
imgpath: 'jqgrid/css/images',
caption: 'MESSAGE',
editurl:'RowManipulator.php',
height: 350,
width: 1000});
jQuery("#list").jqGrid('navGrid','#pager',{},
{height:280,reloadAfterSubmit:true},
{height:280,reloadAfterSubmit:true},
{onclickSubmit: function(rp_ge, postdata){
rp_ge.url = 'RowManipulator.php?UserId='
$('#list').getCell(postdata, 'UserId') &&
Message=$('#list').getCell(postdata,Message);
},
reloadAfterSubmit:true},
{sopt:['cn','eq']})
The line
rp_ge.url = 'RowManipulator.php?UserId='
$('#list').getCell(postdata, 'UserId') &&
Message=$('#list').getCell(postdata,Message);
has syntax errors. Is postdata not already contain the 'UserId'? Then $('#list').getCell(postdata, 'UserId') will gives you back postdata.
Try with
rp_ge.url = 'RowManipulator.php?UserId=' +
$('#list').getCell(postdata, 'UserId') +
'Message=' + $('#list').getCell(postdata,'Message');
or better with
rp_ge.url = 'RowManipulator.php?' +
jQuery.param({UserId: $('#list').getCell(postdata, 'UserId'),
Message: $('#list').getCell(postdata, 'Message')});

Resources