I'm originally a .NET dev by heart so I've always been use to having ADO.net and LINQ for strongly typed, easy data access into gridviews and other .net controls. In trying to learn PHP and MySQL with CodeIgniter and a dash of jQuery, but I'm having a hard time visualizing my data access methods.
I want to use a PHP or jquery grid for my grid controls (which I rely heavily on). What is the best way to populate them from a MySQL environment? I've heard lots about using JSON but I haven't studied anything on it yet. I'm also pretty sure CodeIgniter does a lot of data access as well.
What direction do I need to be taking this? Thank you Stackoverflow!
Let's get started with this:
Plain PHP
<?php
class Report{
….
public function __construct($city, $sidx, $sord, $_search, $searchField, $searchString, $searchOper){
//connecting to db, stm, execute query, fetch array from result …..
echo json_encode(array("name"=>"Alissa", "phone" => "555-55551", "city" => "Sussex");
//or
echo json_encode($result);
//where result is an associative array, codeigniter can map such objects from ORM results
}
}
$report = new Report($_GET['city'], $_GET['sidx'], $_GET['sord'], $_GET['_search'],$_GET['searchField'],$_GET['searchString'],$_GET['searchOper'])
?>
jQuery/html side using jqGrid
$("#grid").jqGrid({
url: 'report.php?city=' + c + '&searchString=null&searchField=null&searchOper=null',
datatype: 'json',
mtype: 'GET',
colNames: ['Name', 'Phone', 'City'],
colModel: [
{ name:'rows.name', index: 'name', search:true, jsonmap: 'name', width: 30, align: 'left', sortable:true},
{ phone:'rows.phone', index: 'phone', jsonmap: 'phone', width: 50, align: 'left'},
{ name:'rows.city', index: 'city', jsonmap: 'city', width: 50, align: 'left', sortable: true},
pager: '#pager',
rowNum: 8,
autowidth: true,
rowList: [8, 16,32,48],
sortname: 'name',
sortorder: 'asc',
viewrecords: false,
caption: 'Customer',
jsonReader : {
root: "rows",
repeatitems: false
},
height: 650,
width: 800
});
No matter what PHP Framework you use, believe me. I use QCubed, sometimes I write plain PDO classes for this.
You can check this:
http://www.codeigniter-jquery.com/codeigniter/using-json-in-codeigniter-with-jquery/
echo json_encode($result);
I'm not so sure what exactly were you asking, but this might be helpful:
Datamapper
it makes query easy, built on top of codeigniter's Active Records
Related
I am building a small application. I have a PHP code which inside has a creation of jqGrid and also I have a servlet which sends a string of an array with JSONs inside.
The string looks like this:
[
{"id":1,"firstName":"Amishay","lastName":"Vaturi"},
{"id":2,"firstName":"Amir","lastName":"Bilu"},
{"id":3,"firstName":"Michael","lastName":"Keidar"},
{"id":4,"firstName":"Mika","lastName":"Spivak"},
{"id":5,"firstName":"Ksenia","lastName":"Mosorov"},
{"id":6,"firstName":"Rose","lastName":"Wahlem"}
]
The problem is I don't see it in the grid I made...
the grid code is this :
$("#jqGrid").jqGrid({
url: 'http://10.0.0.4:8080/api/students/all',
mtype: "GET",
datatype: "jsonstring",
colModel: [
{ label: 'ID', name: 'id', key: true, width: 75 , height: 50 },
{ label: 'First Name', name: 'firstName', width: 150 , height: 50},
{ label: 'Last Name', name: 'lastName', width: 150 , height: 50}
],
viewrecords: true,
width: 780,
height: 250,
rowNum: 20,
pager: "#jqGridPager"
});
I looked here and in the entire net to search for an answer.
I saw I might need to send a different json from the server. perhaps with more info such as records,number of page etc. I also saw I might need to declare a json reader in the jqGrid properties.
I did both.. still didn't work. It's like I didn't find a solution which meets my problem in a 100%.
I will be very happy to get an answer which works (:
Thanks a lot!
The error in your code is the usage of datatype: "jsonstring" instead of
datatype: "json"
By the way you don't need to create hidden column id, because jqGrid assign the value of id property to id attribute of rows (<tr> elements). Additionally I would recommend you to use loadonce: true option, because the format of data which you use don't means server side paging.
I create the demo https://jsfiddle.net/OlegKi/oc7uuh9q/, which used your data to demonstrate that all should work. I just modified your code a little to use new features implemented in free jqGrid, the fork of jqGrid, which I develop.
I have a page containing a ExtJS 4.2.2 dataStore and gridPanel showing items created using information from various tables in a MySQL database.
The purpose of the generated grid is to provide a "confirmation" to the user before any information is actually generated in the database in a table separate to those that originated the initial information, as some items can be flagged to be imported; unflagged items are not imported. The page uses HTML, PHP (with CodeIgniter MVC framework) and ExtJS (which implies Javascript and JQuery).
With my current understanding of ExtJS, I would perform the necessary database insert or update by:
Saving all the changes in the grid to the store
Packaging the store's data into a multidimensional array, which is then assigned into a POST variable in some similar manner to a form
Perform a POST to the same page, picking up the POST variable
Loop through the POST information, passing each row's data to the model to perform the SQL query and INSERT/UPDATE as necessary.
I'm thinking this is a long-winded and most likely inefficient method for doing this; having previously worked with Kendo UI, I would have thought there is some form of "save" action on the store that simply calls a controller/model function that would act on the data in fewer steps.
Having looked at Ext.data.Store's numerous potential candidates (the commitChanges method, update event, the write event, store.sync etc.), I have to say I'm completely bewildered by how I could perform the kind of action I'm thinking of; I need to write the information to a table separate from those that generated the initial information, and none of the above seem to do that.
I would appreciate a "simple words" play-by-play of how to get the "dirty" data from the grid saved to the store, then the store data being passed to a MVC Controller-then-Model function that allows for update/insert to the DB (if that is the best way to do this) - I also appreciate that I will have to modify aspects of my ExtJS code, but what about my current setup isn't helping, if anything?
ExtJS code below renders the grid with data, and not much else:
Ext.Loader.setConfig({
enabled: true
});
Ext.Loader.setPath('Ext.ux', '../ux');
Ext.require([
'Ext.ux.CheckColumn'
]);
Ext.onReady(function(){
Ext.define('ConfirmationModel', {
extend: 'Ext.data.Model',
fields: [
'GroupName', // generated if not a member of a group, will eventually be retrieved if already existing in group by checking import table for JobNo, ItemNo and ItemTypeId
'ItemType',
'ItemTypeId',
'JobNo',
'ItemNo',
'ThicknessDepth',
'Cutter',
'CutterId',
'Source',
'Qty',
'Material',
'MaterialId',
'Type',
'TypeId',
'Work',
'WorkId',
'PaintInternal',
'PaintExternal',
'Notes',
'Documented',
'ImportDate', // fetched by checking import table for jobNo, itemNo and itemTypeId
'ImportCheck' // usually automatically checked if not yet imported
]
});
confirmationStore = Ext.create('Ext.data.Store',{
model: 'ConfirmationModel',
autoLoad: true,
proxy: {
// load using HTTP
type: 'ajax',
url: '<?= $site_url ?>Production/ConfirmationJSON/<?php echo $job_no ?>', // currently pulls all the information from three separate tables, pushes to object arrays then converts to and returns as JSON; will also check import table for existing entries as further work
pageParam: false, //to remove param "page"
startParam: false, //to remove param "start"
limitParam: false, //to remove param "limit"
noCache: false, //to remove param "_dc"
reader: {
type: 'json',
model: 'ConfirmationModel'
}
},
groupField: 'GroupName'
});
confirmationGrid = Ext.create('Ext.grid.Panel', {
width: 1200,
store: confirmationStore,
title: 'Import Confirmation',
tbar: [
{
xtype: 'button',
text: 'Update',
handler: function(){
// function to handle the save/update of information goes here?
document.location.href = '<?php echo site_url() ?>Production/Schedule'; // redirect to next page in steps
}
},
{
xtype: 'button',
text: 'Cancel',
handler: function(){
window.history.back();
}
}
],
columns: [
{ text: 'Item<br />No.', width:50, dataIndex: 'ItemNo' },
{ text: 'Job<br />No.', width: 65, dataIndex: 'JobNo' },
{ text: 'Item Type', width: 70, dataIndex: 'ItemType' },
{ text: 'Thickness<br />Depth', width: 65, dataIndex: 'ThicknessDepth' },
{ text: 'Cutter', width: 65, dataIndex: 'Cutter' },
{ text: 'Source', width: 65, dataIndex: 'Source' },
{ text: 'Qty', width: 40, dataIndex: 'Qty' },
{ text: 'Material', flex: 1, dataIndex: 'Material' },
{ text: 'Type', flex: 2, dataIndex: 'Type' },
{ text: 'Work', flex: 2, dataIndex: 'Work' },
{ text: 'Paint - Internal', flex: 2, dataIndex: 'PaintInternal' },
{ text: 'Paint - External', flex: 2, dataIndex: 'PaintExternal' },
{ text: 'Notes', flex: 2, dataIndex: 'Notes' },
{ text: 'Documented?', width: 75, dataIndex: 'Documented' },
{ text: 'Import<br />Date', width: 60, dataIndex: 'ImportDate' },
{
xtype: 'checkcolumn',
sortable: false,
header: 'Import?',
width: 50,
dataIndex:'ImportCheck'
}
],
features: [{
id: 'group',
ftype: 'groupingsummary',
groupHeaderTpl: '{name}',
enableGroupingMenu: false
}],
renderTo: Ext.get('sencha_confirmation')
});
});
There's no need to save data from the grid to the store, since the content you're seeing in the grid is there because it is already in the store (given that the store is the data provider for the grid).
To send the data in this format, you simply need to configure your proxy's writer's allowSingle: false. This will force the proxy to send through the records it is persisting as an array always, even if there is only one record.
Example:
proxy: {
writer: {
allowSingle: false
},
...
}
This can be accomplished by calling sync() on your store. Sync will automatically create a request to the url specified on your proxy, and will batch together new records, updated records, and deleted records. You can call this manually, or add autoSync: true to your store (I prefer controlling when it's called, but that's up to you).
Re: the MVC side of things, that's dependent on how your application is structured. For example, if you have a "save" button on the grid, you could bind to the button's click event, and in your controller listen for this click event and call your store's sync() method there. Of course, this is just an example: there are an number of events/conditions you could respond to and do the same thing.
I have list of links in one page which is dynamically created. I want to do when I click on one link another page will be open and according to link id which is i am sending the data will be fetch from database and load into a pagination ext data grid.
Bellow in my Javascript code
var extGrid = null;
var center_data_store=null;
var exam_id = null;
Ext.onReady(function(){
// create the data store
exam_id = document.getElementById("hdnExamId").value;
//I am getting id from one hidden field.
//alert(exam_id);// Id is coming.
multiple_choice_all_data_store = new Ext.data.JsonStore({
totalProperty: 'total', // total data, see json output
root: 'results', // see json output
url: 'multiple_choice_all_data_grid.php"?exm_id="+exam_id',
//in above url I am passing data.
fields: [
{name: 'OEXM_Id', type: 'int'},
'OEXM_txtareaQuestion','OEXM_rbtnOption','OEXM_txtOption1','OEXM_txtOption2','OEXM_txtOption3','OEXM_txtOption4','OEXM_txtExamId','OEXM_txtExamName'
]
});
// load data from the url ( data.php )
multiple_choice_all_data_store.load({params:{start: 0, limit: 15}});
// create the Grid
var multiplechoicealldataGrid = new Ext.grid.GridPanel({
store: multiple_choice_all_data_store,
columns: [
new Ext.grid.RowNumberer(),
//{header: 'ID', width: 30, sortable: true, dataIndex: 'OEXM_Id',hidden:false},
{header: 'Question', width: 300, sortable: true, dataIndex: 'OEXM_txtareaQuestion',hidden:false},
{header: 'Answer', width: 100, sortable: true, dataIndex: 'OEXM_rbtnOption',hidden:false},
{header: 'Option1', width: 100, sortable: true, dataIndex: 'OEXM_txtOption1',hidden:false},
{header: 'Option2', width: 100, sortable: true, dataIndex: 'OEXM_txtOption2',hidden:false},
{header: 'Option3', width: 100, sortable: true, dataIndex: 'OEXM_txtOption3',hidden:false},
{header: 'Option4', width: 100, sortable: true, dataIndex: 'OEXM_txtOption4',hidden:false}
],
stripeRows: true,
height:470,
width:792,
title:'All Multiple Choice Question Information',
bbar: new Ext.PagingToolbar({
pageSize: 15,
store: multiple_choice_all_data_store,
displayInfo: true,
displayMsg: 'Displaying Records {0} - {1} of {2}',
emptyMsg: "No topics to display"
})
});
My problem is I am not able to get ID value in my PHP Page.
Try change url in the store definition to 'multiple_choice_all_data_grid.php?exm_id='+exam_id
Then your id should be available in PHP in $_GET['exm_id'] variable
To get a element in ExtJS:
exam_id = Ext.getCmp("hdnExamId").getValue();
The getValue() method is used to retrieve the value of the element.
Edit:
Also fix the url #Lolo is pointing out.
I have a PHP script that extract valid GeoJSON data from a database. Now I would like to prepare a grid view of these data with jqgrid, but I can't figure out the proper jsonReader for the javascript code.
This is my GeoJSON output:
{"type":"FeatureCollection",
"total":0,
"page":1,
"records":117,
"features":[
{"geometry":{"type":"Point","coordinates":[12.3,41.70052]},
"type":"Feature",
"properties":{
"data":"2006-02-22",
"specie":"S. coeruleoalba",
"localita":"Ostia",
"provincia":"Roma"
},"id":0},
{"geometry":{
"type":"Point","coordinates":[15.26667,40.0502]},
"type":"Feature",
"properties":{
"data":"2006-03-01",
"specie":"S. coeruleoalba",
"localita":"Golfo di Salerno",
"provincia":"Salerno"
},"id":1},
{"geometry":{"type":"Point","coordinates":[14.88333,40.56692]},
"type":"Feature",
"properties":{
"data":"2006-03-03",
"specie":"S. coeruleoalba",
"localita":"Battipaglia",
"provincia":"Salerno"
},"id":2}
]}
Using this reader my grid shows the right number of rows (117) and pages, but empty cells
jsonReader : {
root: "features",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "properties",
id: "id"
}
Can someone help me to write a working reader? Thanks in advance
Your main error is that you try to use cell: "properties", but cell property will be ignored in case of usage of repeatitems: false property.
You should just use
jsonReader: {
root: "features",
repeatitems: false
}
and then define jsonmap property for every column. For example you can use the following column definition:
colModel: [
{name: 'coordX', jsonmap:'geometry.coordinates.0', width: 75, sorttype: 'number',
formatter: 'number', formatoptions: {decimalPlaces: 5}},
{name: 'coordY', jsonmap:'geometry.coordinates.1', width: 75, sorttype: 'number',
formatter: 'number', formatoptions: {decimalPlaces: 5}},
{name: 'data', jsonmap:'properties.data', width: 90, align: 'center',
sorttype: 'date', datefmt: 'm/d/Y',
formatter: 'date', formatoptions: {newformat: 'm/d/Y'}},
{name: 'specie', jsonmap:'properties.specie', width: 100},
{name: 'localita', jsonmap:'properties.localita', width: 100},
{name: 'provincia', jsonmap:'properties.provincia', width: 80}
]
As the result you will be able to read your JSON data to the following grid:
(see the demo here). In your JSON data I changed only total value from 0 to 1 because it has no sense to have the total value less as the page value.
I'm working with jqGrid to develop a time management module for a customer. We have already deployed jqGrid extensively over the rest of the site so we're working to make it fit this role too.
We need to be able to display a column for each day of a calendar month, each day then being split into two columns for overtime worked (HV - text input box) and the reason (R - select dropdown). I've got the grid designed to an extent (overtime/reason columns, list of branch staff etc) but am having trouble writing the processor. The code below shows what I currently have. This populates the grid (via another file) with a list of employees. The column list (day numbers 1-31) is generated from a PHP function which determines the current month and year. Grid.php then posts to gridsave.php when the row is clicked-off.
I would like to be able to determine which field has been edited as easily as possible. I do not want 62 columns (HV and R for each day of a 31 day month) in my database just in case, I'd like to programmatically determine the field id (date) and store that in a date column using my processor. If at all possible, I'd like to only pass modified fields to my processor to save on processing time.
Then, in reverse, I need to be able to extract this information (based on the date determined above) and input it into the correct column in jqGrid.
Needless to say I've now come up against a brick wall and not sure how to proceed on any of the above so will have to bow to superior knowledge. Any assistance in this will be much appreciated!
grid.php
var lastsel2;
jQuery(document).ready(function(){
jQuery("#timeLog").jqGrid({
url:'datagrid.php?module=timemanagement&branchid=<?php echo($branchid); ?>',
editurl: "gridsave.php?branchid=<?php echo($branchid); ?>",
datatype: 'json',
mtype: 'GET',
colNames:['First Name','Surname','Job Title',
<?php
$x = 1;
while($x <= $numdays) {
echo("'HV',");
echo("'R',");
$x++;
}
?>
],
colModel :[
{name:'firstname', index:'firstname', align: 'center', width: 100, searchoptions: { sopt: ['eq', 'ne', 'lt', 'gt', 'cn', 'nc']}},
{name:'lastname', index:'lastname', align: 'center', width: 100, searchoptions: { sopt: ['eq', 'ne', 'lt', 'gt', 'cn', 'nc']}},
{name:'jobtitle', index:'jobtitle', align: 'center', width: 100, searchoptions: { sopt: ['eq', 'ne', 'lt', 'gt', 'cn', 'nc']}},
<?php
$x = 1;
while($x <= $numdays) {
echo("{name:'hv-$x-$month-$year', index:'hv', align: 'center', width: 25, sortable: false, editable: true},");
echo("{name:'r-$x-$month-$year', index:'r', align: 'center', width: 25, sortable: false, editable:true, edittype:'select', editoptions:{value:':;OT:OT;S:S;H:H;OA:OA'}},");
$x++;
}
?>
],
onSelectRow: function(id){
if(id && id!==lastsel2){
$('#timeLog').jqGrid('saveRow',lastsel2);
$('#timeLog').jqGrid('editRow',id,true);
lastsel2=id;
}
},
pager: '#pager',
height: 500,
rowNum:25,
rowList:[25,50,100],
sortname: 'firstname',
sortorder: 'ASC',
viewrecords: true,
}).navGrid('#pager', {search:true, edit: false, add:false, del:false});
});
gridsave.php
// Check for exec permission
define('_CHECKEXEC', TRUE);
// Connect to database
include("./includes/init.inc.php");
if($_GET['oper'] == "edit") {
// Generate query and insert data
$sql = "INSERT INTO tbltimemanagement(userid, hv, r) VALUES ('$_POST[id]', '$_POST[hv]', '$_POST[r]');";
mysql_query($sql);
}