Jqgrid Pass select rows column values to dataurl - php

I'm trying to pass column values to php load the select item on the edit form based on the column values.
dataUrl:'includes/Opera_classif.php?Op=local&id=' +ID +Description +id_local
JS
mtype: 'GET',
colNames: [ "ID","Descrição","ID Local", "Local","Select Local"],
colModel: [
{name:'ID',index:'ID', width:20, sorttype:"int"},
{name:'Description',index:'Description', width:150, editable: true,editrules:{required:true}},
{name:'id_local',index:'id_local',hidden:true, width:20, editable: true,editrules:{required:true}},
{name:'Local_Description',index:'Local_Description', width:100, editable: true,editrules:{required:true}},
{
name:'escolhe_local',index:'escolhe_local', width:80,resizable:true, hidden:true, editrules:{edithidden: true },
align:"left",sorttype:"text",editable:true,edittype:"select",
editoptions:{dataUrl:'includes/Opera_classif.php?Op=local'}
}

One can use dataUrl defined as function (see here and here). The function dataUrl get 3 parameter (the first is the rowid, the second is the value from the current column - Local_Description in your case) and this will be initialized to DOM of the grid (so you can use $(this).jqGrid("getRowData", rowid) or $(this).jqGrid("getCell", rowid, "Description") for example). In the way you can generate any dataUrl value which you need.

Related

PHP multi-select filter with Ajax post request with DataTables

I'm trying to convert an existing "select" dropdown filter on a table generated via the DataTables library to be able to handle multiple options, and though I think I have it correct on the front-end Javascript, I'm having trouble figuring out how to handle it in the back-end PHP.
The below is from the script in the front-end view, which makes the Ajax Post request:
<script>
function generateTable() {
var oTable = $('#MyData').dataTable({
"aaSorting": [
[1, "desc"]
],
"aLengthMenu": [
[10, 25, 50, 100, 200],
[10, 25, 50, 100, 200]
],
"iDisplayLength": <?= $Settings->rows_per_page ?>,
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': '/my/getData/path',
'fnServerData': function(sSource, aoData, fnCallback) {
// ...SNIP...
aoData.push({
"name": "some_status",
"value": $("#some_status").val()
});
$.ajax({
'dataType': 'json',
'type': 'POST',
'url': sSource,
'data': aoData,
'success': fnCallback
});
},
"aoColumns": [],
}).fnSetFilteringDelay().dtFilter([
// ...SNIP...
{
column_number: 4,
filter_default_label: "[<?= lang('some_status'); ?>]",
filter_type: "multi_select",
data: []
},
// ...SNIP...
], "footer");
}
</script>
I can confirm that the selected values are added to an array by console logging the $("#some_status").val(). So my assumption was that it would be passed to the backend as an array as well, but apparently not.
What actually happens is the first selection goes fine, but any subsequent selection clears the table, and only works if there's a single value selected, leaving me to believe that only the first selection is pushed to the aoData array.
In PHP I have:
$this->load->library('datatables');
$this->datatables
->select("id, date, reference_no, supplier, some_status")
->from('purchases');
$some_status = $this->input->post('some_status');
if ($some_status != '') {
$this->datatables->where('status', $some_status);
}
How do I handle the some_status value if it's an array, or how do I make sure it even is an array after it was pushed toaoData?
Any help will be appreciated!
EDIT:
To clarify, by console logging the result like below returns the correct selection as I add and remove selections from the multi-select dropdown:
console.log($("#some_status").val());
If I select "Top option" from the dropdown, I get:
[
"top_option"
]
When I then select "Another option" as well, I get:
[
"top_option", "another_option"
]
So the JS side is handling the multi-select, but I don't know if the below is correct, as it works only with a single select, nothing more:
$some_status = $this->input->post('some_status');
if ($some_status != '') {
$this->datatables->where('status', $some_status);
}

can't add data to jqGrid from php within json format

Hello StackOverFlow nation . I'm trying to add information to jqGrid , which is retrieved from MySQL database. I've two files => index.html and data.php (both in the same directory)
index.html source =>
<script type="text/javascript">
$(function(){
$("#jqGrid_tb").jqGrid({
url: "data.php",
datatype: "json",
sortable: true,
height: "auto",
colNames: ["Name","Surname","Birth Year","Famous Film"],
colModel: [
{name: "name", index: "name", width: "150"},
{name: "surname", index: "surname", width: "150"},
{name: "b_year", index: "year", width: "150"},
{name: "film", index: "film", width: "200"}
],
rowNum: 5,
rowList: [5,10,15],
viewrecords: true,
pager: $("#pager"),
caption: "Famous Actors",
}).navGrid("#pager");
});
</script>
<div id="grid">
<table id="jqGrid_tb"></table>
<div id="pager"></div>
</div>
data.php source =>
include ("JSON.php");
$json = new Services_JSON();
$con = new mysqli("host","user","pswd","db");
if (!$con->connect_errno){
if ($r = $con->query("SELECT * FROM actors")){
while ($row = $r->fetch_assoc()){
$info[] = array(
"name" => $row[name],
"surname" => $row[surname],
"b_year" => $row[b_year],
"film" => $row[film],
);
}
$r->free();
}
}
echo $json->encode($info);
if (isset($con)){
$con->close();
}
jqGrid is shown without any information in index.html file , also when opening data.php file information is successfully encoded into JSON format , whats wrong I can't understand . Please help , thanks ...
Your response format is wrong. You can go to jqGrid Demos page where you will find a sample for PHP/MySQL after expanding Loading Data and then choosing JSON Data.
The proper format of data should look like this:
{
"total": "1",
"page": "1",
"records": "2",
"rows": [
{ "name": "Robert", "surname": "De Niro", "b_year": "1943", "film": "Once Upon A Time In America" },
{ "name": "Al", "surname": "Pacino", "b_year":"1971", "film": "Scent Of A Woman"}
]
}
Where:
total --> total count of pages
page --> current page number
records --> total count of records
rows --> the rows of data
Also if you want rows to be objects, you need to disable repeatitems in jqGrid jsonReader options:
$("#jqGrid_tb").jqGrid({
...
jsonReader: { repeatitems: false }
});
It is also adviced for rows to have unique id for later reference.
You should include
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
}
as additional option of jqGrid is you don't want to change format of input data. Moreover you should specify which values should assign jqGrid as id attribute of the row. You can include additional id property as additional property of every returned item or you can add key: true property to the column (in colModel) which contains unique values. For example if you can guarantied that the values from "name" are already unique then you can include key: true property in definition of "name" column.
Additionally you can consider to use loadonce: true option of jqGrid. In the case the full data of the grid will be loaded at once and the sorting, paging and searching (filtering) of data will be implemented by jqGrid on the client side without needs to implement some additional code on the server side. You should don't use the option in case of large number of rows (many hundred or many thousand rows) in the grid.

