I was trying to enable navigation based on a selected row. So, the user select a row from jQgrid, and when press the show (is there a show button for the grid, I saw edit, add etc), it needs to go to a new page based on the url (part of the row).
$(document).ready(function () {
function getLink() {
// var rowid = $("#customer_list").jqGrid('getGridParam', 'selrow');
var rowid = $("#customer_list").getGridParam('selrow');
var MyCellData = $("#customer_list").jqGrid('getCell', rowid, 'dataUrl');
return MyCellData;
}
$("#customer_list").jqGrid({
url:'mytestList',
editurl:'jq_edit_test',
datatype: "json",
colNames:['Call Id','Title','dataUrl'],
colModel:[
{name:'callId', width:80, search:false},
{name:'title', width:200, sortable:false},
{name:'dataUrl',hidden:true}
],
rowNum:10,
sortname:'lastUpdated',
sortorder: 'desc',
pager:'#customer_list_pager',
viewrecords: true,
gridview: true
}).navGrid('#customer_list_pager',
{add:true,edit:true,del:false,search:true,refresh:true},
{closeAfterEdit:true, afterSubmit:afterSubmitEvent}, // edit options
{addCaption:'Create New something', afterSubmit:afterSubmitEvent,
savekey:[true,13]}, // add options
{afterSubmit:afterSubmitEvent} // delete options
);
$("#customer_list").jqGrid('filterToolbar');
});
so, the url is passed for each row as dataUrl. I'm trying to read it and set to the button. When debug through firebug, the rowid was 223 (there were only 12 rows in the grid), and the cell value is empty. Currently the button is kept outside the grid, but it may better to be it part of the vavGrid
thanks.
The code like following could solve your problem
$("#customer_list").jqGrid ('navButtonAdd', '#customer_list_pager',
{ caption: ""/*"Show"*/, buttonicon: "ui-icon-extlink", title: "Show Link",
onClickButton: function() {
var grid = $("#customer_list");
var rowid = grid.jqGrid('getGridParam', 'selrow');
window.location = grid.jqGrid('getCell', rowid, 'dataUrl');
}
});
You could just make the show button be part of each row in the grid and use a custom formatter to turn it into a URL.
Based on the example in the wiki, you'll probably need something along the lines of
function myformatter ( cellvalue, options, rowObject )
{
return "Show";
}
Related
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.
I have a grid and I'm using PHP and JSON. I'm using ondblClickRow to do inline editing. The thing that I need is: when I double click in a field, I want the content of this field will be select. I'm sorry to ask about this, but I didn't find this... when I search it on Google I just find examples of select row and this issues.
I recommend you to look this answer and another one. Probably modification of the code from the last answer to the web browser which you use will get your the solution of your problem.
If you want a single cell to be focused after inline edit mode is enabled, try this:
ondblClickRow: function (rowId, rowIndex, columnIndex) {
var grid = $('#mygrid');
grid.editRow(rowId, true, function() {
var colModel = grid.getGridParam('colMode');
var colName = colModel[colIndex].name;
var input = $('#' + rowId + '_' + colName);
input.get(0).focus();
});
}
}
Found the code here:
http://www.trirand.com/blog/?page_id=393/help/setting-focus-on-a-cell-after-entering-edit-mode/
If you have specific columns in a grid when you click on it should select its contents, then in your colmodel add this code to each column:
{
name: 'TEXT_BOX',
index: 'TEXT_BOX',
label: 'Notes',
width: 100,
align: 'left',
sortable: false,
hidden: false,
dataEvents: [ { type: 'click', data: { i: 7 }, fn: function(e) { e.target.select(); } }]
}
dataEvents will select the text in the input field when you click on it.
// Text will get Selected of cell when inline editing
$('#gridTableObj').jqGrid({
....
..
afterEditCell : function(rowid, cellname, value, iRow, iCol){
$('#'+rowid+'_'+cellname).select(); // with this the edited cell value will be selected.
}
...
..
});
I have a jqgrid that has main rows and a footer row (with userdata loaded) and then a formatter that alters the data in the cells to be linkable. The cells in the main body can be clicked and the onCellSelect event will capture the click. However, clicking on data in the footer row does not seem to fire off the onCellSelect event. How do I capture a select/click event in the footer row? Below is the script for the jqgrid.
$('#jqgSummaryResults').jqGrid({
datatype: 'json',
mtype: 'GET',
url: 'some action',
postData: { 'criteria': function () {
some function}},
rowNum: 100,
rowList: [],
pager: '#jqgpSummaryResults',
viewrecords: true,
sortorder: 'asc',
sortname: 'DateField',
width: 1250,
height: 350,
shrinkToFit: true,
gridview: true,
footerrow: true,
userDataOnFooter: true,
onCellSelect: function (rowid, iCol, cellcontent, e) {
var selectedDate = rowid;
savedMailDueDateString = rowid;
var selectedColumn = iCol;
...
},
loadComplete: function (data) {
...
},
colNames: ['DateField',
'Total Jobs',
...
'% Not Mailed'],
colModel: [
{ name: 'DateField', index: 'DateField', align: 'left' },
{ name: 'TotalJobs', index: 'TotalJobs', align: 'left', formatter: hyperlinkColumnFormatter },
...
{ name: 'PercentNotMailed', index: 'PercentNotMailed', align: 'left', formatter: hyperlinkColumnFormatter },
]
}).navGrid('#jqgpSummaryResults', {
excel: false,
edit: false,
add: false,
del: false,
search: false,
refresh: false
});
Thanks for the assistance.
While I didn't see any way to have jqGrid respond to select (doesn't even seem that that footer is selectable) or a click. The footer row is specified by a ui-jqgrid-sdiv class. You could attach a click event handler as below.
$('.ui-jqgrid-sdiv').click(function() {alert('Bong')});
Edit: In response to Gill Bates question to add a footer event but only on a single cell the selector would be:
$('.ui-jqgrid-sdiv').find('td[aria-describedby="GridName_ColumnName"]').click(function() { alert("Bong");});
GridName_ColumnName is the format for all the footer td aria-describedby, and you can see the exact name via firebug element inspector (or any of it's equivalents).
jqGrid registers click event on main <table> of the grid, but it calls onCellSelect not always. First of all (see here) it tests some additional conditions and then returns (ignore click event) if the conditions failed. For example if one clicks on grouping headers of the grid the callback onCellSelect will not be processed.
The problem with footer row because it exists outside of the grid. The main <table> element are placed inside of div.ui-jqgrid-bdiv, but the footer is inside of another table which is inside of div.ui-jqgrid-sdiv. One can examine the HTML structure of jqGrid using Developer Tools of Internet Explorer, Google Chrome, Firebug or other. One will see about the following
The main <table> element (<table id="list"> in the picture above and which get the class "ui-jqgrid-btable") and another table element with the footer (which get the class "ui-jqgrid-ftable") are separate.
So the fist answer of Mark on your question was correct. If one has multiple grids on the page one could specify footer of specific grid using
var $grid = $('#jqgSummaryResults'); // one specific grid
.... // here the grid will be created
$grid.closest(".ui-jqgrid-view").find(".ui-jqgrid-sdiv").click(function() {
// do in case of the footer is clicked.
var $td = $(e.target).closest("td"),
iCol = $.jgrid.getCellIndex($td); // or just $td[0].cellIndex,
colModel = $grid.jqGrid("getGridParam", "colModel");
// $td - represents the clicked cell
// iCol - index of column in footer of the clicked cell
// colModel[iCol].name - is the name of column of the clicked cell
});
P.S. In the old answer are described many other elements of the grid. The descriptions are not full, but it could be probably helpful.
Here little implementation of this problem, i'm new in jquery and jqgrid, but i had same problem and thanks two posts above of #Oleg and #Mark, Im implemented something like that:
//Raport1Grid - name of my jqgrid
//endusers, adminusers,decretusers - name of my rows in colModel
//Raport1Grid_endusers - GridName_ColumnName
var endUsers = $("[aria-describedby='Raport1Grid_endusers']").click(function(){
//remove previous style of selection
$('.ui-jqgrid-ftable').find('.selecteClass').removeClass('selecteClass');
//set selection style to cell
$(endUsers).addClass('selecteClass');
});
//Also can get value of selectedCell
var qwer = $("[aria-describedby='Raport1Grid_endusers']").text();
alert(qwer);
Demo here
http://jsfiddle.net/Tobmai/5ju3py83/
here is declarations of my subgrid:
subGrid : true,
subgridtype: 'json',
subGridUrl: 'manuf_subgr.php',
subGridModel: [{ name : ['Package','Sticker','Manufacturer'],
width : [85,50,100],
params: ['Catalogue']
}
],
gridComplete: function() {
var timeOut = 50;
var rowIds = $("#schedule").getDataIDs();
$.each(rowIds, function (index, rowId) {
if(rowId.row_cnt != 0){
setTimeout(function() {
$("#schedule").expandSubGridRow(rowId);
}, timeOut);
timeOut = timeOut + 200;
}
});
}
what I expect to happen is this line if(rowId.row_cnt != 0) preventing opening a subgrid if there is no data returned from json... yet all grids are open regardless...
can someone help to implement stop for opening empty subgrids?
full code:
jQuery("#schedule").jqGrid({
url:'sched.php',
datatype: "json",
mtype:'GET',
colNames:['Street_Date','Label','Catalogue', 'Artist', 'Title','UKDP','UPCEAN','format'],
colModel:[
{name:'Street_Date',index:'Street_Date desc, ID', sorttype:"date", formatter:'date', formatoptions: {newformat:'d/m/Y'}, width:75},
{name:'label',index:'label', width:100,align:"center"},
{name:'Catalogue',index:'Catalogue', width:85},
{name:'Artist',index:'Artist', width:120},
{name:'Title',index:'Title', width:250},
{name:'UKDP',index:'UKDP', width:35, align:"right", formatter:"number", sorttype:"float"},
{name:'UPCEAN',index:'UPCEAN', width:120, align:"center"},
{name:'format',index:'format', width:70, sortable:false}
],
height: "100%",
rowNum:20,
rowList:[10,20,30,50,100],
sortname: 'id',
viewrecords: true,
sortorder: "desc",
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: true,
cell: "cell",
id: "id",
userdata: "userdata",
subgrid: {root:"rows", repeatitems: true, cell:"cell" }
},
pager: '#schedule_pager',
caption:"Release Schedule",
grouping:true,
groupingView : {
groupField : ['Street_Date']
},
subGrid : true,
subgridtype: 'json',
subGridUrl: 'manuf_subgr.php',
subGridModel: [{ name : ['Package','Sticker','Manufacturer'],
width : [85,50,100],
params: ['Catalogue']
}
],
gridComplete: function() {
var timeOut = 50;
var rowIds = $("#schedule").getDataIDs();
$.each(rowIds, function (index, rowId) {
if(rowId.row_cnt != 0){
setTimeout(function() {
$("#schedule").expandSubGridRow(rowId);
}, timeOut);
timeOut = timeOut + 200;
}
});
},
onSelectRow: function (rowId) {
$("#schedule").jqGrid ('toggleSubGridRow', rowId);
}
});
You write in the comment that you are newbie and it's the second day when you use it. jqGrid is relatively complex and your first example which you try to implement seems to me too complex for newbie. You try to load fill jqGrid with the data from the database and do grouping and subgrid in one grid.
What you try to implement in your demo can be solved by usage of expandOnLoad: true property of the subGridOptions option:
subGridOptions: {expandOnLoad: true}
You can see the feature on the official demo disguised under "Hierarchy" / "Expand all Rows on load". There are one important problem which I described in the answer. The problem is shortly the following: internal implementation of Ajax requests used in jqGrid prevent (skip) Ajax requests when another pending (not yet answered by the server) are working (see .grid.hDiv.loading in the places of the code here, here in the subgrid module and here, here and here). Neither expandOnLoad: true nor your current implementation can grantee that new Ajax request will be started during previous one still not responded. So you can have not all subgrids opened. You main question: "how to prevent opening of empty subgrids or how to hide it?", I find the second (and less important) question. Even if you see currently that your web site opens all subgrids it can be that access to the same site from more far place from the internet will follow opening of one or some subgrids only.
So I think that you should either change the design of your web page (change what you want to display in subgrids) or change the implementation so that you construct a queue with the list of subgrids which should be opened and you will open the next grid only after the previous one will be opened.
Alternatively you can includes the data for all subgrids in the response for the main grid. In the case you should use subGridRowExpanded callback to fill the grids as subgrid as grid. You you would use no caption and no pager option in the subgrids you will be get the same look as with the standard subgrids. Additionally you will have much more flexibility in the options. I personally prefer to subgrid as grid.
I am trying to test adding a new row and deleting a row in jqGrid and I find that the grid does not refresh to show the new row or remove the deleted row after adding/deleting a row. The server side piece is not in place yet for adding/deleting, so I just fed editurl the same url I used to load data into the grid.
.navGrid('#' + id + '-pager',
{addtext: 'Add Code Value', deltext: 'Delete Code Value', edit:false,add:true,del:true,search:false, refresh:false},
{closeAfterAdd: true, reloadAfterSubmit: true} /* Edit options */,
{closeAfterAdd: true, reloadAfterSubmit: true} /* Add options */,
{reloadAfterSubmit: true} /* Delete options */);
Am I missing something here? I thought reloadAfterSubmit should update the grid with the added/deleted row?
Thanks.
Edited: My custom add function, which is unnecessarily complicated is (note: this should be a client side add only)
addfunc = function() {
//Find dirty unsaved row if any and add to the grid before adding empty row
var dirtyRow = jQuery('#' + id).find('tr[editable]');
var dirtyRowId = dirtyRow.attr('id');
if (dirtyRow.length > 0) {
dirtyRow.addClass('data-isDirty', true);
var rowData = jQuery('#' + id).jqGrid('getRowData', dirtyRowId);
jQuery('#' + id).jqGrid('addRowData', rowId, dirtyRowId);
//The row when added to the grid should not be editable but a normal row
dirtyRow.find('input').each(function() {
var text = jQuery(this).attr('value');
jQuery(this).replaceWith(text);
});
}
var rowId = Math.floor(Math.random()*1000) + 'add_new';
jQuery('#' + id).jqGrid('addRowData', rowId, that.getEmptyRow(colModel), 'first');
var firstRowId = jQuery('#' + id).jqGrid('getDataIDs')[0];
//Add an empty editable row at the top
jQuery('#' + id).jqGrid('editRow', firstRowId);
}
If you use dummy URL, then it don't answer on HTTP POST requests probably. You can solve the problem by usage of mtype: "GET" option. In the case you can use any existing server URL from the same site like "/":
.navGrid('#' + id + '-pager',
{addtext: 'Add Code Value', deltext: 'Delete Code Value',
edit:false,add:true,del:true,search:false, refresh:false},
{mtype: "GET", closeAfterAdd: true, reloadAfterSubmit: true} /* Edit options */,
{mtype: "GET", closeAfterAdd: true, reloadAfterSubmit: true} /* Add options */,
{mtype: "GET", reloadAfterSubmit: true} /* Delete options */);
As editurl parameter of jqGrid you can use any existing URL like editurl: "/"