jqGrid with Related Tables in MySQL - javascript

Good morning,
I'm going back to php and javasvript after a long time, and I used jqGrid pluging to create the grids. What I used well, to edit high and modify without problem. I can find the problem when I want to use a table with related data.
The table is the fees of some affiliates, which are related to the affiliates themselves. To edit use the jqgrid form. I tried to put a select, so they choose the affiliate, but I do not load the data.
I have given it many laps and I do not know what could be happening to me. To say that I am a little rusty. Sorry if there are very fat failures.
I put my code.
Index.html:
<script type="text/javascript">
$(document).ready(function(){
jQuery("#tblCuotas").jqGrid({
url:'cargaCuotas.php',
editurl: "editCuotas.php",
datatype: 'json',
mtype: 'POST',
colModel:[
{
label: 'ID Cuota',
name: 'idCuota',
index:'idCuota',
width: 50,
key: true,
editable: true,
hidden: true
},
{
label: 'Num. Cuota',
name: 'NumD',
index:'NumD',
width: 50,
editable: true,
editoptions : { required: true, placeholder: "Número de Cuota requieredo"}
},
{
label: 'Num. Afiliado',
name: 'NumAfiliado',
index:'NumAfiliado',
width: 150,
editable: true,
edittype: 'select',
formatter:'select',
editoptions : { dataurl: 'afiliadosSelect.php' },
editrules : { required: true, placeholder: "Número de Cuota Afiliado"}
},
{
label: 'Nombre',
name: 'NOMBRE',
index:'NOMBRE',
width: 300,
editable: true
},
{
label: 'Cuota',
name: 'CUOTA',
index:'CUOTA',
width: 150,
editable: true,
editoptions : { required: true, placeholder: "Importe de la cuota requieredo"}
},
{
label: 'Mes',
name: 'MES',
index:'MES',
width: 120,
editable: true,
editoptions : { }
},
{
label: 'Año',
name: 'ANNO',
index:'ANNO',
width: 50,
editable: true,
editoptions : { }
},
{
label: 'Pago',
name: 'PAGO',
index:'PAGO',
width: 50,
editable: true,
edittype: 'select',
editoptions : { value: "Y:SI;N:NO" }
},
{
label: 'Forma Pago',
name: 'FormaPago',
index:'FormaPago',
width: 100,
editable: true,
editoptions : { }
}
],
loadonce: false,
width: window.innerWidth-20,
height: window.innerHeight-150,
pager: '#paginacion',
rowNum: 50,
rowList:[50,100,150],
sortname: 'NumD',
sortorder: 'asc',
viewrecords: true,
caption: 'CUOTAS'
});
jQuery("#tblCuotas").jqGrid('navGrid','#paginacion',
{edit:true,add:true,del:true},
// options for the Edit Dialog
{
html5Check : true,
editCaption: "The Edit Dialog",
recreateForm: true,
checkOnUpdate : true,
checkOnSubmit : true,
closeAfterEdit: true,
reloadAfterEdit:true,
reloadAfterSubmit:true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
},
buttons : [
{
side : "right",
text : "Afiliado",
position : "first",
click : function( form, params, event) {
alert("Custom action in search form");
}
}
]
},
// options for the Add Dialog
{
closeAfterAdd: true,
html5Check : true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
});
</script>
afiliadosSelect.php:
<?php
include "../class/tAfiliados.php";
echo '<script>alert("Custom action in search form");</script>';
$oAfiliado = new tAfiliados(1, 0, 1, 1);
$respuesta = $oAfiliado->selectAfiliados();
echo $respuesta;
?>
tAfiliados.php:
<?php
include 'tMySQL.php';
class tAfiliados
{
public function selectAfiliados()
{
$oMySQL = new tMySQL();
if ($oMySQL->bConnect)
{
$cSQL ="SELECT COUNT(*) AS cuantos FROM afiliados WHERE borrado=0";
$this->fila = $oMySQL->countQuery($cSQL);
$this->cuantos = $this->fila['cuantos'];
$query = "SELECT idAfiliado, NumAfiliado, NOMBRE FROM afiliados WHERE borrado=0 ORDER BY NOMBRE";
$result = $oMySQL->GetQuery($query);
$response ='<select>';
$i=0;
while( $i <= $this->cuantos ) {
$response .= '<option value="'.$result[$i]['NumAfiliado'].'">'.$result[$i]['NOMBRE'].'</option>';
$i++;
}
$response .= '</select>';
}
$oMySQL->Close();
return $response;
}
}
?>
Greetings and many thanks.

Please remove this line from your code:
echo '<script>alert("Custom action in search form");</script>';
This causes problem to load the data. The data should contain only html data and nothing more.
This echo causes the data to fail to load into the grid.
UPDATE:
Sorry, Just now I jhave look at your code. The JavaScript is case sensitive.
Please replace
editoptions : { dataurl: 'afiliadosSelect.php' },
With
editoptions : { dataUrl: 'afiliadosSelect.php' },
UPDATE2
I have prepared a demo with your settings and it works fine. Here is the link. Please check if your path to afiliadosSelect.php is correct in the related toy your file where the grid is. In this case you should get in console a error.

Related

jqGrid set dataURL Dynamically after Edit Form Loads

I am using jqGrid 4.15.6-pre - free jqGrid:
I have two dropdown list in my edit form.
Both are populated from server using the setColProp in the onSelectRRow function.
What I want to do reload the second dropdown list if the value in the first dropdown is changed.
I need to do this without having to close the edit form.
The example below uses the Guriddo jqGrid. You maybe can adapt it to the forked version - free-jqgrid.
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'data.json',
editurl: 'clientArray',
datatype: "json",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 75,
key: true
},
{
label: 'Company Name',
name: 'CompanyName',
width: 140,
editable: true // must set editable to true if you want to make the field editable
},
{
label : 'Phone',
name: 'Phone',
width: 100,
editable: true
},
{
label: 'Postal Code',
name: 'PostalCode',
width: 80,
editable: true
},
{
name: 'Country',
width: 200,
editable: true,
edittype: "select",
editoptions: {
value: "USA:USA;UK:UK;Canada:Canada"
}
},
{
name: 'City',
width: 200,
editable: true,
edittype: "select",
editoptions: {
value: "Select a City"
}
}
],
loadonce: true,
viewrecorde: true,
width: 780,
height: 200,
rowNum: 10,
pager: "#jqGridPager"
});
$('#jqGrid').navGrid('#jqGridPager',
// the buttons to appear on the toolbar of the grid
{ edit: true, add: false, del: false, search: false, refresh: false, view: false, position: "left", cloneToTop: false },
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
recreateForm: true,
closeAfterEdit: true,
viewPagerButtons: false,
afterShowForm: populateCities,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
// This function gets called whenever an edit dialog is opened
function populateCities() {
// first of all update the city based on the country
updateCityCallBack($("#Country").val(), true);
// then hook the change event of the country dropdown so that it updates cities all the time
$("#Country").bind("change", function (e) {
updateCityCallBack($("#Country").val(), false);
});
}
function updateCityCallBack(country, setselected) {
var current = $("#jqGrid").jqGrid('getRowData',$("#jqGrid")[0].p.selrow).City;
$("#City")
.html("<option value=''>Loading cities...</option>")
.attr("disabled", "disabled");
$.ajax({
url: country+".html",
type: "GET",
success: function (citiesHtml) {
$("#City")
.removeAttr("disabled")
.html(citiesHtml);
if(setselected) {
$("#City").val( current );
}
}
});
}
});
Real-time example is here