passing string in "textfield" to another part in code

I have one question about passing strings from one Ext.formPanel textfield to another part of the code. The thing is that I have two "textfield" in the formPanel and I want the words I enter there as part of the "url" I have in the code. Probably you may ask, why does this guy want that?? this is because the "url" I'm using has a PHP script that generates features stored in a postgis db table as GeoJSON.
This the code:
[CODE]
// define the data source
var protocol = new OpenLayers.Protocol.HTTP({
url: "http://localhost/postgis_geojson.php?geotable=boreholes_point_wgs84&geomfield=geom&parameters=" + "column" + ilike '%"string"%',
format: new OpenLayers.Format.GeoJSON({
ignoreExtraDims: true,
'internalProjection': new OpenLayers.Projection("EPSG:900913"),
'externalProjection': new OpenLayers.Projection("EPSG:4326")
})
});
formPanel = new GeoExt.form.FormPanel({
title: "Place Name Search",
height: 150,
region: "north",
protocol: protocol,
items: [{
xtype: "textfield",
id: "column",
emptyText: "Choose table column",
fieldLabel: "Choose table column",
width: 200,
allowBlank: false
}, {
xtype: "textfield",
id: "string",
emptyText: "Search inside table",
fieldLabel: "Enter a word to search",
width: 200,
allowBlank: false
}],
listeners: {
actioncomplete: function(form, action) {
features = action.response.features;
store.loadData(features);
vm=map.getLayersByName("Results");
if(vm.length===0){
vecLayer = new OpenLayers.Layer.Vector("Results");
map.addLayer(vecLayer);
store.bind(vecLayer);
select.bind(vecLayer);
}
}
},
buttons: [{text: 'search',
handler: function(){
formPanel.search();
}
}],
keys: [{ key: [Ext.EventObject.ENTER],
handler: function() {
formPanel.search();
}
}]
});
[/CODE]
These are the cases I already tested:
url: http://localhost/postgis_geojson.php?geotable=boreholes_point_wgs84&geomfield=geom: this generates the whole table "boreholes_point_wgs84" as GeoJSON.
url: http://localhost/postgis_geojson.php?geotable=boreholes_point_wgs84&geomfield=geom&parameters=station ilike '%llena%': this generates only one feature, the feature that has "llena" in the "station" column. So, in this way I can find the feature through the search form.
What I was thinking is if I can pass these two strings I enter in "textfield" and modify the "url" in the way that it can catch these two words and form, for example, the second case I put above. I was playing with this:
url: http://localhost/postgis_geojson.php?geotable=boreholes_point_wgs84&geomfield=geom&parameters=" + "column" + ilike '%"string"%', so using the "id" I specified below each xtype, but it doesn't work.
I appreciate any support on this, thanks in advance,
Best regards,
Gery
The correct way to this is a simple form submission. The text input values will be sent to the server in a form post. Server side should parse the submitted values and do what's necessary. This isn't any different from the use of plain HTML and any server side frameworks.
Alternatively you can force your form to submit using HTTP GET method instead of POST and then your input values will be part of your URL. In ExtJS you use 'method' config. See API docs: http://docs.sencha.com/ext-js/4-1/#!/api/Ext.form.Basic-cfg-method
EDIT: if you are not at all interested in actually 'submitting' the form you can get your field values like this: form.findField('myField').value
I'm pretty sure that this solution will help to understand how to solve this problem, I solved myself.