create button add delete edit jqgrid

I have created a jqgrid, and I was successful in creating add,delete,edit function by enabling these functions which belong to the jqgrid library. I want to create button add,delete,edit functions outside the table and here is my code:
<table id="list47"></table>
<div id="plist47"></div>
<script>
var mydata = JSON.parse('#DATA_QUERIED'),
editSettings = {
checkOnUpdate: true,
reloadAfterSubmit: false,
closeOnEscape: true,
savekey: [true, 13],
closeAfterEdit: true
},
addSettings = {
checkOnUpdate: true,
reloadAfterSubmit: false,
savekey: [true, 13],
closeOnEscape: true,
closeAfterAdd: true
},
delSettings = {
onclickSubmit: function () {
var $this = $(this), p = $this.jqGrid("getGridParam"), newPage = p.page;
if (p.lastpage > 1) {// on the multipage grid reload the grid
if (p.reccount === 1 && newPage === p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
setTimeout(function () {
$this.trigger("reloadGrid", [{ page: newPage }]);
}, 50);
}
return true;
}
},
removeTheOptionAll = function (elem) {
// We use "value" in the searchoption property of some columns of the colModel.
// The option {"": "All"} neams "No filter" and should be displayed only
// in the searching toolbar and not in the searching dialog.
// So we use dataInit:removeTheOptionAll inside of searchoptions to remove
// the option {"": "All"} in case of the searching dialog
if (elem != null && typeof elem.id === "string" && elem.id.substr(0, 3) !== "gs_") {
// we are NOT in the searching bar
$(elem).find("option[value=\"\"]").remove(); // remove "All" option
}
};
$(document).ready(function () {
jQuery("#list47").jqGrid({
data: mydata,
datatype: "local",
autowidth: true,
height: 'auto',
rowNum: 15,
rowList: [5, 10, 20],
colNames: ['USER_ID', 'USER_NAME', 'LOGIN_NAME', 'PASSWORD', 'DESCRIPTION', 'GROUP_ID', 'EMAIL', 'ACTIVE', 'ORGANIZATION_ID'],
colModel: [
{ name: 'USER_ID', index: 'USER_ID', width: 100, },
{ name: 'USER_NAME', index: 'USER_NAME', width: 140,edittype: "textarea" },
{ name: 'LOGIN_NAME', index: 'LOGIN_NAME', width: 140,edittype: "textarea" },
{ name: 'PASSWORD', index: 'PASSWORD', width: 140,edittype: "textarea" },
{ name: 'DESCRIPTION', index: 'DESCRIPTION', width: 140,edittype: "textarea" },
{ name: 'GROUP_ID', index: 'GROUP_ID', width: 140,edittype: "textarea" },
{ name: 'EMAIL', index: 'EMAIL', width: 200,edittype: "textarea" },
{ name: 'ACTIVE', index: 'ACTIVE', width: 70, sorttype: "float",formatter: "number", editable: true },
{ name: 'ORGANIZATION_ID', index: 'RGANIZATION_IDz', width: 140, sorttype: "float",formatter: "number", editable: true }
],
cmTemplate: {editable: true, searchoptions: {clearSearch: false }},
pager: "#plist47",
viewrecords: true,
sortname: 'USER_ID',
gridview: true,
grouping: true,
rownumbers: true,
autoencode: true,
viewrecords: true,
ignoreCase: true,
caption: "Đây là ví dụ mẫu về Grid",
ondblClickRow: function (rowid) {
var $this = $(this), selRowId = $this.jqGrid("getGridParam", "selrow");
if (selRowId !== rowid) {
// prevent the row from be unselected on double-click
// the implementation is for "multiselect:false" which we use,
// but one can easy modify the code for "multiselect:true"
$this.jqGrid("setSelection", rowid);
}
$this.jqGrid("editGridRow", rowid, editSettings);
}
}).jqGrid("navGrid", "#plist47", {}, editSettings, addSettings, delSettings, {
multipleSearch: true,
overlay: false,
onClose: function () {
// if we close the search dialog during the datapicker are opened
// the datepicker will stay opened. To fix this we have to hide
// the div used by datepicker
$("div#ui-datepicker-div.ui-datepicker").hide();
}
}).jqGrid("filterToolbar", { defaultSearch: "cn" });
});
</script>
here is the picture of that code: picture 1
So I have add del edit at the bottom of the jqgrid, now I want to create a button outside jqgrid like:
picture 2
You can do this using the methods for insert, update delete. For update or delete you will need to get the selected id and call the method. By example the code for edit a row can look like this.
$("#button_edit").click( function() {
var selcted_row = $("#grid").jqGrid('getGridParam', 'selrow');
if(selected_row) {
$("#grid").jqGrid("editGridRow",selected_row, editSettings);
} else {
alert("please select row");
}
});
Do similar to delete and adding a row. Look at the documentation for the methods.

jqgrid : Inline checkbox editing in Client Side

I am using jqgrid. I want to allow people to use a checkbox in inline editing. There will not be any buttons like edit etc, As soon as he clicks the checkbox, it should be considered as committed on client side.
There is a checkbox which I want to always keep in edit mode. After user is done making changes, he will click on a submit button & full grid data will get posted to the server.
I expect that getGridParam method should give me the updated cell values. However it is not doing so.
I feel my problem is the onSelectRow method. somewhere I am missing the implementation to save the current row state. & hence in the getGridParam method. I am getting the original values.
Code :
var lastsel;
jQuery("#AcOpenDataGrid").jqGrid({
url: '/Admin/Role/GetMappedMenus',
viewrecords: true, sortname: 'Code', sortorder: "desc",
colNames: [
"Code",
"MenuName",
"Allow"
],
colModel: [
{ name: 'Code', width: 10, key: true, align: 'center', hidden: true },
{ name: 'MenuName', index: 'MenuName', width: 60, search: true, searchoptions: JQ_sopt_string, align: 'left' },
{ name: 'Allow', index: 'Allow', width: 30, editable: true,edittype:'checkbox',editoptions: { value:"True:False" },formatter:'checkbox', formatoptions: {disabled : false} ,search: true, searchoptions: JQ_sopt_string, align: 'center' },
],
height: '500',
autowidth: true,
rowList: JQ_Paging_Opt,
rowNum: JQ_RowNum_Opt,
pager: pager_selector,
datatype: 'json', mtype: 'GET',
cmTemplate: { title: false },
loadonce:true,
altRows: true,
jsonReader: { root: "rows", page: "page", total: "total", records: "records", repeatitems: false, userdata: "userdata", id: "Code" },
editurl: 'clientArray',
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery(grid_selector).jqGrid('restoreRow', lastsel);
//jQuery(grid_selector).jqGrid('saveRow', lastsel);
jQuery(grid_selector).jqGrid('editRow', id, true);
lastsel = id;
}
},
}).navGrid(pager_selector, { view: false, del: false, add: false, edit: false, search: false, refresh: true }
).jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: 'cn' });
});
$(".submit").click(function () {
var localGridData = $("#AcOpenDataGrid").jqGrid('getGridParam', 'data');
//To Do : Post Ajax here.
});
I found a solution here. Not exactly what I expected but it does serves my purpose.
Make a column be a checkbox
beforeSelectRow: function (rowid, e) {
var $self = $(this),
iCol = $.jgrid.getCellIndex($(e.target).closest("td")[0]),
cm = $self.jqGrid("getGridParam", "colModel"),
localData = $self.jqGrid("getLocalRow", rowid);
if (cm[iCol].name === "closed") {
localData.closed = $(e.target).is(":checked");
}
return true; // allow selection
},

jqgrid cascading dropdown lists in pop up edit mode

I have two drop down lists, the first one gets populated from the database values and the second one(PriceCode) depends on what the user selects in the first one(CurrCd). My question is how do I populate that second list dynamically? I am trying to do it in dataEvents but have no way of referencing the second drop down list in edit mode. Is there a correct and logical way of doing so?
Here is my code so far:
grid.jqGrid({
datatype: 'local',
jsonReader: als.common.jqgrid.jsonReader('EntityCd'),
mtype: 'POST',
pager: '#billingPager',
loadonce: true,
colNames: ['Currency', 'Status', 'Bill Curr', 'Price Code'],
colModel: [
{
{ name: 'DefaultCurr', index: 'DefaultCurr', width: 20, sortable: false },
{ name: 'BillStatus', index: 'BillStatus', width: 13, sortable: false },
{
name: 'CurrCd', index: 'CurrCd', width: 20, sortable: false,
editable: true,
edittype: 'select', stype: 'select',
editoptions: {
dataUrl: als.common.getServerPath() + 'LegalEntitiesAjax/GetCurrencies',
dataEvents:[{
type:"change",
fn: function (e) {
//populate price code list here
//below does not work to populate PriceCode
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json; charset=utf-8',
url: als.common.getServerPath() + 'LegalEntitiesAjax/GetPriceList',
data: JSON.stringify({ curcd: this.value }),
async: false,
success: function (data) {
for(i=0; i < data.length; i++) {
$('select#PriceCode').append('<option val=\"' + data[i].PriceCode + '">' + data[i].Description + '</option>');
}
},
error: function (val) { }
});
}
}],
buildSelect: function (data) {
var currSelector = $("<select id='selCurr' />");
$(currSelector).append($("<option/>").val('').text('---Select Currency---'));
var currs = JSON.parse(data);
$.each(currs, function () {
var text = this.CurName;
var value = this.CurCode;
$(currSelector).append($("<option />").val(value).text(text));
});
return currSelector;
}
}
},
{ name: 'PriceCode', index: 'PriceCode', width: 20, sortable: false, editable: true, edittype: 'select', stype: 'select'}
],
loadtext: 'Loading...',
caption: "Bill Entities",
scroll: true,
hidegrid: false,
height: 300,
width: 650,
rowNum: 1000,
altRows: true,
altclass: 'gridAltRowClass',
onSelectRow: webview.legalentities.billing.onBillingSelected,
loadComplete: function (data) {
if (data.length > 0)
{
}
var rowIds = $('#billingGrid').jqGrid('getDataIDs');
$("#billingGrid").jqGrid('setSelection', rowIds[0]);
},
rowNum: 1000
});
grid.jqGrid('navGrid', '#billingPager', {
add: ($("#dev").text() == "True" || $("#globalqc").text() == "True"),
edit: false,
del: false,
search: false,
refresh: false
},
{ // Edit Options
},
{ // Add Options
addCaption: 'Add New Billing Entity',
beforeInitData: function (formid) {
},
url: als.common.getServerPath() + 'LegalEntitiesAjax/AddBillingEntity/',
recreateForm: true,
closeAfterAdd: true,
reloadAfterSubmit: true
},
{ // Del Options
});
The old answer shows how one can implement the dependent selects. You use form editing. Thus the <select> element of PriceCode column of the form editing will have the id="PriceCode". You can use $("#PriceCode").html(/*new options*/); to change the options of <select> editing field of PriceCode column inside of change event handler of CurrCd column.