JqGrid Edit form doesn't display proper item in dropdown

I have a grid populated by a database. One of the columns is a concat of 2 columns in another table. In this case it is a team's location and name. However, when I click on edit and the edit form gets populated, it always picks the first team in the dropdown as opposed to the actual team in the database.
Here is some of the relevant code:
jQuery("#listPlayer").jqGrid({
url:'../controller/playerGrid.php',
datatype: "json",
colNames:['ID','First Name','Last Name', 'Team'],
colModel:[
{name:'id', index:'id', width:20, editable:false, hidden:true},
{name:'first_name', index:'first_name', width:80, editable:true, editrules: {required: true}},
{name:'last_name', index:'last_name', width:80, editable:true, editrules: {required: true}},
{name:'idTeam', index:'idTeam', width:50, editable:true, editrules: {required: true}, edittype: 'select', editoptions: { dataUrl: "../controller/listTable.php?query=team" } }
],
rowNum:50,
rowTotal: 2000,
rowList : [20,30,50],
mtype: "POST",
rownumbers: true,
rownumWidth: 40,
gridview: true,
pager: '#pagerPlayer',
sortname: 'last_name',
viewrecords: true,
sortorder: "asc",
caption: "Player Manager",
editurl: "../controller/playerEditGrid.php"
And this is what the SQL query in listTable.php looks like:
SELECT t.id, CONCAT(t.location, ' ', t.name,' (', l.abbr, ')' ) as idTeam FROM team t, league l WHERE t.idLeague = l.id ORDER BY t.location
I know the problem lies in the fact that it's a concatenation as opposed to a single column but I'm sure there's a way around it... I just don't know it.
I haven't used it this way but the following part of jqgrid help should be applicable for your case: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules#select
The return from your dataurl should already be a valid HTML select element like:
<select>
<option value='1'>One</option>
<option value='2'>Two</option>
...
</select>
refer 3. Setting the editoptions dataUrl parameter in the above url.
hope this helps!

DataTables, Ajax Pipelining

I'm using DataTables with pipelining. I works great except when I tried to enter an extra column to hold "edit" links. See this table.
Here is a snippet of server_processing.php showing the columns:
/* Array of database columns which should be read and sent back to DataTables.
* Use a space where you want to insert a
* non-database field (for example a counter or static image)
*/
$aColumns = array( 'user','email', );
And here is the clientside:
$(document).ready( function (){
$('#example').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/server_processing.php",
"fnServerData": fnDataTablesPipeline,
aoColumns: [null, null, {"bSortable": false}]
}).makeEditable({
sUpdateURL: "UpdateData.php",
sAddURL: "AddData.php",
sAddHttpMethod: "POST",
sDeleteURL: "DeleteData.php",
sDeleteHttpMethod: "POST",
aoColumns: [ { } , { } , null ]
});
});
So, why isn't this working?
Just done this exact same thing myself. I like to configure all my columns using aoColumnDefs, as you can add multiple configuration options for columns in one go.
// Disable sorting on the 3rd column
'aoColumnDefs': [{'aTargets': [2], 'bSortable': false}]
Note that aTargets is an array of column indexes you want to apply those settings to. So if you were to add more link columns (e.g. a Delete link), you can turn off sorting on those without rewriting the column definition every time.
// Disable sorting on the 3rd and 4th column
'aoColumnDefs': [{'aTargets': [2,3], 'bSortable': false}]
And, as I was saying, you can add further configuration options for columns in this same array:
// Disable sorting on the 3rd and 4th column and sort 1st column by string
'aoColumnDefs': [
{'aTargets': [2,3], 'bSortable': false}
{'aTargets': [0], 'sType': 'string'}
]

Categories