export jqgrid data into excel on checkbox selection

I have bind the jqGrid from MVC controller , below is my jqgrid code . I want to export selected checkbox row data to csv , i have gone through all code's but every one providing sample local data, but i am binding from server to jqGrid,so when i select the checkbox rows in jqGrid and click on "Export " button the entire row should export to csv, can anybody have the solution ?
$('#jQGrid').jqGrid({
search: true,
multiboxonly: true,
colNames: ["PayloadCorrelationId", "Export", "Asset", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
colModel: [
{ name: 'CorrelationId', jsonmap: 'CorrelationId', hidden: true, width: 2 },
{ name: "", editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "1:0" }, formatoptions: { disabled: false } },
{ name: 'Device', jsonmap: 'Device', width: 60 }, { name: 'DateReported', jsonmap: 'DateReported', width: 100 },
{ name: 'ErrorType', jsonmap: 'ErrorType', width: 85 },
{ name: 'Error', jsonmap: 'Error', width: 140 },
{ name: 'Latitude', jsonmap: 'Latitude', width: 80 }, { name: 'Longitude', jsonmap: 'Longitude', width: 80 },
{ name: 'Payloadurl', jsonmap: 'Payloadurl', width: 180, formatter: 'link' }],
cellEdit: true,
pager: jQuery('#divpager'),
rowList: [5, 20, 50, 100],
rowNum:5,
sortorder: "desc",
datatype: 'json',
width: 900,
height: 'auto',
viewrecords: true,
mtype: 'GET',
gridview: true,
loadonce: true,
url: '/DataIn/DataInSearchResult/',
emptyrecords: "No records to display",
onSelectRow: true,
onSelectRow: function (id, status) {
var rowData = jQuery(this).getRowData(id);
configid = rowData['CorrelationId'];
alert(configid);
// Add this
var ch = jQuery(this).find('#' + id + ' input[type=checkbox]').prop('checked');
if (ch) {
jQuery(this).find('#' + id + ' input[type=checkbox]').prop('checked', false);
} else {
jQuery(this).find('#' + id + ' input[type=checkbox]').prop('checked', true);
}
// end Add
rowChecked = 1;
currentrow = id;
},
loadComplete: function () {
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
} else {
$(this).show();
$("#lblTotal").html($(this).getGridParam("records") + " Results");
}
}
});
Just to clarify, There must be any buttons on clicking which the csv will generate from the selected check box. If it is so then loop through the grid data to filter out checked rows. You can loop through the grid data easily on firing the button event. Based on the resultant data create the csv.

Categories