 What's New in This Release?
jqSuite PHP Documentation
What's New in This Release?

Last Updated: 12/13/11 | © TriRand Ltd., 2011


 Version 4.3.0.0
Version 4.3.0.0
Released 13, December 2011

This version is a major release where a lot of new features are added.

Additions

jqGrid

Changes in PHP

  • Fix for calculating the count of the records when more that two FROM commands are available
  • Added a public getLastInsert property (boolean) to get the last inserted id when a add operation is performed
  • Added new method getLastInsertId to get the last inserted ID if getLastInsert property is true. This method should be called after renderGrid or editGrid.
  • Error meassaging sytem rewrite
  • Added new public property oper which detrermines the current grid operation
  • Added customError function which overwrites the error meassaging sytem allowing to output custom error message
  • The last inserted id is returned if getLastInsert is set to true. The retun string is like 'PrimaryKeyName#LastInsertID'
  • Added inlineNav public property to enable inline navigator. Note that navigator property should be set to true too in this case
  • Added two new methods inlineNavOptions to set inline navigator options and inlineNavEvent to set a inline event
  • The jqGridUtils class is removed from the jqGrid.php file. Now this class is loaded from jqGrid.php file.
  • Added new method getInlineOptions which return the options for inline editing.

Changes in Java Script Code

  • Column Freezing – you can now freeze the first N columns of the grid, so that a horizontal scroll bar appears and they stay fixed (frozen) while you can still scroll the un-frozen columns.
  • Inline add new row – we figured we have “Add New Dialog” – addRow method
  • Inline navigator – a better way to handle control buttons while in inline add/edit/delete modes
  • Support reading any data from XML including attributes.
  • jQuery 1.7.1 and ThemeRoller 1.8.16 support – the latest jQuery and ThemeRoller releases are now officially supported and tested.
  • A LOT of fixes

jqChart

  • Fixed exporting
  • Fixed memory leaks in legacy IE.
  • Fixed compatibility issue with jQuery 1.7.

jqForm Visual Builder

  • Fixed short php tags in code
  • Fix obtaining and savig the data in the xml file.
Last Updated: 12/13/11 | © TriRand Ltd., 2011


 Version 4.2.0.0
Version 4.2.0.0
Released 24, October 2011

This version is a major release where a lot of new features modules and classes are added.

Additions

Added new module HTML5 jqForm Visual builder

More can be found here

Added new class jqForm

See documentatin on documentation page.
Demos can be found here

jqGrid

Changes in PHP

  • Fix autocomplete when used with DB2 driver
  • Fix for DB2 driver when afterCrud operation is set
  • Add a separator in setSelect method
  • Fix dateFormatter in datepicker
  • Added new PDF option shrink_header (default false) in order to preserve the old behaviour

Changes in Java Script Code

  • jQuery 1.6.x cmpatible
  • Added header grouping
  • idPrefix parameter in the grid to allow not have duplicate id in data row ids in case of two or more grids.
  • if the beforeRequest event return false the ajax request can be canceled.
  • Added beforeProcessing event which raises immediatley after the successed ajax request and before executing the adding new data.
  • Adding Croatian localization
  • RTL support for the new searchFilter module
  • Controlling the positions and dimensions of alert dialog – adding the following parameters in navGrid method – alertwidth, alertheight, alerttop, alertleft. alertzIndex
  • Allow user to override request method for inline edits (GET,POST) – i.e added mtype parameter
  • Support for optgroup in inline edit

jqChart

  • Added useHTML option for most text related configuration objects.
  • Added softConnector option for pie data labels.
  • Added chart.selectionMarkerFill option.
  • Fixed issues with data label positioning for pies.
  • Fixed issue with tooltips covering point in certain cases.
  • Worked on memory leak issues.
  • Fixed issues as listed at GitHub under dates since the last maintenance version.
  • Rewrote data label positioning for pies.
  • Fixed issues as listed at GitHub under dates since the last maintenance version.
  • Added shadows for pies.
  • Exported charts now respect user set min and max after zoom and visibility option.
  • Added option series.connectNulls to connect line graphs through null points.
  • Added support for exporting image symbols in charts.
  • Added data labels for stack totals and improved positioning of column and bar data labels.
  • Fixed issues as listed at GitHub under dates since the last maintenance version.

jqScheduler

  • Add public local and templet paths
  • Fix seraching to work with different chartsets
  • Added option editable. If this option is set to true the scheduler is not editable and the user can not edit or add data
  • Added option multiple_cal. If this option is set to true it is possible to view the data in multiple calendar users.
  • Added option multiple_size. This option have effect only if multiple_cal is true and determineds the number of visble users in the select (multiple option in the select);
  • Added year view
  • Added a progress indicatoe which does not allow interactiong when the data is loaded
Last Updated: 12/13/11 | © TriRand Ltd., 2011


 Version 4.1.2.0
Version 4.1.2.0
Released July 16, 2011

Additions

Grid

Improved PDF export
- Now the grid header text does not shrink the font so that the text fit the width. If there is no room for the text a new line is created
- added new option in PDF options - "shrink_cell" (default is true) if set to false the Font does not increase so that to fit the text in width, but a new line is added if needed.
- added new option in PDF options - "reprint_grid_header" (default is false). If set to true the grid header row is reprinted on every new page
Note : This option currently work only if the pdf option "shrink_cell" is set to false

Fixes

Fix searching with SQL LIKE operator in array driver
Now when debug is set to true the export command is recorded in jqGrid.log file
Fix mtype in add/edit/dell form options
Fix insert and update data when a non UTF-8 chartset is used
Fix database search when non UTF-8 charset is used
Fix Autocomplete to work properly when a non UTF-8 charset is used
Fix jqScheduler to work correct when a non UTF-8 charset is used
Fix client side searching on complex queries
Fix client side sorting when index property is missed.

Last Updated: 10/24/11 | © TriRand Ltd., 2011


 Version 4.1.1.0
Version 4.1.1.0
Released June 22, 2011

Additions

Add new memmber jqScheduler
Added two new classes Template and Session

Grid

Added two new options sharedDelOptions and sharedAddOptions (just like sharedEditOptions). When set to true they can be get using the getGridParam java script method from grid options array.

Fixes

Grid

Fix search module when data contain $ char
Fix SQL Server driver to get correct the primary key
Fix SQL Server driver for checking a undefined values
Fix fetch_num, fetch_object and coulumnCaount methods in Array driver
Fix debuging in queryGrid method
Fix export to Excel for PostgreSQL database for date fields
Fix array driver to support _ in names
Fix for array driver when search and empty result
Fix for single search method
Fix Exporting when array driver and there is a where clause
Fix properly build WHERE clause in array driver
Fix set ASC when ORDER is set to be default in array driver
Fix for closeCursor to reset the counter in array driver

Last Updated: 07/15/11 | © TriRand Ltd., 2011


 Version 4.0.0.4
Version 4.0.0.4
Released May 16, 2011

Additions

Grid

Add a php option sharedEditOptions (bollean). If set to true the options set in edit dialog in toolbar will be used in the same dialog when lunched from row button (rowActions)

Fixes

PHP

Fix a parseDate method which causes Undefined index in export.
Fix setAutocomplete method to accept righ the parameters startWith endWith and contain
Fix insert/update null values.
Fix in phpToJS date method
Fix when try to obtain null values from the response.

Last Updated: 06/22/11 | © TriRand Ltd., 2011


 Version 4.0.0.3
Version 4.0.0.3
Released April 27, 2011

Additions

Grid

Added Montenegrian Translation

Fixes

PHP

Fix parseDate function to accept any valyd PHP date string including AM/PM
Fix array driver to be compatible with PHP 5.3.x and up versions
Fix renderGrid method when create pager paremeter is set to false.
Fix work with local data and the PDO driver is loaded
Fix in renderTree method when echo parameter is set to false.

Javascript

Fix for content_type = 'application/xhtml+xml', where tag names are lower case
More strict check for field type in formedit
Fix typos in form edit when define a html element
Missed brackets whe n define select in filter
Fix setLabel method in case the real colModel name is number.
Fix for checkbox and select elements not to accept the value attribute in setAttributes function
Fix default operation for defaultFilter
Fix selection the search operation in right order and value
Hide AND/OR selectbox when multipleSearch is false.
Adding a missed custom viewfunc in navigator
Replace typeof(some) == 'function' with jQuery isFunction in form edit
Making scrollGrid flexible.
Check first if sopt is not null if set in searchGrid
Fix duplicated id's on the pager in case of more than two grids
Fix duplicate id's in column header in case of two or more grids
Fix for sortable columns according to the unique id in column header
Fix for updatepager to determine if the pager is available. Fix for multikey and multiselect
Fix sortableColumns to get the right id's
Fix Firefox outline styling in grouping
Fix toppager to display correct total pages
Last Updated: 06/22/11 | © TriRand Ltd., 2011


 Version 4.0.0.2
Version 4.0.0.2
Released April 9, 2011

Additions

jqGrid

  • Added new property in colModel editoptions NullIfEmpty. If set to true empty values are posted and set/added in the database as NULLs.
  • Added option fontsize in autocomplete widget to control the font size of the widget. Default is 11px;
  • Added option fontsize in calender widget to control the font size of the widget. Default is 70%;
  • Added option strictcheck in autocomplete widget - If target is set determines the behaviour of setting the value. If strictcheck is false the value in autcomplete input field is not cleared if it is not found in list.
  • If to a row in grid is added class ui-state-disabled the row can not be selected. Also work in multiselect mode.

Fixes

jqGrid

  • Fix setSelect (second fix) method to interpret correct ORDER BY clause when present in the query.
  • Fix for grid cmTemplate for editable fields.
  • Fix for addCol method to add in correct place the column when not first or last.
  • Fix for Autocomplete to work correct with Mysqli driver (the driver requiere special handling)
  • Fix fetch_bject method in Array driver
  • Fix for IE9 to support the height=>auto proerty.
  • Fix when scroll option is set to 1 - to return correct the last page
  • Fix for multiselect when row ID's contain dots.
  • Fixes for showCol/hideCol methods.
  • Fix for setGridWidth method for Webkit browsers
Last Updated: 05/13/11 | © TriRand Ltd., 2011


 Version 4.0.0.1
Version 4.0.0.1
Released March 25, 2011

This is mainly bug fix release

Fixes

jqGrid

  • Fix Autocomplete widget and setAutoComplete method to work with array
  • Fix for errorMsg ethod in SQL Server driver
  • Fix count function when strict erorr reporting is active
  • Fix setSelect method to treat correct ORDER BY clause when present in the query

Last Updated: 04/09/11 | © TriRand Ltd., 2011


 Version 4.0.0.0
Version 4.0.0.0
Released March 21, 2011

Additions

jqGrid

Added TreeGrid component
Added new search module. For all features see Search Options and Events
Added keyboard navigation in the grid and treegrid. This is achieved with the grid method bindKeys
Added new grid column event - cellattr - this function can add attributes and properties to a given cell. Ideal for merge cells by condition.
Improve Subgrid speed and options.
Added new grid options cmTemplate, which allow to overwrite the default options for the columns.
Added new javaScript method - getLocalRow which return the data from the local data array. Usually used with TreeGrid.
In all database drivers is added ErrorMessage method which return the last error.
Added PHP variable showError. If set to true all error messages are send to the client and shown in modal window.
Added PHP performcount variable. If set to false does nnot perform a counting query.
Added PHP method setBeforeCrudAction - now we can define sql commands before we do a CRUD into the main table.
Added new PHP method buildSearch - the method accept as parameter the search string from grid and return the SQL where clause. Also the methos can return array which first element is the string which can be used in prepare statement and the second is the array of values
Added Arabic translation
Added Lithuanian translation
Added isNull operator when searching
Updated Finnish translation
Add new event 'onClickGroup'. This event fires after clicking group (to expand or collapse group). See grid events.

jqChart

SQL Data now can contain two columns - to set X and Y values
Added setTheme method - which can be used to change the chart theme dynamically. A url can be used

Fixes

jqGrid

Fix Micrsoft SQL driver to support right queries when a paging is used and the query contain DISTINCT operator
Fix bug determining the type of the returned data from the summary information
Fix custom button now have right id attached
Fix error when strict reporting is set in PHP
Fix echo parameter in editGrid PHP method
Fix get accessor method
Fix for Microsoft date formatter
Fix multiselectwhen all rows are selected with click.
Support of Unix timestamp in date formatter.
Ability to add modal in column chooser
Fix for date formatter
Fox when ShrinkToFit = false
Prevent navigator, navButtonAdd and filterToolbar methods to be executed several times. Usually this happen in jQuery UI modal which append the content and script and script is executed again.
Fix for double quotes and backslach when searching
Fixes in toJson javascript funcion
Fixes for local searching
Fix saveRow javascriopt and formatter of type actions to accept righ errors from the server.
Fix local searching when column names contain dot, semicolon.
Fix position of the modal when the option overlay is set to 0

jqChart

Fix autodetecting column types when SQL command is used to obtain data.
Fix Left to Rigth texts in FireFox
Fix for exporting Pie charts
Fixed issue with charts not displaying in IE on pages with large background images or external resources
Fixed issue Safari Mobile crashing after removing a series dynamically.
Last Updated: 03/21/11 | © TriRand Ltd., 2011


 Version 3
Version 3

Last Updated: 04/26/11 | © TriRand Ltd., 2011


 Version 3.8.2.2
Version 3.8.2.2
Released January 21, 2011

Fixes jqGrid

  • Fix a bug when getting summary data - Standart Version only
  • Fix a bug to prevent second a etc calling of generated javascript code. This usually hapen when using the dialog or tab widgets to append data as first child of the body ( jQuery append function executes the script again).

Fixes jqChart

  • Fix exporting of null values
Last Updated: 04/09/11 | © TriRand Ltd., 2011


 Version 3.8.2.1
Version 3.8.2.1
Released January 10, 2011

Fixes jqGrid

  • Fix export to pdf when try to include a non existing file.
  • Fix export in CSV
  • Fix in setAutocomplete in grid to output with right headers the json response.
  • Fix in setColModel method to obtain the right parameter when try to construct model
  • Fix for Autocomplete in grid not to output two responses.
  • Fix in grouping module - summaryval array is extended correct with array and not with object.
  • Fix for groupingRemove method when some rows are hidden (i.e some groups are collapsed) and the method is called with false parameter.
  • Fix - the group item is using the formatter for it if defined
  • Fix grouping items when values are null, undefined or 0.
  • Fix multi selection when putting the values in selarrrow
  • Fix for SerializeSubgrid call.
  • Fix for getColProperty method

Additions

  • Added Charting module - jqChart. For full info, please refer to the jqChart documentation
  • Added support for MongoDB database. (currently CRUD operations are not included)
  • Added Array driver which allows to manipulate array data like SQL data (currently no CRUD).
  • Added method setAfterCrudAction(module, querysql, params). When used add a set of sql actions after CRUD is done with succes. It is possible to add a unlimited action for given operation (add, edit,del). See Tutorial
  • Added new method setButtonOptions. With this method is possible to set various options for the export buttons like Text, icon and etc.
  • Added method setSuccessMsg( string $msg )method for the edit modules. When set this text is send to the grid when the CRUD oper is successfull.
  • Added another button in the navigation toolbar - column. When set to true a column Chooser is lunched. Note that if you want to use them you should load the appropriate CSS and js files.
  • Updated formatter actions, which allow defining a butttons and actions for inline editing
  • Added error function in setAutocomplete method.
  • Adding Serbian language file
  • Form editing (add,edit,delete,search dialogues) now look more impressive
  • All functions in grid.common.js now are in jgrid name space. This prevent some function conflicts with other JS libs.
  • Perform search on filter dialog whenpressing Enter key.
  • Run the onHeaderClick callback after all animations are finished, so that the callback can operate on the new height Thanks to flack
  • Make it possible to deselect a selected row by clicking it again
  • If colModel has index defined for grouping field, use it for sorting
  • Restore inline edited rows in case of form and inline edit defined at the same time.
  • Now the beforeInitData event can return true or false. If the event return false the the action is not done and the form is not lunched.
  • Adding templates for colModel, which simplify the code.
  • Update for Persian language.
  • Support for Microsoft date format in formatter date.
Last Updated: 04/09/11 | © TriRand Ltd., 2011


 Version 3.8.1.1
Version 3.8.1.1
Released November 7, 2010

Fixes

  • Fix: grouping should not be checked with F array.
  • Fix: When data element in addJsonData and addXMLData is not provided with the response.
  • Fix: Save the right value when beforeSaveCell is used in cell editing
  • Fix local sorting when integer data is available and a case insensitive search is active.
  • Fix in setCell when a index has a values 0.
  • Fix disabled attribute in checkbox formatter
  • Fix closing tag in viewGridRow method
  • Fix XHTML problems in grid base module
  • Fix grouping by integer.
  • Fix date formats in German locale
  • Correct some errors in German locale
  • Fix: z-index is the same when a modal grid creates a dialogue which contains another grid which calls add/delete/edit dialog
  • Fix French locale
  • Fix gettting the right table when more that two DnD tables are set.
  • Fix for TreeGrid to expand the right index node
  • Fix gridDnD not to accept calling when used other methods (Thanks to Oleg)
  • Fix for Catalan Translation
  • Fix grouping summaryval to be extended correct with array and not a object
  • Fix sorting and resizing in TreeGrid
  • Fix remove grouping method when some rows are hidden (i.e some groups are collapsed) and groupingRemove is called with false parameter

Additions

  • Add export to PDF
  • Add export to CSV
  • Add a possibility to change the ovwerlay of the modals
  • Set default search options for select to eq(equal) in filterToolbar method
Last Updated: 04/09/11 | © TriRand Ltd., 2011


 Version 3.8
Version 3.8
Released August 1, 2010

Fixes

  • Fix export to excel to be compatible with Excel 2007
  • Fix export url in export to excel method
  • Fix searchFilter method to be compatible with other JS libraries
  • Fix Google compiler error when build min file
  • Fix when scroll grid option is set to 1 and we have only one page.
  • Fix local reader when a xml or json string is set
  • Fix for Spanish Translation. It is called wrong with sp instead of es.
  • Fix local sorting when name != index.
  • Fix when we trigger grid and we are in treeGrid mode.
  • Fix setCell to set correct the value on the first row when datatype is local
  • Fix for isEmpty function.
  • Fix getCellIndex method in case when we pass a parameter which is not td or th.
  • Fix date sorting when local data is enabled.
  • Fix: with custom element Add worked only 1st time.
  • Fix: exception can be a string.
  • Fix setRowData when datatype local and the rowid is't in the index.
  • Fix for refresh button which causes two triggering of the grid and not correct clear some data in toolbar filter.
  • Fix for getAccessor.
  • Fix for table to grid method to be compatible with other non jQuery JS libs
  • Fix for unformat select to support values which are delemited with more than two ”:”
  • Fix for inline edit when a ajax error occur. We must call restore row after this
  • Fix for getting the name as attribute when the element is not a input one (used when custom element is created).
  • Fix for filterToolbar when autosearch is true in Chrome, Safari browsers. The enter key causes submitting the value.
  • Fix sorting when the grid is scrolled horizontally and scroll option is set to 1.

Additions

  • One level Grouping. For more information refer to grid grouping options and Grouping tutorial.
Last Updated: 04/09/11 | © TriRand Ltd., 2011


 Version 3.7
Version 3.7
Released June 15, 2010

Fixes

  • Fix setColModel to support DB2 databases.
  • Fix in prepare method for SQL Server driver
  • Fix a subgrid as grid when the id contain special characters
  • Fix adding userdata with addUserData method when there is no data in result->userdata object

Additions

  • Support for DB2 databases. The driver is tested in Windows and IBM i5 series.
  • Added $optimizeSearch parameter (default false). This parameter should be used only in MySQL databases where the number of rows in the returned query is relative big > 800 000 rows and the query is not very complex and a search module is activated.
  • Added possibility to load all the data at once and operate it localy without to make additional server calls. Note that CRUD operations should work if they are activated. For this porpose is added rowTotal parameter in the grid. See tutorial.

Upgrade

  • The jquery.jqGrid.min.js should be replaced with the new one provided from the package
  • Replace all jqGrid PHP files with the new ones provided from the packege
Last Updated: 04/09/11 | © TriRand Ltd., 2011


 Version 3.6.4
Version 3.6.4

Fixes

  • Fix Export to excel when the search is empty string
  • Fix quote function
  • Fix for complex quieries to properly get the count.
  • Fix Export to excel to get right the where clause.
  • Call closeCursor on the right place when build the colModel
  • Add close the cursor for Oci8 when get the primary key.
  • Fix for close the cursor in PDO when get primary key

Additions

  • Add mysqli driver
  • Added customFunc where we can modify the final grid result
  • Added addUserData method for custom loading user data.
  • Adding xmlCDATA variable which allow to send the xml as CDATA.
Last Updated: 04/09/11 | © TriRand Ltd., 2011


 Version 3.6.3
Version 3.6.3

Bug Fixes

  • Replace $_REQUEST when obtain parameter value with GetParam function,which get the parameter from GET or POST only- Fix in selectLimit method where the $param input parameter was nulled
  • Fix for obtaining the count parameter from the generated query object
  • Fix for Excel export where the header function was placed in the wrong placewhich causes in some system to output only certain record set.
  • Fix in renderGrid method to be compatible with jQuery 1.4.x
  • Fix for count parameter not to be included in userdata
  • Fix for PostgreSQL to get the right columns types (typo error)
  • Fix for MySQL PDO driver to support TYNIINT (Also PDO bug in driver)
  • Fix in searching to get the propererly values when the encoding is utf-8
  • Fix in setGridParam method
  • Fix in serching when we get the parameters from search. Now we check ifthe build in PHP json_decode exists. If this is not true we use our own decodefunction
  • Fix when a PHP STRICT error checking is on. Now all related functions are declared as public static.
  • replace PHP array_merge with own array_extend. The array_merge in certaincases deletes the already setted properies.
  • Fix in decode function to treat correct " in the result set.

Additions

  • Added debugging. This is done with $grid->debug = true. In this case a jqGrid.log file is created in the directory where the script is executed.
  • To querySubgrid method is added second parameter $echo, if set to true the result is returned as object
  • Added SQLite driver via PHP PDO. The driver is still in beta. The problem in this driver is that there is a bug in the PHP SQLite PDO driver when theresult set does not contain data. In this case the columnMeta function returnfalse. This mean that if the first result set is empty we can not build thecolModel, since we can not obtain the columns.
  • Aded a Oracle driver via the native oci8 PHP http://php.net/manual/en/book.oci8.php
Last Updated: 04/09/11 | © TriRand Ltd., 2011


 jqGrid PHP Documentation
jqGrid PHP Documentation
Welcome to the technical documentation of jqGrid for PHP. If you have questions and comments, please use the following channels to get back to us:

Public forums:
http://www.trirand.net/forum/

Email:
support@trirand.net

Last Updated: 12/13/11 | © TriRand Ltd., 2011


 Introduction
Introduction

jqGrid for PHP is a server-side component built on top of open and widely used standards such as jQuery, jQuery UI, ThemeRoller, etc..

Some of the major features include:

  • Blazing speed - only the minimal data required is sent from server to client using JSON. Supports millions of rows of data.
  • Supports the most popular SQL Databases like PostgreSQL, MySQL, Microsoft SQL Server.
  • Minimal HTML size - jqGrid uses client-side rendering, meaning no hundreds of KBs of nested <tables> in HTML.
  • jQuery based client-side - familiar and powerful client-side API based on jQuery.
  • Feature complete - every feature you might need, including adding/editing of records, hierarchy, sorting, filtering, paging, etc
  • ThemeRoller support - theming is based on ThemeRoller. A set of 25 themes by professional designers is available, including great free theme authoring tool.
  • many more.

Last Updated: 07/15/11 | © TriRand Ltd., 2011


 Installation & System Requirements
Installation & System Requirements

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 System requirements
System requirements

Browser Support

jqGrid for PHP supports all major browsers:

  • Internet Explorer 6.x+
  • FireFox 3.x+
  • Safari 2.x+
  • Google Chrome 2.x+
  • Opera 9.5+

Note: a minor number of features may not work in all browsers. For example, currently RTL (right-to-left) support is limited to IE and FireFox only

PHP

jqGrid is designed to work with PHP versions 5.1+.

Databases

Currently jqGrid for PHP supports the following databases:

  • MySQL 5.x+ (PDO)
  • PostgreSQL versions 7.x+ (PDO)
  • SQLite versions 3.x+ (PDO)
  • Microsoft SQL Server 2005+
  • Oracle 8+
  • MySQL (through Mysqli)
  • DB2 (IBM DB2 functions)
  • Array
  • MongoDB

MySQL, PostgreSQL and SQLite databases are supported through PHP PDO (PHP Data Objects), so depending on your PHP setup you may need to install it before using jqGrid for PHP. PDO is by default installed in PHP 5.1+ distributions. PDO is a core PHP technology, created and supported by the core PHP team.

To ensure that PDO is installed in your production enviornment, please run the following PHP script on your development/production machine:

<?php
phpinfo();
?>

Save the file and run it on your web server. The following should appear if you want to use MySQL and have PDO installed:

The following should appear if you want to use PostgreSQL and have PDO installed:

The following should appear if you want to use SQLite and have PDO installed:

Microsoft SQL Server is supported through the PHP driver provided by Microsoft. Please follow the installation instructions provided by Microsoft in the PHP driver documentation. After the driver is installed, the following should appear if you run the "phpinfo()" function:

Oracle is supported through the PHP OCI8 driver. Please follow the installation instructions provided in the same link. After the driver is installed, the following should appear if you run the "phpinfo()" function:

Additinally MySQL database is supported through Mysqli driver. Follow the installation instuction provided from the same link. After the installation is done the following should appear if you run the "phpinfo()" function:

Additinally DB2 database is supported through DB2 driver. Follow the installation instuction provided from the same link. After the installation is done the following should appear if you run the "phpinfo()" function:

Last Updated: 05/31/11 | © TriRand Ltd., 2011


 Quick installation
Quick installation
Download and unzip the contents of the archive to any convenient location. The package contains the following folders:

- [php] - Contains the jqGrid PHP classes and the driver files for the appropriate database.
- [themes] - Contains the themes shipped with the product. Since jqGrid supports jQuery UI Themeroller, any theme compatible with jQuery UI ThemeRoller will work for jqGrid as well. Therefore, the package contains just one theme ("Redmond"). You can download any additional themes directly from jQuery UI's ThemeRoller site available here:

http://jqueryui.com/themeroller/

In addition to the "Redmond" theme, there is one more file in the [themes] folder - ui.jqgrid.css. This is the one and only Css file jqGrid needs. Just add it after you add the reference to the "Redmond" theme in your PHP/HTML file containing jqGrid for PHP.

<link rel="stylesheet" type="text/css" href="themes/redmond/jquery-ui-1.7.2.custom.css" />
<link rel="stylesheet" type="text/css" href="themes/ui.jqgrid.css" />

- [js] - The javascript files of jqGrid (and the needed libraries). You need to include them in your PHP page.

The first file is "jquery.js" - this is the official jQuery library on which jqGrid is built upon.
The second file you need is the i18n (localization) javascript file. Depending on the language you need, just pick one from the "js/i18n" folder.
The last one is the jqGrid javascript code itself, located in "jquery.jqGrid.min.js"

The final result you will have in an PHP page containing jqGrid would be something similar to that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqGrid </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>

</head>
<body>
......
<?php include "myfirstgrid.php";?>
.......
</body>
</html>

Save the file as grid.php or any desired name in the root directory.

In the root directory you will find a file named jq-config.php. Open the file and enter the appropriate information for the connection to the database. Save the file and then create a file myfirstgrid.php with the following content.

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
// We suppose that mytable exists in your database
$grid->SelectCommand = 'SELECT field1, field2, field3  FROM mytable';

// set the ouput format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('myfirstgrid.php');
// Set grid caption using the option caption
$grid->setGridOptions(array(
    "caption"=>"This is custom Caption",
    "rowNum"=>10,
    "sortname"=>"field1",
    "rowList"=>array(10,20,50)
    ));

// Change some property of the field(s)
$grid->setColProperty("field1", array("label"=>"ID", "width"=>60));

// Run the script
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
?>

Run the file grid.php from your web browser. All subsequent requests the grid needs (e.g. paging, sorting, searching, etc) will be forwarded back to the "myfirstgrid.php" file (using the $grid->setUrl(...) method) and the grid will automatically handle the requests and provide the needed response - no need for custom coding.

Last Updated: 03/18/11 | © TriRand Ltd., 2011


 Connection and database drivers
Connection and database drivers
If you take a look at our "Quick installation" topic, you will see that jqGrid for PHP does not create its own connection to the database, but uses a connection that already exists. This is a very flexible approach in complex applications where the connection to the database had already been created. Typically in our examples we will create the connection using PDO rules, but this is not neccessary and you can reuse your own connection.

PDO Driver

When a PDO driver is used (for MySQL or PostgreSQL) a file named jqGridPdo.php should be included in addition to the main jqGrid.php file. The file is available in the [php] folder of the jqGrid for PHP download package. Please note, that in this case you do not need to specify explicitly which database should be used - MySQL or PostgreSQL. The script will detect this automatically from the connection. Here is an example:

<?php
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class - needed for MySQL and Postgre SQL
require_once "php/jqGridPdo.php";
...
?>

Microsoft SQL Driver

When Microsoft SQL Server is used, a file named jqGridSqlsrv.php should be included in addition to the main jqGrid.php file. The file is available in the [php] folder of the jqGrid for PHP download package.

Note: In order to work properly with fields of type "Date", when the connection is created you should also set a property - "ReturnDatesAsStrings"=>true in the connection string. The reason for this is that the driver by default handles dates as PHP date object.

Here is an example:

<?php
// Example connection
$connectionInfo = array("UID" => 'user', "PWD" => 'password',"Database"=>"test", "ReturnDatesAsStrings" => true);
$serverName = "localhost\SQLEXPRESS";
$conn = sqlsrv_connect( $serverName, $connectionInfo);
...
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the SQL Server driver class
require_once "php/jqGridSqlsrv.php";
...
?>

Last Updated: 02/24/10 | © TriRand Ltd., 2011


 Localization
Localization

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 List of available language packs
List of available language packs

List of predefined packs

A complete list of available predefined language packs in the /js/i18n folder with their filename and the language they represent.

File name | Language
grid.locale-bg.js | Bulgarian
grid.locale-en.js | English
grid.locale-de.js | German
grid.locale-fr.js | French
grid.locale-sp.js | Spanish
grid.locale-it.js | Italian
grid.locale-nl.js | Dutch
grid.locale-no.js | Norwegian
grid.locale-fi.js | Finish
grid.locale-he.js | Hebrew
grid.locale-ja.js | Japanese
grid.locale-cn.js | Chinese
grid.locale-pt.js | Portuguese
grid.locale-pt-br.js | Brazilian-Portuguese
grid.locale-ru.js | Russian
grid.locale-ro.js | Romanian
grid.locale-pl.js | Polish
grid.locale-cs.js | Czech
grid.locale-el.js | Greek
grid.locale-fa.js | Persian
grid.locale-is.js | Icelandic
grid.locale-sv.js | Swedish
grid.locale-tr.js | Turkish
grid.locale-ua.js | Ukranian
grid.locale-cat.js | Catalan

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Using predefined language packs
Using predefined language packs

Basics

jqGrid for PHP comes with a large number of predefined language packs and settings for almost all popular languages. They are located in the installation package, in the /js/i18n folder. Language packs are in the form of javascript files, containing definitions for all strings in the grid that can be localized - this includes messages, captions, paging information, search/add/delete dialog labels, etc.

In order to use a particular language pack, you need to include the javascript language pack to the head section of your page, after the jQuery library reference (since language packs depend on jQuery) and before referencing the jqGrid javascript file (since it is dependent on the language pack). A typical setup for English localization would look like this:

...
<head>
<!-- The jQuery UI theme that will be used by the grid -->
<link rel="stylesheet" type="text/css" media="screen" href="/themes/redmond/jquery-ui-1.7.1.custom.css" />

<!-- The jQuery UI theme extension jqGrid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="/themes/ui.jqgrid.css" />

<!-- jQuery runtime minified -->
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>
<!-- The localization file we need, English in this case -->
<script src="/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<!-- The jqGrid client-side javascript -->
<script src="/js/jquery.jqGrid.min.js" type="text/javascript"></script>
...
</head>
...

Note: The order in which the javascript files are included is very important, because of the dependencies described above.

If you want to use the Norwegian localization of jqGrid, just use something along the lines of:

...
<head>
<!-- The jQuery UI theme that will be used by the grid -->
<link rel="stylesheet" type="text/css" media="screen" href="/themes/redmond/jquery-ui-1.7.1.custom.css" />

<!-- The jQuery UI theme extension jqGrid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="/themes/ui.jqgrid.css" />

<!-- jQuery runtime minified -->
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>
<!-- The localization file we need, Norwegian in this case -->
<script src="/js/i18n/grid.locale-no.js" type="text/javascript"></script>
<!-- The jqGrid client-side javascript -->
<script src="/js/jquery.jqGrid.min.js" type="text/javascript"></script>
...
</head>
...

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Modifying/Creating a new language pack
Modifying/Creating a new language pack

Structure of a language pack

A language pack is essentially a javascript code file with constants for specific strings in the grid that can be localized. In addition to that, there are formats (e.g. currency format, date format, etc) that can be predefined to match the locale of the specific country.

In order to modify a language pack, just open the respective javascript file and edit it with your favourite text editor. For example, let's say we want to modify the English language pack. Opening the /js/i18n/grid.locale-en.js file in a text editor brings are something along the lines of (this is just a part of the file):

$.jgrid = {
   defaults : {
      recordtext: "View {0} - {1} of {2}",
      emptyrecords: "No records to view",
      loadtext: "Loading...",
      pgtext : "Page {0} of {1}"
   },
   search : {
      caption: "Search...",
      Find: "Find",
      Reset: "Reset",
      odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with',
            'does not begin with','is in','is not in','ends with',
            'does not end with','contains','does not contain'],
      groupOps: [   { op: "AND", text: "all" },   { op: "OR",  text: "any" }   ],
      matchText: " match",
      rulesText: " rules"
   },
   ...

Just modify any of the strings/rules you wish. The naming of the string is self-explanatory - for example in order to modify the pager text displaying the number of pages, just modify the pgtext variable in the defaults array. Some of the variables have parameters, e.g. {0}, {1}, etc - these are placeholders for dynamic parameters for the respective string - e.g. pgtext requires two parameters - the current page and the total number of pages. They will be provided automatically by jqGrid.

You can also modify various locale specific formats in the same file. They are defined in the formatter portion of the localization file, for example (this is just a part of the formatter)

formatter : {
      integer : {thousandsSeparator: " ", defaultValue: '0'},
      number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'},
      currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'},
      date : {
         dayNames:   [
            "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
            "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
         ],
         monthNames: [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
            "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
         ],
         ...

Just modify anything you wish, like thousandsSeparator for integer format, or the month or dayNames. Finally, save the file with another name, for example, "grid.locale-custom.js" and include it in your page instead of the English file, e.g.

...
<head>
<!-- The jQuery UI theme that will be used by the grid -->
<link rel="stylesheet" type="text/css" media="screen" href="/themes/redmond/jquery-ui-1.7.1.custom.css" />

<!-- The jQuery UI theme extension jqGrid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="/themes/ui.jqgrid.css" />

<!-- jQuery runtime minified -->
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>
<!-- The localization file we need, Custom in this case -->
<script src="/js/i18n/grid.locale-custom.js" type="text/javascript"></script>
<!-- The jqGrid client-side javascript -->
<script src="/js/jquery.jqGrid.min.js" type="text/javascript"></script>
...
</head>
...

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Programmatically overriding language defaults
Programmatically overriding language defaults
In some cases, you may want to keep the majority of the locale settings in your javascript language packs, but still change some of them programmatically based on certain server-side conditions.

The way this works is the following - if a specific value for a property is not specified in PHP code, the default from the language pack will be used. If it is specified in code however, it will override the language pack default.

A common example for this is customizing the Editing Dialog. By default (if English language pack is used), the default caption of the dialog and the submit/cancel buttons will have these values (taken from grid.locale-en.js):

edit : {
   editCaption: "Edit Record",
   bSubmit: "Submit",
   bCancel: "Cancel"
}

If you want to change that however, just set the respective settings in the setNavOptions method of the jqGridRender class, e.g.

<?php
...

$grid = new jqGridRender($conn);
...
$grid->setNavOptions('edit',array("editCaption"=>"My New Caption","bSubmit"=>"My Submit Text","bCancel"=>"My Cancel Text") );
...
?>

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Right-To-Left languages
Right-To-Left languages
Some language locales require right-to-left (RTL) support. We are fully committed to that and provide the best right-to-left support in the industry. In order for this to work, just use the respective language locale javascript file and set the direction property of the grid to rtl, e.g.

<?php
...
$grid = new jqGridRender($conn);
...
$grid->setGridOptions(array("direction"=>"rtl"));
...
?>

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Theming
Theming

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Basics
Basics
Theming is based on the highly popular and open ThemeRoller, which is the standard for developing jQuery UI widgets. This means that you have access to 25 ready-to-use themes created by professional designers, plus a unique free web-based tool allowing you to create your own theme. You can also customize a theme starting from an existing one.

The list of currently available themes is:

  • base
  • black-tie
  • blitzer
  • cupertino (Apple-like UI)
  • dark-hive
  • dot-luv
  • eggplant
  • excite-bike
  • flick
  • hot-sneks
  • humanity
  • le-frog
  • mint-choc
  • overcast
  • pepper-grinder
  • redmond (Windows-like UI)
  • smoothness
  • south-street
  • start
  • sunny
  • swanky-purse
  • trontastic
  • ui-darkness
  • ui-lightness
  • vader

Here is a preview of some of them

Redmond

UI Lightness

Humanity

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Setting a theme for the grid
Setting a theme for the grid
The install package of jqGrid for PHP comes with just the default Redmond theme. It is available in the [themes] folder of the install package. You can download any additional themes directly from jQuery UI's ThemeRoller site available here:

http://jqueryui.com/themeroller/

There are currently 25 professional themes available. You can also create a new theme (either from scratch or based on another theme).

In addition to the "Redmond" theme, there is one more file in the [themes] folder - ui.jqgrid.css. This is the one and only Css file jqGrid for PHP needs for themeing in addition to the ThemeRoller theme. Just add it after you add the reference to the ThemeRoller theme in your PHP file.

Example:

<head>
<link rel="stylesheet" type="text/css" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" href="themes/ui.jqgrid.css" />
...
</head>

If you wish to use one of the other 25 themes ThemeRoller offers or your own theme, just replace the Redmond css file with the CSS file of the respective theme.

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Rolling your own theme
Rolling your own theme
In order to create your own theme, just use the superb ThemeRoller theme creator tool available here.

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Architecture and classes guide
Architecture and classes guide

jqGrid for PHP is designed in a way that allows it to be integrated in any framework or architecture, without compromising any of its features. In order to achieve this, we have separated the component into three classes - each of them provides functionality that is convenient in different contexts.

In addition to that, each class inherits the properties of its base class, so that the base features will be available to you at any time.

Below is the list of classes:

jqGrid Class
jqGridEdit Class
jqGridRender Class

Here is the hierarchy of the classes

jqGrid
   |
   --jqGridEdit
      |
      --jqGridRender

jqGrid is the base class and provides some of the functionality, jqGridEdit extends on that and provides editing capabilities, jqGridRender extends jqGridEdit and provides all grid features plus automatic generation of Javascript and HTML placeholders required by the grid. In this respect, jqGridRender is the most advanced class and requires the minimal amount of coding, however in certain situations you may find jqGrid and jqGridEdit more convenient to use based on the context.

Last Updated: 12/13/11 | © TriRand Ltd., 2011


 jqGrid Class
jqGrid Class

This is the base jqGrid Class, which is responsible for

  • Delivering data to an already manually constructed (with javascript) jqGrid instance
  • Searching
  • Sorting
  • Paging
  • Simple subgrid support
  • Export to Excel

Using this class requires some javascript knowledge, since the grid should be created in an existing html or php page with javascript declaration. In other words, the jqGrid class will only take care of the server side operations, while all other events and operations at the client side can be defined manually by the developer. More information on jqGrid javascript documentation can be found here
.

In order to illustrate how the jgGrid class can be used, please take a look at the following example:

Note: all examples used in the documentation use the Northwind database, which is included in the installation (download) package as SQL dump.

Create an html file with following content (note, that you will need to declare the grid with javascript if you are using the jqGrid class):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate"},
     {"name":"CustomerID","index":"CustomerID"},
     {"name":"Freight","index":"Freight"},
     {"name":"ShipName","index":"ShipName"}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager"
});
// Set navigator with search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:false,del:false});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

Save the file and the create a file named querygrid.php. Note that this file is used in the url parameter of the grid (defined in the javascript of the html file).

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGrid instance
$grid = new jqGrid($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
$grid->dataType = "json";
$grid->queryGrid();
?>

That is all. Save the file and run the html file in your browser. Note that paging, searching and sorting are executed automatically by the jqGrid class - no need to write custom code.

Last Updated: 07/15/11 | © TriRand Ltd., 2011


 Variables
Variables
Type | Name | Description | Default | Access
static mixed | $queryLog | Array that holds the log information | empty array | protected
string | $dataType | The output format for the grid. Can be json or xml | xml | public
array | $datearray | Store the names that are of "Date" type. The names should correspond to the names in colModel. Used in search to convert the user date to db date | empty array | public
string | $dbdateformat | Date format accepted in the database. See getDbDate. Used for searching. Also used in CRUD operation - see jqGridEdit class | Y-m-d | protected
string | $dbtimeformat | Datetime format accepted in the database. See getDbTime. Used in serching data. Also used in CRUD operation - see jqGridEdit class | Y-m-d H:i:s | protected
string | $dbtype | This is detected automatically from the passed connection. | empty string | protected
boolean | $debug | Enable disable debuging. Depending on the variable $logtofile outputs the information either in file or console | false | public
string | $encoding | Default enconding passed to the browser. | utf-8 | public
string | $ExportCommand | Set the sql command for excel export. If this command is empty a $SelectCommand is used | empty string | public
array $GridParams Holds the parameters that are send from the grid to the connector. This array correspond to prmNames object in jqGrid Javascript library array("page" => "page","rows"=>"rows",
"sort" => "sidx","order"=>"sord",
"search" => "_search","nd"=>"nd",
"id" => "id","filter"=>"filters",
"searchField"=>"searchField",
"searchOper"=>"searchOper",
"searchString"=>"searchString",
"oper" => "oper","query"=>"grid",
"addoper" => "add","editoper"=>"edit",
"deloper" => "del","excel"=>"excel",
"subgrid"=>"subgrid"); 		protected
integer | $gSQLMaxRows | Maximum number of rows to be exported for the excel | 1000 | public
string | $I | Used to perform case insensitive search in PostgreSQL. The variable is setted automaticali | protected
boolean | $jsonencode | If set to true uses the PHP json_encode if available. If this is set to false a encode is used. This should be changed if the character set in the database is not utf-8 | true | public
boolean | $logtofile | Determines if the log should be written to file or echoed. By default it is true and when the debugging is enabled a jqGrid.log file is created in the directory where the jqGrid class is called. | true | public
boolean | performcount | If set to false does not execute the automatic query for the count of records and summary operation. Use this variable with care | true | public
resourse | $pdo | Stores the connection passed to the constructor | empty | protected
boolean | $readFromXML | Obtain the SQL qurery from XML file. In this case the SelectCommand should be set as xmlfile.sqlid. The xmlfile is the name of xml file where we store the sql commands, sqlid is the id of the required sql. | false | public
string | $select | Holds the modified select command used into grid | empty | protected
string | $SelectCommand | In case if no table is set, this holds the sql command which is executed and the result is sended to the grid | empty | public
string | $SubgridCommand | Set a sql command used for the simple subgrid. Experimental | empty | public
boolean | $showError | Allow to send all errors which occur on server to the client. If used with jqGrid and jqGridEdit class the appropriate error events should be written. If used with jqGridRender class these events are created automatically | false | public
string | $table | set a table to display a data to the grid if the $SelectCommand is empty string | empty | public
string | $userdateformat | The date format used by the user when a search is performed. Also used in CRUD operation - see jqGridEdit class | d/m/Y | protected
string | $usertimeformat | The datetime format used by the user when a search is performed.Also used in CRUD operation - see jqGridEdit class | d/m/Y H:i:s | protected
function | $customFunc | Custom function which can be called to modify the grid output. Parameters passed to this function are the response object and the db connection. See Tutorials on how to use it. | null | public
boolean | $xmlCDATA | Defines if the xml otput should be enclosed in CDATA when xml output is enabled | false | public
boolean $optimizeSearch Optimizes the search SQL when used in MySQL with big data sets.
Use this option only in MySQL databases with not very complex queries (queries with subselects) 		false public
array $PDF Stores the options for PDF export. To set a vareios PDF options for export use setPdfOptions method

array(
"page_orientation" => "P",
"unit"=>"mm",
"page_format"=>"A4",
"creator"=>"jqGrid",
"author"=>"jqGrid",
"title"=>"jqGrid PDF",
"subject"=>"Subject",
"keywords"=>"table, grid",
"margin_left"=>15,
"margin_top"=>7,
"margin_right"=>15,
"margin_bottom"=>25,
"margin_header"=>5,
"margin_footer"=>10,
"font_name_main"=>"helvetica",
"font_size_main"=>10,
"header_logo"=>"",
"header_logo_width"=>0,
"header_title"=>"",
"header_string"=>"",
"header"=>false,
"footer"=>true,
"font_monospaced"=>"courier",
"font_name_data"=>"helvetica",
"font_size_data"=>8,
"margin_footer"=>10,
"image_scale_ratio"=>1.25,
"grid_head_color"=>"#dfeffc",
"grid_head_text_color"=>"#2e6e9e",
"grid_draw_color"=>"#5c9ccc",
"grid_header_height"=>6,
"grid_row_color"=>"#ffffff",
"grid_row_text_color"=>"#000000",
"grid_row_height"=>5,
"grid_alternate_rows"=>false,
"path_to_pdf_class"=>"tcpdf/tcpdf.php", "shrink_cell"=>true,

"reprint_grid_header"=>false
);

 protected
Last Updated: 07/15/11 | © TriRand Ltd., 2011


 Public Methods
Public Methods
addUserData( array $adata )

Add a custom data to the grid footer row if it is enabled. Also can be used to transport additional data in userdata array to be used later at client side. The syntax is $grid->addUserData(array("Name1"=>"Data1",...)); The method is executed after the sumarry rows are executed, so it can overwrite some summary data which is palced on the footer.
Parameters:
  • array $adata: associative array

buildSearch( $filter, $otype='str' )

Build a where clause friom filter string compatible with string posted from grid when a search is performed.
Usually this method is used separatley.
Parameters:
  • string $filter: the string to be parsed
  • string $otype: determines the return value. if it is = str the return is a string, otherviese array with values redy to be used in prepared statement
  • return string or array depending on $otype parameter

void debugout( )

Prints all executed SQL queries to file or console

API Tags:
See: jqGrid::$logtofile
Access: public

exportToCsv( [ $summary = null], [ $params = null], [ $colmodel = null], [$echo = true], [$filename = 'exportdata.csv'], [$sep=';'], [$sepreplace=''] )

Public method to export a grid data to csv data.
Can use the ExportCommand. If this command is not set uses _setSQL to set the query.
The number of rows exported is limited from gSQLMaxRows variable
@see _setSQL API.

Parameters:

  • array $summary: - set which columns should be sumarized in order to be displayed to the grid By default this parameter uses SQL SUM function: array("colmodelname"=>"sqlname"); It can be set to use the other one this way array("colmodelname"=>array("sqlname"=>"AVG")); By default the first field correspond to the name of colModel the second to the database name
  • array $params: parameter values passed to the SQL if the query is with parameters
  • array $colmodel: - diffrent descriptions for the headars, width, hidden cols This array is actually a colModel array in jqGrid. The array can look like Array( [0]=>Array("label"=>"Some label", "width"=>100, "hidden"=>true, "name"=>"client_id", "formatter"=>"select", editoptions=>...), [1]=>Array("label"=>"Other label", "width"=>80, "hidden"=>false, "name"=>"date",... ), ... )
  • boolean $echo: determines if the result should be returned or echoed
  • string $filename: the filename to which the sheet can be saved in case if $echo is true
  • string $sep - the separator for the csv data
  • string $sepreplace - with what to replace the separator if in data
  • return string

exportToExcel( [ $summary = null], [ $params = null], [ $colmodel = null], [$echo = true], [$filename = 'exportdata.xls'] )

Export the recordset to excel xml file. Can use the ExportCommand. If this command is not set uses _setSQL to set the query. The number of rows exported is limited from gSQLMaxRows variable

Parameters:

  • array $summary: - set which columns should be sumarized in order to be displayed to the grid By default this parameter uses SQL SUM function: array("colmodelname"=>"sqlname"); It can be set to use the other one this way array("colmodelname"=>array("sqlname"=>"AVG")); By default the first field correspond to the name of colModel the second to the database name
  • array $params: parameter values passed to the SQL if the query is with parameters
  • array $colmodel: - diffrent descriptions for the headars, width, hidden cols This array is actually a colModel array in jqGrid. The array can look like Array( [0]=>Array("label"=>"Some label", "width"=>100, "hidden"=>true, "name"=>"client_id", "formatter"=>"select", editoptions=>...), [1]=>Array("label"=>"Other label", "width"=>80, "hidden"=>false, "name"=>"date",... ), ... )
  • boolean $echo: determines if the result should be returned or echoed
  • string $filename: the filename to which the sheet can be saved in case if $echo is true

exportToPdf( [ $summary = null], [ $params = null], [ $colmodel = null], [$filename = 'exportdata.pdf'] )

Export the recordset to PDF file. Can use the ExportCommand. If this command is not set uses _setSQL to set the query. The number of rows exported is limited from gSQLMaxRows variable.
The method uses the setPdfOptions to set various PDF options. See below.

Parameters:

  • array $summary: - set which columns should be sumarized in order to be displayed to the grid By default this parameter uses SQL SUM function: array("colmodelname"=>"sqlname"); It can be set to use the other one this way array("colmodelname"=>array("sqlname"=>"AVG")); By default the first field correspond to the name of colModel the second to the database name
  • array $params: parameter values passed to the SQL if the query is with parameters
  • array $colmodel: - diffrent descriptions for the headars, width, hidden cols This array is actually a colModel array in jqGrid. The array can look like Array( [0]=>Array("label"=>"Some label", "width"=>100, "hidden"=>true, "name"=>"client_id", "formatter"=>"select", editoptions=>...), [1]=>Array("label"=>"Other label", "width"=>80, "hidden"=>false, "name"=>"date",... ), ... )
  • string $filename: the filename to which the export can be saved

getDbDate( )

Return the current date format used in the undelayed database. The default format is 'Y-m-d'

API Tags:
Access: public

getDbTime( )

Return the current datetime format used in the undelayed database. The default format is 'Y-m-d H:i:s'

API Tags:
Access: public

getGridParams( )

Return the associative array which contain the parameters that are sended from the grid to request, search, update delete data. These parameters correspond to the prmNames objec in jqGrid Java Script library

API Tags:
Access: public

getUserDate( )

Return the current date format used from the client. The default format is 'd/m/Y'

API Tags:
Access: public

getUserTime( )

Return the current date format used from the client. The default format is 'd/m/Y H:i:s'

API Tags:
Access: public

queryGrid( [ $summary = null], [ $params = null], [boolen $echo = true] )

Return the result of the query to jqGrid. Support searching,paging, sorting. Also support summarized rows. Note that this method output the result in name:value pair. With other words the repeatitems parameter in json or xml reader in jqGrid should be set to false.

Parameters:

  • array $summary: - set which columns should be sumarized in order to be displayed to the grid By default this parameter uses SQL SUM function: array("colmodelname"=>"sqlname"); It can be set to use the other one this way array("colmodelname"=>array("sqlname"=>"AVG")); By default the first field correspond to the name of colModel the second to the database name
  • array $params: - parameter values passed to the sql
  • boolen $echo: if set to false return the records as object, otherwiese json encoded or xml string depending on the dataType variable

API Tags:
Access: public

querySubGrid( array $params )

Return the result of the query for the simple subgrid. The format (json or xml) depend of dataType variable
Parameters:

  • array $params: parameters passed to the query

API Tags:
Access: public

selectLimit( [$limsql = ''], [$nrows = -1], [$offset = -1], [ $params = null] )

Will select, getting rows from $offset (1-based), for $nrows.This simulates the MySQL "select * from table limit $offset,$nrows" , and the PostgreSQL "select * from table limit $nrows offset $offset". Note that MySQL and PostgreSQL parameter ordering is the opposite of the other. eg. Also supports Microsoft SQL Server SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) Return object containing the limited record set.

Parameters:

  • string $limsql: optional sql clause, if not set uses SelctCommand or table.
  • integer $nrows: is the number of rows to get
  • integer $offset: is the row to start calculations from (1-based)
  • array $params: array of bind variables

API Tags:
Access: public

setDbDate( string $newformat )

Set a new database date format using PHP convensions
Parameters:

  • string $newformat: - the new database format

API Tags:
Access: public

setDbTime( string $newformat )

Set a new database datetime format using PHP convensions
Parameters:

  • string $newformat: - the new database format

API Tags:
Access: public

setGridParams( array $_aparams )

Set a grid parameters to identify the action from the grid. Note that these should be set in the grid (prmNames) - i.e the parameters from the grid should equal to the GridParams.
Parameters:

  • array $_aparams: set new parameter.

API Tags:
Access: public

setPdfOptions( array $apdf )

Set options for PDF export.
Parameters:

  • array $_appdf: set new PDF parameters.

API Tags:
Access: public

The default PDF parammeters are stored in protected array and are listed below with the default values

array(
"page_orientation" => "P",
"unit"=>"mm",
"page_format"=>"A4",
"creator"=>"jqGrid",
"author"=>"jqGrid",
"title"=>"jqGrid PDF",
"subject"=>"Subject",
"keywords"=>"table, grid",
"margin_left"=>15,
"margin_top"=>7,
"margin_right"=>15,
"margin_bottom"=>25,
"margin_header"=>5,
"margin_footer"=>10,
"font_name_main"=>"helvetica",
"font_size_main"=>10,
"header_logo"=>"",
"header_logo_width"=>0,
"header_title"=>"",
"header_string"=>"",
"header"=>false,
"footer"=>true,
"font_monospaced"=>"courier",
"font_name_data"=>"helvetica",
"font_size_data"=>8,
"margin_footer"=>10,
"image_scale_ratio"=>1.25,
"grid_head_color"=>"#dfeffc",
"grid_head_text_color"=>"#2e6e9e",
"grid_draw_color"=>"#5c9ccc",
"grid_header_height"=>6,
"grid_row_color"=>"#ffffff",
"grid_row_text_color"=>"#000000",
"grid_row_height"=>5,
"grid_alternate_rows"=>false,
"path_to_pdf_class"=>"tcpdf/tcpdf.php",
"shrink_cell"=>true,
"reprint_grid_header"=>false
);

setSuccessMsg( string $msg )

Set a string which will be send to the grid if the operation after add, edit or del is successfull.
Parameters:

  • string $msg: - message send to the grid

API Tags:
Access: public

setUserTime( string $newformat )

Set a new user datetime format using PHP convensions
Parameters:

  • string $newformat: - the new format

API Tags:
Access: public
Last Updated: 07/15/11 | © TriRand Ltd., 2011


 Passing parameters
Passing parameters
In most cases the SQL should obtain dynamically parameters from other variables. This mean that the query should be parametrized. As can be seen this can be done in the same query, but we highly recommend to use the jqGrid feature to pass the parameter values to the method and not to build your own query.
The reason for this is that the query is prepared before it is executed and the parameters are bound to the query for performance and security reasons (e.g in order to prevent SQL Injection attacks)

Related methods

exportToExcel
queryGrid
querySubGrid
editGrid
renderGrid

In order to ilustrate how this can be done We will use the example we have used before. Let say that we want to display the rows with OrderID bigger than a certain number (session variable) which should be set before executing the script.The script can look like this:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// get the variable
$param1 = $_SESSION['ordernum'];

// Create the jqGrid instance
$grid = new jqGrid($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders WHERE OrderID > ? ';

$grid->dataType = "json";

// pass the parameter
$grid->queryGrid(null, array($param1));
?>

All the parameters should be passed whitin an array and the number of the placeholders ? should equal the length of the array.
You can pass as many parameters as you want.

As you can see the array is passed as second argument of the queryGrid method.

Last Updated: 06/12/10 | © TriRand Ltd., 2011


 Queries
Queries
There are situations where the query should be diffrent depending on different conditions. In order to do that we can:

  • Use read query from an XML file.
  • Use SelectCommant
  • Use table

Related methods

exportToExcel
queryGrid
editGrid
renderGrid

The ralated public variables

$readFromXML
$SelectCommand
$table

The logic in which the methods read the query is:
- First we look if the $readFromXML variable is set to true. If the variable is true we read the query from the XML file (see below).
- If the $readFromXML is false we look at $SelectCommand.
- If the $SelectCommand is empty at end we look for $table

Read query from XML

In order to read the query from XML we should use two variables - $readFromXML and $SelectCommand. The $readFromXML should be set to true and the $SelectCommand should meet some conditions. These are as follows:

SelectCommand should be set as xmlfile.sqlid. The xmlfile is the name of xml file where we store the sql commands, sqlid is the id of the required sql.

Note The xmlfile set in the SelectCommand should not end with xml, but the same file should have xml extension

The xml file should have the following structure

 < ?xml version="1.0" encoding="UTF-8"?>
 <queries>
     <sql Id="getUserById">
        Select ..  From ..  Where ...
    </sql>
    <sql Id="validateUser">
        Select   From  Where
    </sql>
     ...
 </queries>

Let suppose that we want not to display the Freight field (Using our example) if the user belogs to a group greater than 3.

Create a file groupright.xml which should look like this:

< ?xml version="1.0" encoding="UTF-8"?>
 <queries>
     <sql Id="allfields">
        SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders
    </sql>
    <sql Id="limitedfields">
        SELECT OrderID, OrderDate, CustomerID, ShipName FROM orders
    </sql>
     ...
 </queries>

Save the file in certain location and write the following PHP script

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

$group = $_SESSION['usergroup'];

// Create the jqGrid instance
$grid = new jqGrid($conn);
// Enable reading from XML
$grid->readFromXML = true;

// Set the query based on the condition
if($group <= 3)
    $grid->SelectCommand = 'pathtothefile/groupright.allfields';
else
    $grid->SelectCommand = 'pathtothefile/groupright.limitedfields';

$grid->dataType = "json";
$grid->queryGrid();
?>

Last Updated: 01/09/11 | © TriRand Ltd., 2011


 Searching
Searching
Searching is supported out of the box in all methods listed below . The component supports both single search and multiple searching.
The exception here is that when the grid is used in configuration with queryGrid, editGrid and exportToExcel as separate methods the filterToolbar method in jqGrid Javascript lib should be configured to post the search values as string. You can see details of that below.

Related methods

exportToExcel
queryGrid
editGrid
renderGrid

Below is an example how to configure filterToolbar to be synchronized with the queryGrid, editGrid and exportToExcel methods.
Using again our example the code can look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate"},
     {"name":"CustomerID","index":"CustomerID"},
     {"name":"Freight","index":"Freight"},
     {"name":"ShipName","index":"ShipName"}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager"
});
// Set filterToolbar to post the search parameters as string
jQuery("#grid").jqGrid('filterToolbar',{stringResult: true});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

There is no need to change any PHP code.

Last Updated: 09/13/10 | © TriRand Ltd., 2011


 Working with dates
Working with dates
jqGrid provides an elegant way to work with dates. The reason for this special handling is that the date format that the underlaying database accepts in most cases differs from those presented on the client side. If you use Microsoft SQL Server please refer here if you work with dates.

We consider two types of dates - Date and DateTime.
The default format of Date and DateTime types on the server-side is Y-m-d for date and Y-m-d H:i:s for datetime.
The default format of Date and DateTime types on the client-side(javascript) is d/m/Y and d/m/Y H:i:s
For more information on date formatting in PHP, please refer to here

You can change these formats using the following methods:
setDbDate
setDbTime

for the underlying database and
setUserDate
setUserTime

for the client side representation.

In order to synchronize date formats between the client and server, a datearray variable should be used.
This is an array which tells the script which fields are dates. The value(s) in the array should correspond to the name in colModel This conversion is used when a search or CRUD (create, read, update, delete) operations are performed

In order to ilistrate this we again will refere to rhis example.

Let's suppose that the date format accepted from the server is Y-m-d and at client the format should be m/d/Y.
In order to display and search correctly the html file should be changed this way.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate", "formatter":"date", "formatoptions":{"srcformat":"Y-m-d", "newformat":"m/d/Y"} },
     {"name":"CustomerID","index":"CustomerID"},
     {"name":"Freight","index":"Freight"},
     {"name":"ShipName","index":"ShipName"}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager"
});
// Set navigator with search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:false,del:false});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

The changes in PHP script should be:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGrid instance
$grid = new jqGrid($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';

// set the user date format to m/d/Y
$grid->setUserDate('m/d/Y');

// tell the grid which field is date
$grid->datearray = array('OrderDate');

$grid->dataType = "json";
$grid->queryGrid();
?>

That is all. Now your display and search will be correct.

Related methods

exportToExcel
queryGrid
editGrid
renderGrid
getDbDate
getDbTime
setDbDate
setDbTime
getUsedDate
getUserTime
setUserDate
setUserTime

Related variables

datearray
Last Updated: 09/13/10 | © TriRand Ltd., 2011


 Summary Fields
Summary Fields
Summary fields is another useful feature of the grid. The purpose of this feature is to display diffrent statistical information in the footer row of the grid. The default summary operation is the SUM (summary) SQL function, but you can use any other supported funciton like AVG (average), MIN, MAX, etc. There is no special variable in the grid that conrols this behavior. The summary array should be passed directly to the methods listed below with a parameter named $summary

The structure of the array is:

array("colname"=>"databaseexp")

or

array("colname"=>array("databaseexp"=>"operation"));

where

  • colname is the name corresponding to the name in colModel
  • databaseexp is either database field or database expresion like field1+field2
  • operation is the database statistical function like SUM, AVG, MIN, MAX, COUNT...

If "operation" is not explicitly used, we asumme that SUM function is used.

For example, if your SQL statement looks like this:

$grid->SelectCommand = "SELECT a, b , c+d AS e FROM table";

and you want the summary of c and d field to be displayed in the grid, the array should like this

$mysumarray = array('e'=>array("c+d"=>"SUM"));

Related methods

exportToExcel
queryGrid
editGrid
renderGrid

Let's ilustrate this again using this example.

Our goal is to display the average of the Freight field in the footer of the column:
The html code should be:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate"},
     {"name":"CustomerID","index":"CustomerID"},
     {"name":"Freight","index":"Freight"},
     {"name":"ShipName","index":"ShipName"}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager",
"footerrow":true,
"userDataOnFooter": true
});
// Set navigator with search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:false,del:false});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

Note the two additional settings in the grid definition - footerrow and userDataOnFooter. The first setting enables the footer row the second uses the userData array to put the values on the footer row.

The PHP code should be:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGrid instance
$grid = new jqGrid($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
$grid->dataType = "json";

$avg = array('Freight'=>array('Freight'=>'AVG'));

// pass the avg array to the grid
$grid->queryGrid($avg);
?>

Last Updated: 06/24/10 | © TriRand Ltd., 2011


 Working with different charset
Working with different charset
By default jqGrid is configured to work with utf-8 charset, but in some cases this is not applicable for existing legacy aplications. In order to work with charset diffrent than utf-8, you need to change is the $encoding variable.

However, the are a few steps that you need to do in addition to that to make sure everything works as expected:

1. In the html or php file where the grid is constructed, the appropriate meta tag should be set.

...
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
...
</head>
...

2. The connection command to the database should be set in order characters to be displayed properly

For MySQL and PostgreSQL this is a

SET NAMES 'charset'

This command should be executed before interacting with the grid.

For Microsoft SQL Server the connection info string should contain the charset setting as well:

<?php
// Example connection
$connectionInfo = array("UID" => 'user', "PWD" => 'password',"Database"=>"test", "CharacterSet" => "windows-1251", "ReturnDatesAsStrings" => true);
$serverName = "localhost\SQLEXPRESS";
$conn = sqlsrv_connect( $serverName, $connectionInfo);
...
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the SQL Server driver class
require_once "php/jqGridSqlsrv.php";
...
?>

3. And at end we should set $encoding variable in the grid. When this command is set the grid executes a PHP header function to send the appropriate header to the browser and more importantly - in case of 'json' output uses his own encode (when charset is <> utf-8). This is need because the built-in PHP functions for json encoding and decoding are utf-8 compatible only.

Related methods

exportToExcel
queryGrid
querySubGrid
editGrid
renderGrid

Related variable(s)

encoding

Again we ilustrate this with example. Let suppose that the database is encoded in windows-1251 charset. Using our example

Changes in the html file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
<title>PHP jqGrid Class Example</title>
...

The changes in the PHP script:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// perform the set names command
$conn->query("SET NAMES cp1251");

// Create the jqGrid instance
$grid = new jqGrid($conn);

// Set the encoding
$grid->encoding = "windows-1251";

// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
$grid->dataType = "json";
$grid->queryGrid();
?>

Last Updated: 09/13/10 | © TriRand Ltd., 2011


 Export to Excel
Export to Excel
Exporting to Excel is another useful feature of jqGrid. It is important to note the the generated file is not plain CSV (comma separated values) file, but Microsoft Excel XML file. The reason for that is that in diffrent client machines the variables of type "Date" and "DateTime" and long numbers are not displayed correctly when CSV is used. Using XML file with the appropriate field types makes the file portable to all client machines without loss of information.

Moreover, when summary rows (footer formula) are used, the grid creates a formula and the summary fields are displayed at end of the file.

When this method is used within jqGrid and jqGridEdit classes they should be called separatley in order to perform the export.
When used in jqGridRender class everthing is done automatically when the export to excel is enabled.

Also when used separatley and you want to display diffrent header, width and hide some fields a colmodel array should be configured and passed as parameter to the method. If none is set in this case only column names are used

The array has the following structure and properties

Array(
    [0]=>Array("label"=>"Some label", "width"=>100, "hidden"=>true, "name"=>"colname"),
    [1]=>Array(...),
     ...
);

Where

  • label is the header displayed for this field
  • width is the width in pixels
  • hidden (boolean) if set does not export this column
  • name is the name from column model

If set the length of this array should be equal to the number of fields in the SQL command used.

Related Methods

exportToExcel
renderGrid

Related variable(s)

gSQLMaxRows
ExportCommand

Example:
Let suppose that when we export to excel we want to show additionally the ShipAddress and ShipCity and perform a summary on the field Freight. We will use again our example.
For this purpose we will first create a custom button in the navigator and use the build in method for this purpose excelExport. The method is avialble since version 3.6.3 of jqGrid Java Script lib. When used the method passes additinally a variable oper=excel to identify that we want a export to Excel.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate"},
     {"name":"CustomerID","index":"CustomerID"},
     {"name":"Freight","index":"Freight"},
     {"name":"ShipName","index":"ShipName"}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager"
});
// Set navigator with search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:false,del:false});

// add custom button to export the data to excel
jQuery("#grid").jqGrid('navButtonAdd','#pager',{
       caption:"",
       onClickButton : function () {
           jQuery("#grid").excelExport();
       }
});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

In PHP code we will use ExportCommand to perform the export.

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGrid instance
$grid = new jqGrid($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';

// we want to export additinal data when excel
$grid->ExportCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName, ShipAddress, ShipCity FROM orders';

$grid->dataType = "json";

// now we should check whenever a export is lunched
$export = $_POST['oper'];

if($export == 'excel')
    // let set summary field
   $grid->exportToExcel(array('Freight'=>'Freight'));
else
   $grid->queryGrid();
?>

Last Updated: 06/07/11 | © TriRand Ltd., 2011


 Export to Pdf
Export to Pdf
Similar to export to Excel export to PDF is another useful feature of jqGrid.
When summary rows (footer formula) are used, the grid creates a formula and the summary fields are displayed at end of the file.

When this method is used within jqGrid and jqGridEdit classes they should be called separatley in order to perform the export.
When used in jqGridRender class everthing is done automatically when the export to pdf is enabled.

Also when used separatley and you want to display diffrent header, width and hide some fields a colmodel array should be configured and passed as parameter to the method. If none is set in this case only column names are used

The array has the following structure and properties

Array(
[0]=>Array("label"=>"Some label", "width"=>100, "hidden"=>true, "name"=>"colname"),
[1]=>Array(...),
...
);
Where

  • label is the header displayed for this field
  • width is the width in pixels
  • hidden (boolean) if set does not export this column
  • name is the name from column model

If set the length of this array should be equal to the number of fields in the SQL command used.

This method uses a TCP PDF library www.tcpdf.org. The library is a part from the download package and usually you will need to do nothing (in sence to include some files) in order to perform export to PDF.
The PDF class is placed in the pdf subdir of the package. If the pdf subdirectory is not suitable for you needs, you can change it place. In this case the "path_to_pdf_class" should be changed according to the new place.
This can be done using the setPdfOptions method (see below).

By default the download package contain only one UTF font - freeserif (except the standart non UTF).
This font should be set using setPdfOptions(..) method. The names connected with this are font_name_main and font_name_data plus font_monospaced
A dejavupack can be downloaded from here: DejavuPack
To have more fonts please download the font pack from TCPPDF site and set the appropriate name in the setPdfOptions as described above

Related Methods

exportToPdf
setPdfOptions
renderGrid

Related variable(s)

PDF
gSQLMaxRows
ExportCommand

As can be seen we have one important private array variable $PDF, where all the export options are stored.
Direct the values of this array can not be changed. This ia done with the method stPdfOptions whch paramater is array.

Example:
We can change the path to pdf class this way.

$grid = new jqGridRender($conn) // or $grid = new jqGridQuery($conn);
...
$grid->setPdfOptions(array("path_to_pdf_class"=>"mynewdir/tcpdf.php"));

Below we list all the possible options and the related values to it.

$PDF = array(
"page_orientation" => "P",
"unit"=>"mm",
"page_format"=>"A4",
"creator"=>"jqGrid",
"author"=>"jqGrid",
"title"=>"jqGrid PDF",
"subject"=>"Subject",
"keywords"=>"table, grid",
"margin_left"=>15,
"margin_top"=>7,
"margin_right"=>15,
"margin_bottom"=>25,
"margin_header"=>5,
"margin_footer"=>10,
"font_name_main"=>"helvetica",
"font_size_main"=>10,
"header_logo"=>"",
"header_logo_width"=>0,
"header_title"=>"",
"header_string"=>"",
"header"=>false,
"footer"=>true,
"font_monospaced"=>"courier",
"font_name_data"=>"helvetica",
"font_size_data"=>8,
"margin_footer"=>10,
"image_scale_ratio"=>1.25,
"grid_head_color"=>"#dfeffc",
"grid_head_text_color"=>"#2e6e9e",
"grid_draw_color"=>"#5c9ccc",
"grid_header_height"=>6,
"grid_row_color"=>"#ffffff",
"grid_row_text_color"=>"#000000",
"grid_row_height"=>5,
"grid_alternate_rows"=>false,
"path_to_pdf_class"=>"tcpdf/tcpdf.php",
"shrink_cell"=>true,
"reprint_grid_header"=>false
);

Option | Description | Values | Default
page_orientation | Determines the orientation of the page. Can be Portrait or Landscape | P - Portrait; L - Landscape | P (Portrait)
unit | Set the measure of the export. Note that if you change this value all the related options which contain measures (except pixels) should be changed in the appropriate way | mm - Millimeters, cm- Centimeters, in - Inchs, pt-Point | mm (Millimetters)
page_format | Set various format of the page. | A, B, C, E, G (from 0 - 12), USLETTER, LETTER and a lot of otther formats | A4
creator | Set the creator of the pdf document | Any string | jqGrid
author | Set the author of the document | Any string | jqGrid
title | Set the title of the document. This is the title when see the properties of the document. | Any String | jqGrid PDF
subject | Set the subject of the document | Any string | Subject
keywords | Set the kyewords for the document | Any string | table, grid
margin_left | set the left margin of the page in measurment defined in unit option | Number | 15
margin_top | set the top margin of the page in measurment defined in unit option | Number | 7
margin_right | set the right margin of the page in measurment defined in unit option | Number | 15
margin_bottom | set the bottom margin of the page in measurment defined in unit option | Number | 25
margin_header | set the header margin of the page in measurment defined in unit option | Number | 25
margin_footer | set the footer margin of the page in measurment defined in unit option | Number | 25
font_name_main | Defines the main font. This font is used in the headers. | Any valid font name (as set in the font subdirectory) | helvetica
font_size_main | Defines the size of the font_name_main font. This font is used in the headers. | Number | 10
header_logo | If set defines the image which will be placed at the top left corner of the page. The image should be placed in the image directory of the pdf directory | Name of the image | Empty string
header_logo_width | Defines the width od the header image | Number | 0
header_title | Defines the the title which will be printed at top of the page near th image logo if defined | Any string | Empty string
header | Enables or disables the printing of the heder related data. Important: By default this option is disabled. If you want to print some header data it is a good idea to increase the margin_top option | true or false | false
footer | Enables or disables the printing of the footer related data. | true or false | true
font_monospaced | Defines the default monospaced font | Any valid font name | courier
font_name_data | Defines the font for the printing of the table data | Any valid font name | helvetica
font_size_data | Defines the size default monospaced font | Number | 8
margin_footer | Defines the margin of the footer in measurment defined in unit option | Number | 10
grid_head_color | Defines the table header color background | Color defined as html value | #dfeffc
grid_head_text_color | Defines the table header text color | Color defined as html value | #2e6e9e
grid_draw_color | Defines the table border color | Color defined as html value | #5c9ccc
grid_header_height | Defines the height of the table header data in measurmen defined in unit | Color defined as html value | 6
grid_row_color | Defines the table row color background | Color defined as html value | #ffffff
grid_row_text_color | Defines the table row text color | Color defined as html value | #000000
grid_row_height | Defines the height of the table row data in measurmen defined in unit | Color defined as html value | 5
grid_alternate_rows | Enable or disable zebra striping in the export | true or false | false
path_to_pdf_class | Set the path and filename to the tcpdf class. | String | tcpdf/tcpdf.php
shrink_cell | If set to false the Font does not increase so that to fit the text in width, but a new line is added if needed. | boolean | true
reprint_grid_header | If set to true the grid header row is reprinted on every new page. Note: This option currently work only if the pdf option "shrink_cell" is set to false | boolean | false

Example:
This example will be the same as the Export to Excel Example, but this time we will export the data in PDF file
Let suppose that when we export to PDF we want to show additionally the ShipAddress and ShipCity and perform a summary on the field Freight. We will use again our example.
For this purpose we will first create a custom button in the navigator and use the build in method for this purpose excelExport with tag set to pdf. The method is avialble since version 3.6.3 of jqGrid Java Script lib. When used the method passes additinally a variable oper={tag} to identify that we want a export to a different formats.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate"},
     {"name":"CustomerID","index":"CustomerID"},
     {"name":"Freight","index":"Freight"},
     {"name":"ShipName","index":"ShipName"}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager"
});
// Set navigator with search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:false,del:false});

// add custom button to export the data to excel
jQuery("#grid").jqGrid('navButtonAdd','#pager',{
       caption:"",
       onClickButton : function () {
           jQuery("#grid").jqGrid('excelExport',{tag:"pdf"});
       }
});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

In PHP code we will use ExportCommand to perform the export.

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGrid instance
$grid = new jqGrid($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';

// we want to export additinal data when excel
$grid->ExportCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName, ShipAddress, ShipCity FROM orders';

$grid->dataType = "json";

// now we should check whenever a export is lunched
$export = $_POST['oper'];

if($export == 'pdf')
    // let set summary field
   $grid->exportToPdf(array('Freight'=>'Freight'));
else
   $grid->queryGrid();
?>
Last Updated: 07/15/11 | © TriRand Ltd., 2011


 Export to CSV
Export to CSV
Similar to export to Excel export to CSV (Comma Separated Value) is another useful feature of jqGrid.
When summary rows (footer formula) are used, the grid creates a formula and the summary fields are displayed at end of the file.

When this method is used within jqGrid and jqGridEdit classes they should be called separatley in order to perform the export.

When used in jqGridRender class everthing is done automatically when the export to csv is enabled.

Also when used separatley and you want to display diffrent header and hide some fields a colmodel array should be configured and passed as parameter to the method. If none is set in this case only column names are used

The array has the following structure and properties

Array(
[0]=>Array("label"=>"Some label", "hidden"=>true, "name"=>"colname"),
[1]=>Array(...),
...
);
Where

  • label is the header displayed for this field
  • hidden (boolean) if set does not export this column
  • name is the name from column model

If set the length of this array should be equal to the number of fields in the SQL command used.

Mainly the method should be used when export to excel is not applicable or there is a need to exchange data in standart CSV way.

Related Methods

exportToCsv
renderGrid

Related variable(s)

gSQLMaxRows
ExportCommand

Hint - If you want to export to a tab delimited file set the separator variable to \t - i.e.

$grid->exportToCsv( null, null, null, true, 'exportdata.csv', '\t' );

Example:
This example is the same as export to excelexample, but this time we will export to CSV data

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate"},
     {"name":"CustomerID","index":"CustomerID"},
     {"name":"Freight","index":"Freight"},
     {"name":"ShipName","index":"ShipName"}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager"
});
// Set navigator with search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:false,del:false});

// add custom button to export the data to excel
jQuery("#grid").jqGrid('navButtonAdd','#pager',{
       caption:"",
       onClickButton : function () {
           jQuery("#grid").jqGrid('excelExport',{tag:csv});
       }
});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

In PHP code we will use ExportCommand to perform the export.

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGrid instance
$grid = new jqGrid($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';

// we want to export additinal data when excel
$grid->ExportCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName, ShipAddress, ShipCity FROM orders';

$grid->dataType = "json";

// now we should check whenever a export is lunched
$export = $_POST['oper'];

if($export == 'csv')
    // let set summary field
   $grid->exportToCsv(array('Freight'=>'Freight'));
else
   $grid->queryGrid();
?>

Last Updated: 11/06/10 | © TriRand Ltd., 2011


 Simple Subgrid
Simple Subgrid
Simple Subgrid (only for viewing subgrid data) is supported throght the querySubGrid method. The method just outputs the data in format acceptable for the grid.

Related Method(s)

querySubGrid

Related variable(s)

SubgridCommand
dataType

Example:
Again using our example let say that we want to display in subgrid the order details.
For this purpose we need first to enable subGrid with the appropriate parameters and create additional PHP file which will deliver the desired data to the subgrid.

The html file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate"},
     {"name":"CustomerID","index":"CustomerID"},
     {"name":"Freight","index":"Freight"},
     {"name":"ShipName","index":"ShipName"}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager",

// changes for the subgrid
"subGrid": true,
"subGridUrl": "subgrid.php",
"subGridModel" : [ {
name: ['OrderID', 'ProductID', 'Quantity', 'UnitPrice'],
params: ['OrderID']
} ]
// end of changes for subgrid

});
// Set navigator with search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:false,del:false});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

Note that we send additinal parameter OrderID to the SubGrid url in order to identify which order to display.
Let create the new file named subgrid.php with the following content:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once 'php/jqGrid.php';
// include the driver class
require_once 'php/jqGridPdo.php';
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
// Get the needed parameters passed from the main grid
$rowid = jqGridUtils::Strip($_REQUEST["OrderID"]);

// Create the base jqGrid instance
$grid = new jqGrid($conn);
// Write the SQL Query
$grid->SubgridCommand = "SELECT OrderID, ProductID, Quantity, UnitPrice FROM order_details WHERE orderID=?";
// set the ouput format to json
$grid->dataType = 'json';
// Use the build in function for the simple subgrid
$grid->querySubGrid(array(&$rowid));
$conn = null;
?>
Last Updated: 09/13/10 | © TriRand Ltd., 2011


 Debugging
Debugging
Sometimes there are situations where something is wrong and the code does not work in a way that we want. For this purpose we have introduced a mini debugger, which tell us waht is happen with the grid.

To enable this feature the public variable debug should be set to true.
When this variable is enabled a file named jqGrid.log is created in the directory where your script reside.
In order to ilustarte this we again will use our example.

There is no special requierment wheere to put the debug option. It should just be called after the grid is created.

Now the PHP code should look like this

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGrid instance
$grid = new jqGrid($conn);
// enable debugging
$grid->debug = true;
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
$grid->dataType = "json";
$grid->queryGrid();
?>

After runnig the html file a file jqGrid.log will be created with the following structure:

Executed 2 query(s) - 2010-02-13 16:39:34
Array
(
    [0] => Array
        (
            [time] => 2010-02-13 16:39:34
            [query] => SELECT COUNT(*) AS COUNT  FROM orders
            [data] =>
            [types] =>
            [fields] =>
            [primary] =>
            [input] =>
        )

    [1] => Array
        (
            [time] => 2010-02-13 16:39:34
            [query] => SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders ORDER BY OrderID asc LIMIT 0, 10
            [data] =>
            [types] =>
            [fields] =>
            [primary] =>
            [input] =>
        )

)

This tell us that when the script is called two queries are executed.
Below we will explain every item in the query.

  • [time] is the timestamp of the query execution
  • [query] is the executed query. If a parameters are speciefied the query will contain the placeholder ?
  • [data] is array with the actual values that are passed in the place of the parameters
  • [types] is array that contain the field types (like integer, string) when a CRUD operations are performed This is valid only when jqGridEdit and jqGridRender classes are used.
  • [fields] is array containing diffretent information for the fields when a CRUD operations are performed This is valid only when jqGridEdit and jqGridRender classes are used.
  • [primary] is a string which tell us the name of the paimary key when a CRUD operations are performed This is valid only when jqGridEdit and jqGridRender classes are used.
  • [input] is associative array with the input values (data to be inserted, updated, deleted) when a CRUD operations are performed This is valid only when jqGridEdit and jqGridRender classes are used.
Last Updated: 01/10/11 | © TriRand Ltd., 2011


 jqGridEdit Class
jqGridEdit Class

The jqGridEdit class extends jqGrid class. All functionality that the jqGrid class exposes is also available in the jqGridEdit class.

The main purpose of this class is to perform CRUD (Create, Retrieve, Update, Delete) operations automatically. These operations can be performaned only when a database table is defined and associated with the jqGrid intance. Another important thing to note is that the table must have at least one primary unique key. The key can be any table column with unique value and/or serial key (also known as autoincrement in most databases like MySQL for example).

Using this class requires some javascript knowledge, since the grid should be created in an existing html or php page with javascript declaration. In other words, the jqGridEdit class will only take care of the server side operations, while all other events and operations at the client side can be defined manually by the developer. More information on jqGrid javascript documentation can be found here
.

Last Updated: 07/15/11 | © TriRand Ltd., 2011


 Variables
Variables
List of variables that can be used with this class. The class also provides all inherited variables from its base jqGrid class

Type | Names | Description | Default | Access
boolean | $add | Enable/Disable inserting a record into the table. Have sense only if used with editGrid method | true | public
boolean | $decodeinput | Enable/Disable decoding the input for update and insert operations using the html_entity_decode. The option should be used when the grid option autoencode is set to true. | false | public
boolean | $del | Enable/Disable deleting a record in table. Have sense only if used with editGrid method | true | public
boolean | $edit | Enable/Disable updating a record into the table. Have sense only if used with editGrid method | true | public
string | $mtype | Determines haw the input data should be accepted. Can be GET or POST | POST | public
booean | $serialKey | Defines if the primary key is serial (autoincrement) | true | public
boolean | $trans | If the option is set to true every CRUD is enclosed in transaction | true | public

Last Updated: 03/18/11 | © TriRand Ltd., 2011


 Public Methods
Public Methods
Othe public methods that can be used within this calss can be seen jqGrid Class Methods:

delete( $data )

Delete the data into the database according the table element. A primaryKey should be set. If the key is not set It can be obtained from jqGridDB::getPrimaryKey Return true on success, false when the operation is not succefull

Parameters:

  • array $data: associative array which key values correspond to the names in the table

API Tags:
Access: public

editGrid( [ $summary = null], [ $params = null], [string $oper = false] )

Perform the all CRUD operations depending on the oper param send from the grid (oper option, which by default is add,edit,delete) and the table element If the primaryKey is not set we try to obtain it using jqGridDB::getPrimaryKey If the primary key is not set or can not be obtained the operation is aborted.
Also the method call the queryGrid to perform the grid ouput

Parameters:

  • array $summary: - set which columns should be sumarized in order to be displayed to the grid. See here
  • array $params: additional parameters that can be passed to the query. See here
  • string $oper: if set the requested oper operation is performed without to check the parameter sended from the grid.

API Tags:
Access: public

getFields( )

Return array of the table fields generated for CRUD operations. Should be used after insert, update, delete. Mainly can be used for debugging purposes

API Tags:
Access: public

getPrimaryKeyId( )

Return the primary key of the table

API Tags:
Access: public

insert( array $data )

Insert the data array into the database according to the table element. A primaryKey should be set. If the key is not set It can be obtained from jqGridDB::getPrimaryKey Return true on succes, false otherwiese.
Parameters:

  • array $data: associative array which keys correspond to the names and values to be insered into the table.

API Tags:
Access: public

setAfterCrudAction( string $oper, string $sql, array $param )

Run sql command(s) after a CRUD operation (add, edit, del) is succesfull.
Can run unlimeted command
Parameters:

  • string $oper: the operation after which the sql query should be run can be 'add', 'edit', 'del'
  • string $sql: the sql command to be run
  • array $param: paremeters passed to the sql query

API Tags:
Access: public

setBeforeCrudAction( string $oper, string $sql, array $param )

Run sql command(s) before a CRUD operation (add, edit, del). If for some reason this operation fail all other operation in the transaction are ignored.
Can run unlimeted commands
Parameters:

  • string $oper: the operation after which the sql query should be run can be 'add', 'edit', 'del'
  • string $sql: the sql command to be run
  • array $param: paremeters passed to the sql query

API Tags:
Access: public

setPrimaryKeyId( string $keyid )

Set a primary key for the table
Parameters:

  • string $keyid: the praymery key to be set.

API Tags:
Access: public

setTable( string $_newtable )

Set table for CRUD operations
Parameters:
  • string $_newtable: a table to be used for CRUD. Also the method use the public variable $table.

API Tags:
Access: public

update( array $data )

Update the data into the database according the table element. A primaryKey should be set. If the key is not set It can be obtained from jqGridDB::getPrimaryKey Return true on success, false when the operation is not succefull
Parameters:

  • array $data: associative array which key values correspond to the names in the table

API Tags:
Access: public
Last Updated: 07/15/11 | © TriRand Ltd., 2011


 Inserting
Inserting
Inserting a record into the database table with jqGridEdit class is quite easy. Three things should be done - specify a table, set the parimary key (optional specify if the primary key is serial) and and call the method insert with the data posted from the grid.

It is important to note that the data array passed for inserting should contain key elements which correspond to the names in the table. In terms of jqGrid this is a name property in colModel.

We will demontrate this with example. We will use as base our example:

Let suppose that we want only to insert a record in the orders table. For this purpose we will use the navigator and into the navigator we will enable only add form. Here is the code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate", editable:true},
     {"name":"CustomerID","index":"CustomerID", editable:true},
     {"name":"Freight","index":"Freight", editable:true},
     {"name":"ShipName","index":"ShipName", editable:true}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager",
// now we should set the url where we post the data
// in this case the same url
"editurl": "querygrid.php"
});
// Set navigator with adding record and search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:true,edit:false,del:false});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

As can be ssen we have made a lot of the fields editable setting the property of the grid editable to true.
Another important settings here is in the field OrderID. This field is field is not editable, because it is defined as serial in the database, so we do not need to post them to the server.
When we do this the field will not appear in the form where we add a data.

The changes in the PHP code:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGridEdit instance
$grid = new jqGridEdit($conn);

// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
$grid->dataType = "json";

// We should determine if we add a record.
// jqGrid send oper to identify the operation performed
// in this case we should check for add

$oper = $_POST['oper'];
if($oper == 'add') {
   $grid->table = 'orders';
   $grid->setPrimaryKeyId('OrderID');
   $data = $_POST;
   $grid->insert($data);
} else {
   $grid->queryGrid();
}
?>

Another usefull feature here is that you can insert on other table just set it after the first insert and primary key too and do the insert.
Something like this

<?php
...
$oper = $_POST['oper'];
if($oper == 'add') {
   $grid->table = 'orders';
   $grid->setPrimaryKeyId('OrderID');
   $data = $_POST;
   $grid->insert($data);

   $grid->table = 'othertable'
   $grid->setPrimaryKeyId('otherid');
   $grid->insert($otherdata);
} else {
   $grid->queryGrid();
}
?>

Last Updated: 02/14/10 | © TriRand Ltd., 2011


 Updating
Updating
Just like inserting updating is performed the same way.
We will demonstarte this with example. Note the changes in the html file.
First we will enable editing and second we will set the name of the id to be a OrderID.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate", editable:true},
     {"name":"CustomerID","index":"CustomerID", editable:true},
     {"name":"Freight","index":"Freight", editable:true},
     {"name":"ShipName","index":"ShipName", editable:true}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager",
// now we should set the url where we post the data
// in this case the same url
"editurl": "querygrid.php",

// tell the grid to post the OrderID as primary key

"prmNames":{"id":"OrderID"}

});
// Set navigator with editing record and search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:true,del:false});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

When we set "prmNames":{"id":"OrderID"} we tell the grid to post the value of the id and the name should be not id, but OrderID. This is true, since we set in the colModel key:true, which indicates that this is the id.

The related PHP code is

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGridEdit instance
$grid = new jqGridEdit($conn);

// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
$grid->dataType = "json";

// We should determine if we add a record.
// jqGrid send oper to identify the operation performed
// in this case we should check for add

$oper = $_POST['oper'];
if($oper == 'edit') {
   $grid->table = 'orders';
   $grid->setPrimaryKeyId('OrderID');
   $data = $_POST;
   $grid->update($data);
} else {
   $grid->queryGrid();
}
?>

Last Updated: 02/14/10 | © TriRand Ltd., 2011


 Deleting
Deleting
Just like inserting and updating deleting is used the same way.
The related example for this is as follow.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate", editable:true},
     {"name":"CustomerID","index":"CustomerID", editable:true},
     {"name":"Freight","index":"Freight", editable:true},
     {"name":"ShipName","index":"ShipName", editable:true}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager",
// now we should set the url where we post the data
// in this case the same url
"editurl": "querygrid.php",

// tell the grid to post the OrderID as primary key

"prmNames":{"id":"OrderID"}

});
// Set navigator with deleting and search enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:false,del:true});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

As can be seen we change only the options in navigator to support deleting

The related PHP code

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGridEdit instance
$grid = new jqGridEdit($conn);

// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
$grid->dataType = "json";

// We should determine if we add a record.
// jqGrid send oper to identify the operation performed
// in this case we should check for add

$oper = $_POST['oper'];
if($oper == 'edit') {
   $grid->table = 'orders';
   $grid->setPrimaryKeyId('OrderID');
   $data = $_POST;
   $grid->delete($data);
} else {
   $grid->queryGrid();
}
?>

Last Updated: 02/14/10 | © TriRand Ltd., 2011


 All in One
All in One
Knowing how to Insert, Update and Delete data it is very natural to have a method that combines all of these operations. The method is named editGrid and combines insert, update, delete and queryGrid methods in one place.

The method uses prmNames names grid options to identify in which mode we are and and do the appropriate operation.
Another feature of the method is that the primary key kan not be set. In case if the primary key is not set the method try to get the primary key of the table. If the primary key can not be obtained a error message is displayed and the CRUD operation is aborted.

Let suppose that we want to enable all the CRUD operations in the grid. The html code is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP jqGrid Class Example</title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
....
// Craeate the grid manually
jQuery("#grid").jqGrid({
"colModel":[
     {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true},
     {"name":"OrderDate","index":"OrderDate", editable:true},
     {"name":"CustomerID","index":"CustomerID", editable:true},
     {"name":"Freight","index":"Freight", editable:true},
     {"name":"ShipName","index":"ShipName", editable:true}
],
"url":"querygrid.php",
"datatype":"json",
"jsonReader":{repeatitems:false},
"pager":"#pager",
// now we should set the url where we post the data
// in this case the same url
"editurl": "querygrid.php",

// tell the grid to post the OrderID as primary key

"prmNames":{"id":"OrderID"}

});
// Set navigator with all operations enabled.
jQuery("#grid").jqGrid('navGrid','#pager',{add:true,edit:true,del:true});
......
});
</script>

</head>
<body>
......
<table id="grid"></table>
<div id="pager"></div>
.......
</body>
</html>

The appropriate PHP code is
<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqGridEdit instance
$grid = new jqGridEdit($conn);

// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
$grid->dataType = "json";

$grid->table = 'orders';
$grid->setPrimaryKeyId('OrderID');
$grid->editGrid();
?>

  Last Updated: 01/09/11 | © TriRand Ltd., 2011


 jqGridRender Class
jqGridRender Class

The jqGridRender Class is the most advanced and feature rich class jqGrid for PHP provides, aimed to do almost evething with the grid without writing any Javascript code. For users that want to write custom Javascript code we have developed a set of methods that can be used within PHP code.

The jqGridRender class extends the jqGridEdit Class (i.e. jqGrid Class too) . This mean that everthing that can be done with these classes is available in this class too.

Last Updated: 12/13/11 | © TriRand Ltd., 2011


 Variables
Variables
List of variables that can be used with this class again with these from jqGridEdit and jqGrid classes

Type | Names | Description | Default | Access
boolean | $export | Globally Enable/Disable export to Excel, Pdf, Csv | true | public
string | $exportfile | The default file name for export to excel | exportdata.xml | public
string | $pdffile | The export to file to PDF | exportdata.pdf | public
string | $csvfile | The export to file to CSV | exportdata.csv | public
string | $csvsep | Separator for CSV export | ';' | public
string | $csvsepreplace | CSV string to replavce separator when available in data | ' ' | public
boolean | $navigator | Enable/Disable a navigator buttons on the pager element | true | public
boolean | $toolbarfilter | Enable/Disable toolbar searching | true | public

Last Updated: 07/15/11 | © TriRand Ltd., 2011


 Methods
Methods
Othe public methods that can be used within this class can be seen jqGrid Class Methods:
and here in jqGrid Edit Class Methods

addCol( $aproperties, [mixed $position = 'last'] )

Add a column at the first or last position in the colModel and sets a certain properties to it

Parameters:

  • array $aproperties: data representing the column properties - including name, label...
  • string $position: can be first or last - default is first. If a number is set the column is added before the position corresponded to the position in colModel

API Tags:
Access: public

callGridMethod( string $grid, string $method, [ $aoptions = null] )

JavaScript code for execution of valid grid method. This code is putted after the creation of the grid.

Parameters:

  • string $grid: valid grid id should be putted as #mygrid
  • string $method: valid grid method
  • array $aoptions: contain the parameters passed to the method. Omit this parameter if the method does not have parameters

API Tags:
Access: public

getColModel( )

Return array of the generated colModel. Should be called after setColModel

API Tags:
Access: public

getGridOption( string $key )

Return a jqGrid option specified by the key, false if the option can not be found.
Parameters:
string $key: the name of the grid option

API Tags:
Access: public

renderGrid( [string $tblelement = ''], [string $pager = ''], [boolean $script = true], [ $summary = null], [ $params = null], [boolean $createtbl = false], [boolean $createpg = false], [boolean $echo = true] )

Main method which do allmost everthing for the grid. Construct the grid, perform CRUD operations, perform Query and serch operations, export to excel, set a jqGrid method, and javascript code

Parameters:

  • string $tblelement: the id of the table element to costrict the grid
  • string $pager: the id for the pager element
  • boolean $script: if set to true add a script tag before constructin the grid.
  • array $summary: - set which columns should be sumarized in order to be displayed to the grid
  • array $params: parameters passed to the query
  • boolean $createtbl: if set to true the table element is created automatically from this method. Default is false
  • boolean $createpg: if set to true the pager element is created automatically from this script. Default false.
  • boolean $echo: if set to false the function return the string representing the grid

API Tags:
Access: public

setAutocomplete( string $colname, [string $target = false], [mixed $data = ''], [array $options = null], [boolean $editing = true], [ $searching = false], boolean $seraching )

Construct autocompleter used in the grid. The autocomplete can be used in the editing modules or/and in search module.

Parameters:

  • string $colname: (requiered) valid colname in colModel
  • string $target: if set determines the input element on which the value will be set after the selection in the autocompleter
  • mixed $data: can be array or string which is the SQL command which is executed to obtain the values. The command can contain one, two or three fields. If the field in SQL command is one, then this this field will be displayed and setted as value in the element. If the fields in SQL command are two, then the second field will be displayed but the first will be setted as value in the element.
  • array $options: - array with options for the autocomplete. Can be all available options from jQuery UI autocomplete in pair name=>value. In case of events a "js:" tag should be added before the value. Additionally to this the following options can be used - cache, searchType, ajaxtype, itemLiength. For more info refer to docs.
  • boolean $editing: determines if the autocomplete should be used in editing modules. Deafult is true
  • boolean $seraching: determines if the autocomplete should be present in the search module. Deafult is true.
  • $searching:

API Tags:
Access: public
Uses: jqAutocomplete - class. This requiere to include jqAutocomplete.php in order to work

setButtonOptions( string $exptype , array $aoptions )

Set a various options for the buttons on the navigator bar like tite, caption , icon.
For the other CRUD buttons see parameters passed to the 'navigator'
Parameters:

  • string $exptype: The button which is placed in the pager. The name correspond of those of the navigator - can be excel, csv, pdf, columns.
  • array $aoptions: array containing the following keys - "caption", "title", "buttonicon"

API Tags:
Access: public

setColModel( [ $model = null], [ $params = null], [ $labels = null] )

Construct the column model of the grid. The model can be passed as array or constructed from the SQL Query . The method try to determine the primary key and if it is found set as key:true to the appropriate field. If the primary key can not be determined set the first field as key:true in the colModel. Return true on success.
Parameters:

  • array $model: if set construct the model ignoring the SQL command
  • array $params: parametters passed to the SQL query
  • array $labels: if this parameter is set the method set the labels in colModel. The array should be associative which key value correspond to the name of colModel

API Tags:
Access: public

setColProperty( mixed $colname, $aproperties )

Set a new property in the constructed colModel. Return true on success. Should be called after setColModel method.
Parameters:

  • mixed $colname: valid coulmn name or index in colModel
  • array $aproperties: the key name properties.

API Tags:
Access: public

setDatepicker( string $colname, [array $options = null], [boolean $editing = true], [ $searching = true], boolean $seraching )

Construct a pop up calender used in the grid. The datepicker can be used in the editing modules or/and in search module.

Parameters:

  • string $colname: (requiered) valid colname in colModel
  • array $options: - array with options for the datepicker. Can be all available options from jQuery UI datepicker in pair name=>value. In case of events a "js:" tag should be added before the value.
  • boolean $editing: determines if the datepicker should be used in editing modules. Deafult is true
  • boolean $seraching: determines if the datepicker should be present in the search module. Deafult is true.
  • $searching:

API Tags:
Access: public
Uses: jqCalender - class. This requiere to include jqCalender.php in order to work

setFilterOptions( array $aoptions )

Set options for the toolbar filter when enabled with $toolbarfilter
Parameters:

  • array $aoptions: valid options for the filterToolbar

API Tags:
Access: public

setGridEvent( string $event, string $code )

Set a valid grid event
Parameters:

  • string $event: - valid grid event
  • string $code: Javascript code which will be executed when the event raises

API Tags:
Access: public

setGridOptions( array $aoptions )

Set a grid options. The method uses array with keys correspondingto the jqGrid options as described in jqGrid docs

Parameters:

  • array $aoptions: A key name pair. Some options can be array to.

API Tags:
Access: public

setJSCode( string $code )

Put a javascript code after all things are created. The method is executed only once when the grid is created.
Parameters:
  • string $code: - javascript to be executed

API Tags:
Access: public

setNavEvent( string $module, string $event, string $code )

Set a event in the navigator or in the diffrent modules add,edit,del,view, search
Parameters:

  • string $module: - can be navigator, add, edit, del, view, search
  • string $event: - valid event for the particular module
  • string $code: - javascript code to be executed when the event occur

API Tags:
Access: public

setNavOptions( string $module, array $aoptions )

Set options in the navigator or in diffrent diffrent modules add,edit,del,view, search
Parameters:

  • string $module: - can be navigator, add, edit, del, view, search
  • array $aoptions: options that are applicable to this module The key correspond to the options in jqGrid

API Tags:
Access: public

setSelect( string $colname, mixed $data, [boolean $formatter = true], [boolean $editing = true], [boolean $seraching = true], [array $defvals = array()] )

Construct the html select used in the grid. The select element can be used in the editing modules, in formatter or in search module. The purpose of this method is to link other tables to desired filed.

Parameters:

  • string $colname: (requiered) valid colname in colModel
  • mixed $data: can be array (with pair key value) or string which is the SQL command which is executed to obtain the values. The command should contain a minimun two fields. The first is the key and the second is the value whch will be displayed in the select
  • boolean $formatter: deternines that the select should be used in the formatter of type select. Default is true
  • boolean $editing: determines if the select should be used in editing modules. Deafult is true
  • boolean $seraching: determines if the select should be present in the search module. Deafult is true.
  • array $defvals: Set the default value if none is selected. Typically this is usefull in serch modules. Can be something like arrary(""=>"All"); Note that this is puted only in the serch modules, but not in the editing one

API Tags:
Access: public

setSubGrid( [string $suburl = ''], [array $subnames = false], [array $subwidth = false], [array $subalign = false], [array $subparams = false] )

Prepares a executuion of a simple subgrid Return false if no subnames options are set
Parameters:

  • string $suburl: Url from where to get the data
  • array $subnames: Required - the names that should correspond to fields of the data
  • array $subwidth: (optional) - sets a width of the subgrid columns. Default 100
  • array $subalign: (optional) - set the aligmend of the columns. default center
  • array $subparams: (optional) additional parameters that can be passed when the subgrid plus icon is clicked. The names should be present in colModel in order to pass the values

API Tags:
Access: public

setSubGridGrid( string $suggridurl, array $subgridnames=null )

Prepares a subgrid in the grid expecting any valid html content provieded via the $suggridurl

Parameters:

  • string $suggridurl: url from where to get html content
  • array $subgridnames: array containing a valid names from the generated colModel. In this case a pair name value (name provided in the array and the value from the corresponding clicked row) is added to the url and posted to the server.

API Tags:
Access: public

setUrl( string $newurl )

Set a url for editing and the grid url from where to obtain the data.

Parameters:

  • string $newurl: the new url

API Tags:
Access: public
Last Updated: 12/13/11 | © TriRand Ltd., 2011


 Grid Options
Grid Options
For the Grid options a two methods can be used

getGridOption($key) to obtain the desired option
where $key is a name listed in the table below
and
setGridOption(array $aoptions) to set a new option(s)
where
$aoptions is array where multiple optins can be set.
The method can be called several times in order to set or overwrite existing option(s).

Example: If we want to change the width and the height of the grid we can write the code like this

<?php
...
// Create the jqGridRender instance
$grid = new jqGridRender($conn);
...
$grid->setGridOptions(array("width"=>500,"height"=>350));
...
$grid->renderGrid(...);
?>

The same code is equivalent

<?php
...
// Create the jqGridRender instance
$grid = new jqGridRender($conn);
...
$grid->setGridOptions(array("width"=>500));
$grid->setGridOptions(array("height"=>350));
...
$grid->renderGrid(...);
?>

Bellow is a list of all available grid options

Type

Name

Description

Default

array

ajaxGridOptions

This option allow to set global ajax settings for the grid when we request data. Note that with this option is possible to overwrite all current ajax setting in the grid including the error, complete and beforeSend events.

empty array

array

ajaxSelectOptions

This option allow to set global ajax settings for the select element when the select is obtained via dataUrl option in editoptions or searchoptions objects

empty array

string

altclass

The class that is used for alternate rows. You can construct your own class and replace this value. This option is valid only if altRows options is set to true

ui-priority-secondary

boolean

altRows

Set a zebra-striped grid

false

boolean

autoencode

When set to true encodes (html encode) the incoming (from server) and posted data (from editing modules). By example < will be converted and posted to &lt;

false

boolean

autowidth

When set to true, the grid width is recalculated automatically to the width of the parent element. This is done only initially when the grid is created. In order to resize the grid when the parent element changes width you should apply custom code and use a setGridWidth method for this purpose

false

string

caption

Defines the Caption layer for the grid. This caption appears above the Header layer. If the string is empty the caption does not appear.

empty string

integer

cellLayout

This option determines the padding + border width of the cell. Usually this should not be changed, but if custom changes to td element are made in the grid css file this will need to be changed. The initial value of 5 means paddingLef⇒2+paddingRight⇒2+borderLeft⇒1=5

5

boolean

cellEdit

Enables (disables) cell editing. See Cell Editing for more details

false

string

cellsubmit

Determines where the contents of the cell are saved: 'remote' or 'clientArray'. See Cell Editing for more details

'remote'

string

cellurl

the url where the cell is to be saved. See Cell Editing for more details

null

array

cmTemplate

A object which can overwrite the default values of all newly created columns. By example if you want that all columns in the grid should not be sortable set array("sortable"=>false) for this property and all columns will be not sortable when the grid is created.

null

array

colModel

Array which describes the parameters of the columns.This is the most important part of the grid. For a full description of all valid values see colModel API.

empty array

array

colNames

An array in which we place the names of the columns. This is the text that appears in the head of the grid (Header layer). The names are separated with commas. Note that the number of element in this array should be equal of the number elements in the colModel array.

empty array

string

datastr

The string of data when datatype parameter is set to xmlstring or jsonstring

null

string

datatype

Defines what type of information to expect to represent data in the grid. Valid options are xml - we expect xml data; xmlstring - we expect xml data as string; json - we expect JSON data; jsonstring - we expect JSON data as string; local - we expect data defined at client side (array data); javascript - we expect javascript as data; function - custom defined function for retrieving data. See colModel API and Retrieving Data

xml

boolean

deselectAfterSort

Applicable only when we use datatype : local. Deselects currently-selected row(s) when a sort is applied.

true

string

direction

Determines the language direction in grid. The default is “ltr” (Left To Right language). When set to “rtl” (Right To Left) the grid automatically do the needed. It is important to note that in one page we can have two (or more) grids where the one can have direction “ltr” while the other can have direction “rtl”. This option work only in FireFox 3.x versions and Internet Explorer versions >=6. Currently Safai and Google Chrome does not support fully direction “rtl”. Also the same apply to Opera browsers. The most common problem in FireFox is that the default settings of the browser does not support RTL. In order change this see HOW TO section in this chapter .

ltr

string

editurl

Defines the url for inline and form editing.

null

string

emptyrecords

Display the information when the returned (or the current) number of records is zero. This option is valid only if viewrecords option is set to true.

see lang file

boolean

ExpandColClick

when true, the treeGrid is expanded and/or collapsed when we click on the text of the expanded column, not only on the image

true

string

ExpandColumn

indicates which column (name from colModel) should be used to expand the tree grid. If not set the first one is used. Valid only when treeGrid option is set to true.

null

boolean

footerrow

If set to true this will place a footer table with one row below the gird records and above the pager. The number of columns equal of these from colModel

false

boolean

forceFit

If set to true, and resizing the width of a column, the adjacent column (to the right) will resize so that the overall grid width is maintained (e.g., reducing the width of column 2 by 30px will increase the size of column 3 by 30px). In this case there is no horizontal scrolbar. Note: this option is not compatible with shrinkToFit option - i.e if shrinkToFit is set to false, forceFit is ignored.

false

string

gridstate

Determines the current state of the grid (i.e. when used with hiddengrid, hidegrid and caption options). Can have either of two states: 'visible' or 'hidden'

visible

boolean

gridview

In the previous versions of jqGrid including 3.4.X,reading a relatively big data sets (Rows >=100 ) caused speed problems. The reason for this was that as every cell was inserted into the grid we applied about 5-6 jQuery calls to it. Now this problem is resolved; we now insert the entry row at once with a jQuery append. The result is impressive - about 3-5 times faster. What will be the result if we insert all the data at once? Yes, this can be done with a help of gridview option when set to true. The result is a grid that is 5 to 10 times faster. Of course when this option is set to true we have some limitations. If set to true we can not use treeGrid, subGrid, or afterInsertRow event. If you do not use these three options in the grid you can set this option to true and enjoy the speed.

false

mixed

height

The height of the grid. Can be set as number (in this case we mean pixels) or as percentage (only 100% is acceped) or value of auto is acceptable.

150

boolean

hiddengrid

If set to true the grid initially is hidden. The data is not loaded (no request is sent) and only the caption layer is shown. When the show/hide button is clicked the first time to show grid, the request is sent to the server, the data is loaded, and grid is shown. From this point we have a regular grid. This option has effect only if the caption property is not empty and the hidegrid property (see below) is set to true.

false

boolean

hidegrid

Enables or disables the show/hide grid button, which appears on the right side of the Caption layer. Takes effect only if the caption property is not an empty string.

true

boolean

hoverrows

When set to false the mouse hovering is disabled in the grid data rows.

false

array

jsonReader

Array which describes the structure of the expected json data. For a full description and default setting, see Retrieving Data JSON Data

integer

lastpage

Readonly property. Determines the total number of pages returned from the request.

0

integer

lastsort

Readonly property. Determines the index of last sorted column beginning from 0

0

boolean

loadonce

If this flag is set to true, the grid loads the data from the server only once (using the appropriate datatype). After the first request the datatype parameter is automatically changed to local and all further manipulations are done on the client side. The functions of the pager (if present) are disabled.

false

string

loadtext

The text which appear when requesting and sorting data. This parameter is located in language file

Loading…

string

loadui

This option controls what to do when an ajax operation is in progress.
disable - disables the jqGrid progress indicator. This way you can use your own indicator.
enable (default) - enables “Loading” message in the center of the grid.
block - enables the “Loading” message and blocks all actions in the grid until the ajax request is finished. Note that this disables paging, sorting and all actions on toolbar, if any.

enable

string

mtype

Defines the type of request to make (“POST” or “GET”)

GET

string

multikey

This parameter have sense only multiselect option is set to true. Defines the key which will be pressed when we make multiselection. The possible values are: shiftKey - the user should press Shift Key altKey - the user should press Alt Key ctrlKey - the user should press Ctrl Key

empty string

boolean

multiboxonly

This option works only when multiselect = true. When multiselect is set to true, clicking anywhere on a row selects that row; when multiboxonly is also set to true, the multiselection is done only when the checkbox is clicked (Yahoo style). Clicking in any other row (suppose the checkbox is not clicked) deselects all rows and the current row is selected.

false

boolean

multiselect

If this flag is set to true a multi selection of rows is enabled. A new column at left side is added. Can be used with any datatype option.

false

integer

multiselectWidth

etermines the width of the multiselect column if multiselect is set to true.

20

integer

page

Set the initial number of page when we make the request.This parameter is passed to the url for use by the server routine retrieving the data

1

mixed

pager

Defines that we want to use a pager bar to navigate through the records. This must be a valid html element; in our example we gave the div the id of “pager”, but any name is acceptable. Note that the Navigation layer (the “pager” div) can be positioned anywhere you want, determined by your html; in our example we specified that the pager will appear after the Table Body layer. The valid calls can be (using our example) 'pager', '#pager', jQuery('#pager'). I recommend to use the second one. See Pager

empty string.

string

pagerpos

Determines the position of the pager in the grid. By default the pager element when created is divided in 3 parts (one part for pager, one part for navigator buttons and one part for record information)

center

boolean

pgbuttons

Determines if the Pager buttons should be shown if pager is available. Also valid only if pager is set correctly. The buttons are placed in the pager bar.

true

boolean

pginput

Determines if the input box, where the user can change the number of requested page, should be available. The input box appear in the pager bar.

true

string

pgtext

Show information about current page status. The first value is the current loaded page. The second value is the total number of pages

See lang file

array

prmNames

Default values prmNames:
{page:“page”,rows:“rows”, sort: “sidx”,order: “sord”, search:“_search”, nd:“nd”, id:“id”,oper:“oper”,editoper:“edit”,addoper:“add”,deloper:“del”}
Customizes names of the fields sent to the server on a Post: default values for these fields are “page”, “rows”, “sidx”, “sord”, “search” and “nd”. For example, with this setting, you can change the sort order element from “sidx” to “mysort”: prmNames: {sort: “mysort”}. The string that will be posted to the server will then be myurl.php?page=1&rows=10&mysort=myindex&sord=asc rather than myurl.php?page=1&rows=10&sidx=myindex&sord=asc
When some parameter is set to null they will be not sended to the server. By example if we set prmNames: { nd:null} the nd parameter will not be sended. For npage option see scroll option.
The options meaning the following
page - the the requested page,
rows - the number of rows requested,
sort - the sorting column,
order - the sort order,
search - the search indicator,
nd - the time passed to the request (for IE browsers not to cache the request),
id - the name of the id when post data in editing modules,
oper - the operation parameter,
editoper - the name of operation when the data is posted in edit mode,
addoper - the name of operation when the data is posted in add mode,
deloper - the name of operation when the data is posted in delete mode,

none

array

postData

This array is passed directly to the url. This is associative array and can be used this way: {name1:value1…}. See API methods for manipulation.

empty array

integer

reccount

Readonly property. Determines the exactly number of rows in the grid. Do not mix this with records parameter. Instead that in most cases they are equal there is a case where this is not true. By example you define rowNum parameter 15, but you return from server records parameter = 20, then the records parameter will be 20, the reccount parameter will be 15, and in the grid you will have 15 records.

0

string

recordpos

Determines the position of the record information in the pager. Can be left, center, right

right

integer

records

Readonly property. Determines the number of returned records in grid from the request

none

string

recordtext

Represent information that can be shown in the pager. Also this option is valid if viewrecords option is set to true. This text appear only if the tottal number of recreds is greater then zero.In order to show or hide some information the items in {} mean the following: {0} the start position of the records depending on page number and number of requested records; {1} - the end position {2} - total records returned from the data

see lang file

string

resizeclass

Assigns a class to columns that are resizable so that we can show a resize handle only for ones that are resizable

empty string

array

rowList

An array to construct a select box element in the pager in which we can change the number of the visible rows. When changed during the execution, this parameter replaces the rowNum parameter that is passed to the url. If the array is empty the element does not appear in the pager. Typical you can set this like [10,20,30]. If the rowNum parameter is set to 30 then the selected value in the select box is 30.

empty array

boolean

rownumbers

If this option is set to true, a new column at left of the grid is added. The purpose of this column is to count the number of available rows, beginning from 1. In this case colModel is extended automatically with new element with name - 'rn'. Also, be careful not to use the name 'rn' in colModel

false

integer

rowNum

Sets how many records we want to view in the grid. This parameter is passed to the url for use by the server routine retrieving the data. Note that if you set this parameter to 10 (i.e. retrieve 10 records) and your server return 15 then only 10 records will be loaded. Set this parameter to -1 (unlimited) to disable this checking.

20

integer

rownumWidth

Determines the width of the row number column if rownumbers option is set to true.

25

array

savedRow

This is read only property and is used in Inline and cell editing modules to store the data, before editing the row or cell. See Cell editing and Inline editing.

empty array

boolean or integer

scroll

Creates dynamic scrolling grids. When enabled, the pager elements are disabled and we can use the vertical scrollbar to load data. When set to true the grid will always hold all the items from the start through to the latest point ever visited.
When scroll is set to value (eg 1), the grid will just hold the visible lines. This allow us to load the data at portions whitout to care about the memory leaks. Additionally this we have optional extension to the server protocol: npage (see prmNames array). If you set the npage option in prmNames, then the grid will sometimes request more than one page at a time, if not it will just perform multiple gets.

false

integer

scrollOffset

Determines the width of the vertical scrollbar. Since different browsers interpret this width differently (and it is difficult to calculate it in all browsers) this can be changed.

18

boolean

scrollrows

When enabled, selecting a row with setSelection scrolls the grid so that the selected row is visible. This is especially useful when we have a verticall scrolling grid and we use form editing with navigation buttons (next or previous row). On navigating to a hidden row, the grid scrolls so the selected row becomes visible.

false

array

selarrrow

This options is read only. Determines the currently selected rows when multiselect is set to true. This is one dimensional array and the values in the array correspond to the selected id's in the grid.

empty array

string

selrow

This option is read only. Contain the id of the last selected row. If you sort or apply a pagging this options is set to null

null

boolean

shrinkToFit

This option describes the type of calculation of the initial width of each column against with the width of the grid. If the value is true and the value in width option is set then: Every column width is scaled according to the defined option width. Example: if we define two columns with a width of 80 and 120 pixels, but want the grid to have a 300 pixels - then the columns are recalculated as follow: 1- column = 300(new width)/200(sum of all width)*80(column width) = 120 and 2 column = 300/200*120 = 180. The grid width is 300px. If the value is false and the value in width option is set then: The width of the grid is the width set in option. The column width are not recalculated and have the values defined in colModel.

true

boolean

sortable

When enabled this option allow column reordering with mouse. Since this option uses jQuery UI sortable widget, be a sure that this widget and the related to widget files are loaded in head tag. Also be a sure too that you mark the grid.jqueryui.js when you download the jqGrid.

false

string

sortname

The initial sorting name when we use datatypes xml or json (data returned from server). This parameter is added to the url. If set and the index (name) match the name from colModel then to this column by default is added a image sorting icon, according to the parameter sortorder (below). See prmNames.

empty string

string

sortorder

The initial sorting order when we use datatypes xml or json (data returned from server).This parameter is added to the url - see prnNames. Two possible values - asc or desc.

asc

boolean

subGrid

If set to true this enables using a subgrid. If the subGrid is enabled a additional column at left side is added to the basic grid. This column contains a 'plus' image which indicate that the user can click on it to expand the row. By default all rows are collapsed. See Subgrid

false

array

subGridModel

This property, which describes the model of the subgrid, has an effect only if the subGrid property is set to true. It is an array in which we describe the column model for the subgrid data. For more info see Subgrid.

empty array

mixed

subGridType

This option allow loading subgrid as a service. If not set, the datatype parameter of the parent grid is used.

null

string

subGridUrl

This option has effect only if subGrid option is set to true. This option points to the file from which we get the data for the subgrid. jqGrid adds the id of the row to this url as parameter. If there is a need to pass additional parameters, use the params option in subGridModel. See Subgrid

empty string

integer

subGridWidth

Determines the width of the subGrid column if subgrid is enabled.

20

array

toolbar

This option defines the toolbar of the grid. This is array with two values in which the first value enables the toolbar and the second defines the position relative to body Layer. Possible values “top”,”bottom”, “both”. When we set toolbar: [true,”both”] two toolbars are created – one on the top of table data and one of the bottom of the table data. When we have two toolbars then we create two elements (div). The id of the top bar is constructed like “t_”+id of the grid and the bottom toolbar the id is “tb_”+id of the grid. In case when only one toolbar is created we have the id as “t_” + id of the grid, independent of where this toolbar is created (top or bottom)

[false,'']

boolean

toppager

When enabled this option place a pager element at top of the grid below the caption (if available). If another pager is defined both can coexists and are refreshed in sync. The id of the new created pager is a combination of the gridid+“_toppager”.

false

integer

totaltime

Readonly parameter. Measure the loading time of the records - currently available only when we load xml or json data. Also the check begin when the request is complete and we begin to insert data into the grid and ends when the last row is added.

0

mixed

treedatatype

Determines the initial datatype (see datatype option). Usually this should not be changed. During the reading process this option is equal to the datatype option.

null

boolean

treeGrid

Enables (disables) the tree grid format. For more details see Tree Grid

false

string

treeGridModel

Deteremines the method used for the treeGrid. Can be nested or adjacency. See Tree Grid

nested

array

treeIcons

This array set the icons used in the tree. The icons should be a valid names from UI theme roller images. The default values are: {plus:'ui-icon-triangle-1-e',minus:'ui-icon-triangle-1-s',leaf:'ui-icon-radio-off'}

array

treeReader

extends the colModel defined in the basic grid. The fields described here are added to end of the colModel array and are hidden. This means that the data returned from the server should have values for these fields. For a full description of all valid values see Tree Grid.

numeric

tree_root_level

Determines the level where the root element begins when treeGrid is enabled

0

string

url

The url of the file that holds the request

null

array

userData

This array contain custom information from the request. Can be used at any time.

empty array

boolean

userDataOnFooter

When set to true we directly place the user data array userData at footer. The rules are as follow: If the userData array contain name which is equal to those of colModel then the value is placed in that column.If there are no such values nothing is palced. Note that if this option is used we use the current formatter options (if available) for that column

false

boolean

viewrecords

Defines whether we want to display the number of total records from the query in the pager bar.

false

array

viewsortcols

The purpose of this parameter is to define different look and behavior of sorting icons that appear near the header. This parameter is array with the following default options viewsortcols : [false,'vertical',true]. The first parameter determines if all icons should be viewed at the same time when all columns have sort property set to true. The default of false determines that only the icons of the current sorting column should be viewed. Setting this parameter to true causes all icons in all sortable columns to be viewed.
The second parameter determines how icons should be placed - vertical means that the sorting icons are one under another. 'horizontal' means that the icons should be one near other.
The third parameter determines the click functionality. If set to true the columns are sorted if the header is clicked. If set to false the columns are sorted only when the icons are clicked.
Important note: When set a third parameter to false be a sure that the first parameter is set to true, otherwise you will lost the sorting.

number

width

If this option is not set, the width of the grid is a sum of the widths of the columns defined in the colModel (in pixels). If this option is set, the initial width of each column is set according to the value of shrinkToFit option.

none

array

xmlReader

Array which describes the structure of the expected xml data. For a full description refer to Retrieving Data XML Data.

number

rowTotal

This parameter have effect only when is used with the loadonce parameter set to true. This allow to load all the needed data at once and operate it localy. Note that paging, searching and sorting will work.
When the parameter is set to -1 we load all the data from the request.
When parameter is a number greater than zero we load the requested number of rows.
Note that rowNum determines the total records displayed in the grid, while rowTotal the total rows on wich we operate.

null

boolean

grouping

This parameter enable the grouping in the grid. When set to true you must configure the groupingView options array in order to group by certain fields (see below). When the grouping is enabled the following grid options are set internally to the following values:

  • scroll = > false
  • rownumbers => false;
  • subGrid => false;
  • treeGrid => false;
  • gridview => true;

false

array

groupingView

This parameter configures the grouping. It has effect only if the grouping option is set to true (see above).
The parameter contain the following options:

  • groupField - array - set the name on wich grouping occur. The name correspond to the name in colModel.
  • groupOrder - array - set the order on which the grouping occue. Can be asc or desc
  • groupText - array - set the text that will appear at the header when the grouping occur. Actually this a template. We have the following template options - '{0}' will display the current value of the grouped field and '{1}' will display tottal number of the group. By example if the current value of the grouping field is Client the the setting '{0} - total {1} item(s)' will display 'Client - total 5 item(s)'.
  • groupColumnShow - array which values are booleans. Determines if the grouped column should be displayed. Default value is true. setting the value to false will hide the grouped coulumn.
  • groupSummary - array which values are booleans. When set to true a footer column will be displayed at end of each group allowing to put summary information for the group. When this option is set to true the following options in colModel can be set in order to have the summary information - summaryType and optionally summaryTpl. For more info refer to colModel options and Grouping with summary.
  • groupDataSorted - boolean (default false). If set to true causes jqGrid to add a additional parameter with the name which will be posted to the server. This way the data comes to the grid sorted in the appropriate way. It is highly recommended to set this option to true if a data from server is used. This option does not have effect if the data is local.
  • groupCollapse - boolean - Defines if initially the grid should show or hide the detailed rows of the group.
  • plusicon - string. determines the plus icon from jQuery UI theme roller set icons. Default 'ui-icon-circlesmall-plus'
  • minusicon - string. determines the minus icon from jQuery UI theme roller set icons. Default 'ui-icon-circlesmall-minus'
One possible setting can look like this

$grid->setGridOptions(array(
...
"grouping"=>true,
"groupingView"=>array(
"groupField" => array('CustomerID'),
"groupColumnShow" => array(true),
"groupText" =>array('{0}'),
"groupDataSorted" => true,
"groupSummary" => array(true)
)
));

null

Last Updated: 12/13/11 | © TriRand Ltd., 2011


 Grid Events
Grid Events
The event is action that is rasied on the client side when something is hapen in the grid. Since this is a client side job in order to use the grid events you will need to write a java script code. Bellow is example in which when a row is selected a we alert a message to the user.
The PHP method that initializes the event is setGridEvent.

<?php
...
// Create the jqGridEdit instance
$grid = new jqGridRender($conn);

// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
$grid->dataType = "json";

$myevent = <<<ONSELECT
function(rowid, selected)
{
   if (rowid) alert("Row is selected");
}
ONSELECT;
$grid->setGridEvent('onSelectRow',$myevent);

....

$grid->renderGrid();
?>

As can be seen from this example the first parameter of the method is the name of the event and the second is the code associated with that event. Note how $myevent is written - function(params,...) - This will produce in the cleint

onSelectRow:function(rowid, selected) {....}

Below is the list of events that can be used into the grid:

Event | Parameters | Description
afterInsertRow | rowid rowdata rowelem | This event fires after every inserted row. rowid is the id of the inserted row rowdata is an array of the data to be inserted into the row. This is array of type name: value, where the name is a name from colModel rowelem is the element from the response. If the data is xml this is the xml element of the row; if the data is json this is array containing all the data for the row Note: this event does not fire if gridview option is set to true
beforeRequest | none | This event fire before requesting any data. Also does not fire if datatype is function
beforeSelectRow | rowid, e | This event fire when the user click on the row, but before select them. rowid is the id of the row. e is the event object This event should return boolean true or false. If the event return true the selection is done. If the event return false the row is not selected and any other action if defined does not occur.
gridComplete | none | This fires after all the data is loaded into the grid and all other processes are complete. Also the event fires independent from the datatype parameter and after sorting paging and etc.
loadBeforeSend | xhr | A pre-callback to modify the XMLHttpRequest object (xhr) before it is sent. Use this to set custom headers etc. The XMLHttpRequest is passed as the only argument.
loadComplete | xhr | This event is executed immediately after every server request. xhr XMLHttpRequest object
loadError | xhr, status, error | A function to be called if the request fails. The function gets passed three arguments: The XMLHttpRequest object (xhr), a string describing the type of error (satus) that occurred and an optional exception object (error), if one occurred.
onCellSelect | rowid, iCol, cellcontent, e | Fires when we click on particular cell in the grid. rowid is the id of the row iCol is the index of the cell, cellcontent is the content of the cell, e is the event object element where we click. (Note that this available when we not use cell editing module and is disabled when using cell editing).
onClickGroup | groupid, collapsed | This event fires after clicking group (to expand or collapse group). it has 2 parameters, group id (string) and collapsed (boolean). 'groupid' is a combination of grid id plus 'ghead_' plus the current count number in the grid view. . 'collapsed' is current group's collapse status.
ondblClickRow | rowid, iRow, iCol, e | Raised immediately after row was double clicked. rowid is the id of the row, iRow is the index of the row (do not mix this with the rowid), iCol is the index of the cell. e is the event object
onHeaderClick | gridstate | Fire after clicking to hide or show grid (hidegrid:true); gridstate is the state of the grid - can have two values - visible or hidden
onPaging | pgButton | This event fires after click on [page button] and before populating the data. Also works when the user enters a new page number in the page input box (and presses [Enter]) and when the number of requested records is changed via the select box. To this event we pass only one parameter pgButton See pager. If this event return 'stop' the processing is stopped and you can define your own custom pagging
onRightClickRow | rowid, iRow, iCol, e | Raised immediately after row was right clicked. rowid is the id of the row, iRow is the index of the row (do not mix this with the rowid), iCol is the index of the cell. e is the event object. Note - this event does not work in Opera browsers, since Opera does not support oncontextmenu event
onSelectAll | aRowids, status | This event fires when multiselect option is true and you click on the header checkbox. aRowids array of the selected rows (rowid's). status - boolean variable determining the status of the header check box - true if checked, false if not checked. Note that the aRowids alway contain the ids when header checkbox is checked or unchecked.
onSelectRow | rowid, status | Raised immediately after row was clicked. rowid is the id of the row, status is the status of the selection. Can be used when multiselect is set to true. true if the row is selected, false if the row is deselected.
onSortCol | index, iCol, sortorder | Raised immediately after sortable column was clicked and before sorting the data. index is the index name from colModel, iCol is the index of column, sortorder is the new sorting order - can be 'asc' or 'desc'. If this event return 'stop' the sort processing is stopped and you can define your own custom sorting
resizeStart | event, index | Event which is called when we start resize a column. event is the event object, index is the index of the column in colModel.
resizeStop | newwidth, index | Event which is called after the column is resized. newwidth is the is the new width of the column , index is the index of the column in colModel.
serializeGridData | postData | If set this event can serialize the data passed to the ajax request. The function should return the serialized data. This event can be used when a custom data should be passed to the server - e.g - JSON string, XML string and etc. To this event we pass the postData array.

Last Updated: 12/13/11 | © TriRand Ltd., 2011


 Column Model Options
Column Model Options
The colModel property defines the individual grid columns as an array of properties. This is the most important part of the jqGrid.
When used in this class the colModel is generated for you automaticaly based on the SQL query command.
The generation of the column model is done with setColModel method. After this generation a method setColProperty can be used to change or add another one.

When the method is called it adds the following options automatically (see below) name, index, sorttype, key

Related methods for grid columns

getColModel
setColModel
setColProperty

Below is a list of properties for the colModel

Property

Type

Description

Default

align

string

Defines the alignment of the cell in the Body layer, not in header cell. Possible values: left, center, right.

left

cellattr

function

Java script function which allow to set various properties for the cell dynamically. For more information see Cell Attributes

null

classes

string

This option allow to add classes to the column. If more than one class will be used a space should be set. By example classes:'class1 class2' will set a class1 and class2 to every cell on that column. In the grid css there is a predefined class ui-ellipsis which allow to attach ellipsis to a particular row. Also this will work in FireFox too.

empty string

datefmt

string

Governs format of sorttype:date (when datetype is set to local) and editrules {date:true} fields. Determines the expected date format for that column. Uses a PHP-like date formatting. Currently ”/”, ”-”, and ”.” are supported as date separators. Valid formats are:
y,Y,yyyy for four digits year
YY, yy for two digits year
m,mm for months
d,dd for days.

ISO Date (Y-m-d)

defval

string

The default value for the search field. This option is used only in and will be set as initial search.

empty

editable

boolean

Defines if the field is editable. This option is used in cell, inline and form modules. See editing

false

editoptions

array

Array of allowed options (attributes) for edittype option. See editing

empty array

editrules

array

sets additional rules for the editable field editing. See editing

empty array

edittype

string

Defines the edit type for inline and form editing Possible values: text, textarea, select, checkbox, password, button, image and file. See editing

text

fixed

boolean

If set to true this option does not allow recalculation of the width of the column if shrinkToFit option is set to true. Also the width does not change if a setGridWidth method is used to change the grid width.

false

formoptions

array

Defines various options for form editing. See See formoptions

empty

formatoptions

array

Format options can be defined for particular columns, overwriting the defaults from the language file. See Formatter for more details.

none

formatter

mixed

The predefined types (string) or custom function name that controls the format of this field. See Formatter for more details.

none

hidedlg

boolean

If set to true this column will not appear in the modal dialog where users can choose which columns to show or hide.

false

hidden

boolean

Defines if this column is hidden at initialization.

false

index

string

Set the index name when sorting. Passed as sidx parameter.

empty string

jsonmap

string

Defines the json mapping for the column in the incoming json string. This option does not have in in jqGrid PHP

none

key

boolean

In case if there is no id from server, this can be set as as id for the unique row id. Only one column can have this property. If there are more than one key the grid finds the first one and the second is ignored.

false

label

string

When colNames array is empty, defines the heading for this column. If both the colNames array and this setting are empty, the heading for this column comes from the name property.

none

name

string

Set the unique name in the grid for the column. This property is required. As well as other words used as property/event names, the reserved words (which cannot be used for names) include subgrid, cb and rn.

Required

resizable

boolean

Defines if the column can be re sized

true

search

boolean

When used in search modules, disables or enables searching on that column.

true

searchoptions

array

Defines the search options used searching See Search Configuration

empty

sortable

boolean

Defines is this can be sorted.

true

sorttype

string

Used when datatype is local. Defines the type of the column for appropriate sorting.Possible values:
int/integer - for sorting integer
float/number/currency - for sorting decimal numbers
date - for sorting date
text - for text sorting. The script automaticall fill this property.

text

stype

string

Determines the type of the element when searching - can be text or select. See here

text

surl

string

Valid only in and edittype : 'select' and describes the url from where we can get already-constructed select element

empty string

template

array

With this option is it possible to set a repeated properties in colMode for all or particular fields. By example if a lot of columns have a custom formating options for a number, you can define a sepaarte set of this options and then just point it on the setColProperty('field', array("template"=>myproperties)), where my properties is a set of valid colModel options

null

width

number

Set the initial width of the column, in pixels. This value currently can not be set as percentage

150

xmlmap

string

Defines the xml mapping for the column in the incomming xml file. Use a CCS specification for this. This property does not have sense in jqGrid PHP

none

unformat

function

Custom function to “unformat” a value of the cell when used in editing See Custom Formatter. (Unformat is also called during sort operations. The value returned by unformat is the value compared during the sort.)

null

summaryType

string or function

This option have effect only if the grid grouping option is enabled and the groupSummary array in groupingView options is set to true. This determines the summary function which will be applied to each group. The following predefined function types are vailable:

  • min - set the minimal vauee within the group
  • max - set the maximal values within the group
  • sum - set the summary value for the group
  • avg - set the average value for the group
  • count - set the number of items within the group
The value can be a custom javascript function

empty string

summaryTpl

string

This option have effect only if the grid grouping option is enabled and the groupSummary array in groupingView options is set to true. Determines the template for the summary footer information. The template can contain arbitrary text plus a value of {0} which is actually the result of the summar function for that group. For more info see grouping tutorial

empty string

Last Updated: 05/13/11 | © TriRand Ltd., 2011


 Editing Options
Editing Options
One of the key reasons for displaying data in a grid is to edit it, quickly and easily. jqGrid supports editing data in three ways:

  1. cell editing: edit specific cells in a gird
  2. inline editing: edit several cells in the same row
  3. form editing: create a form to edit outside of the grid

By default when to colModel is created all fields are marked as editable, where the field is represented as input of type text.
If we want to disable the editing of some field we should just set the property editable to false:

$grid->setColProperty('somefield',array("editable"=>false));

after the colModel is created with setColModel method.

All editing modules uses a common properties in colModel in order to perform editing. Below is the list of these properties with detailed description:

  • editable
  • edittype
  • editoptions
  • editrules
  • formoptions (valid only in form editing)

The common syntax of using these options is:

<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("editable"=>true, "edittype"=>"text", "editoptions"=>array(...), "editrules"=>array(...), "formoptions"=>array(...)));
...

$grid->renderGrid(...);
...
?>

editable

The editable option is boolean and can have two values true or false. The option defines if this field is editable (or not). Default is true. To make a field non editable, set this to false: editable=>false.
We should mention that the hidden fields are not editable instead that they have been marked as editable. In in-line and cell editing modules you should show these fields (using showCol method) in order to edit it. In form editing module you should use editrules option (see below)

edittype

Edittype option defines the type of of the editable field. Possible values: 'text', 'textarea', 'select', 'checkbox', 'password', 'button', 'image', 'file' and 'custom'. The default value is 'text'.

text

When edittype is 'text', jqGrid constructs a input tag of type text:

<input type="text" ...../>

In editoptions we can set all the possible attributes for this field. For example,

... "editoptions"=>array("size"=>10, "maxlength"=> 15).....

will cause jqGrid to construct the following input

<input type="text" size="10" maxlength="15" />

In addition to the these settings, jqGrid adds the id and name attribute.

textarea

When edittype is 'textarea', jqGrid constructs a input tag of type textarea

<input type="textarea" .../>

In editoptions we can add additional attributes to this type. Typically, these govern the size of the box:

... "editoptions"=>array("rows"=>3, "cols"=> 20).....

<input type="textarea" rows="3" cols="20".../>

To these attributes jqGrid adds id and name attributes .

checkbox

When edittype is 'checkbox', jqGrid constructs a input tag as follows:

<input type="checkbox" .../>

editoptions is used to define the checked and unchecked values. The first value is checked. For example

..."editoptions"=>array("value"=>"Yes:No" )...

This will construct

<input type="checkbox" value="Yes" offval="No".../>

defines a checkbox in which when the value is Yes the checkbox becomes checked, otherwise unchecked. This value is passed as parameter to the editurl.

If in the editoptions the value property is not set jqGrid search for the following values (false|0|no|off|undefined) in order to construct checkbox. If the cell content does not contain one of these values then the value attribute becomes the cell content and offval is set to off.
Example if the cell content is true, then
<input type="checkbox" value="true" offval="off" checked.../>
To these attributes jqGrid adds id and name attributes .

select

When edittype is 'select', jqGrid constructs a input tag as follows:

<select>
<option value='val1'> Value1 </option>
<option value='val2'> Value2 </option>
...
<option value='valn'> ValueN </option>
</select>

To construct this element we have two possible variants

  • Using the setSelect method
  • Setting editoptions dataUrl parameter

The method setSelect will be considered later (link)

The editoptions dataUrl parameter is valid only for element of edittype:select. The dataUrl parameter represent the url from where the html select element should be get.
When this option is set, the element will be filled with values from the ajax request. The data should be a valid html select element with the desired options - something like:

<select>
<option value='1'>One</option>
<option value='2'>Two</option>
...
</select>

To this element, jqGrid adds the id and name attributes as above.
The corresponding script cam look like this:

...
$grid->setColProperty('somename',array('edittype'=>'select','editoptions'=>array('dataUrl'=>'some_url')));
...

Multiple selection of options in a select box is also possible. Also the size attribute can be added too

...
$grid->setColProperty('somename',array('edittype'=>'select','editoptions'=>array("multiple"=>true,"size"=>3,...)));
...

password

When edittype is 'password', jqGrid constructs a input tag of type text:

<input type="password" ...../>

In editoptions we can set all the possible attributes for this field. For example,

... "editoptions"=>array("size"=>10, "maxlength"=> 8).....

will cause jqGrid to construct the following input

<input type="password" size="10" maxlength="8" />

In addition to the these settings, jqGrid adds the id and name attribute.

button

When edittype is 'button', jqGrid constructs a input tag of type text:

<input type="button" ...../>

In editoptions we can set all the possible attributes for this field. For example,

... "editoptions"=>array("value"=>"MyButton").....

will cause jqGrid to construct the following input

<input type="button" value="MyButton" />

In addition to the these settings, jqGrid adds the id and name attribute.

image

When edittype is 'image', jqGrid constructs a input tag of type text:

<input type="image" ...../>

In editoptions we can set all the possible attributes for this field. For example,

... "editoptions"=>array("src"=>"path_to_my_image").....

will cause jqGrid to construct the following input

<input type="image" src="path_to_my_image" />

In addition to the these settings, jqGrid adds the id and name attribute.

file

When edittype is 'file', jqGrid constructs a input tag of type text:

<input type="file" ...../>

In editoptions we can set all the possible attributes for this field. For example,
... "editoptions"=>array("alt"=>"Alt text").....

will cause jqGrid to construct the following input

<input type="file" alt="Alt text"... />

In addition to the these settings, jqGrid adds the id and name attribute.

When this element is created (usually in form editing) the form does not become ENCTYPE=“multipart/form-data” in order to upload the file. You should apply another plugin for this purpose - Ajax File Upload plugin works fine.

custom
This edit type allow definition of custom editable element. When edit type is set to custom we should provide a set of functions which should to create the element, and get the value from it in order to be posted to the server.
Functions that should be defined:

1. custom_element - this function is used to create the element. The function should return the new DOM element. Parameters passed to this function are the value and the editoptions from colModel.
2. custom_value - this function should return the value from the element after the editing in order to post it to the server. Parameter passed to this function is the element object

When the custom element is created we automatically do the following additinal tasks:

1.add a class 'customelement'
2.add attribute name with name from colModel
3.add id according to the rules for every edited module.

See example on how to construct custom element

editoptions

editoptions property is array which contain important information about the editing column. It is important to note that in editoptins array you can set any valid attribute for the chosen edittype.

Below is the list of most commonly used options:

Property | Type | Description
value | mixed | When set for edittype checkbox this value should be a string with two possible values separated with a colon (:) - Example "editoptions"=>array("value"=>“Yes:No”) where the first value determines the checked property. When set for edittype select value can be a string, object or function. If the option is a string it must contain a set of value:label pairs with the value separated from the label with a colon (:) and ended with(;). The string should not ended with a (;)- "editoptions"=>array("value"=>“1:One;2:Two”). When defined as function - the function should return either formated string or object. In all other cases this is the value of the input element if defined.
dataUrl | string | This option is valid only for the elements of type select - i.e., edittype:select and should represent the url for getting the data that should contain the select definition. The data is obtained via ajax call and should be a valid html select element with the desired options <select><option value='1'>One</option>…</select>. In this case you can use option group. The ajax request is called only once when the element is created. In inline edit or cell edit module it is called every time when you edit a new row or cell. In form edit module only once.
buildSelect | function | This option have sense only if the dataUrl parameter is set. In case where the server response can not build the select element you can use your on function to build the select. The function should return a string containing the select and options value(s) as described in dataUrl option. Parameter passed to this function is the server response. This function should be created like this "editoptions"=>array("buildSelect"=>"js:function(response){...}",..)
dataInit | function | To this function, if defined, we pass the element object. This function is called only once when the element is created. The event is called only once when the element is created. In inline edit or cell edit module it is called every time when you edit a new row or cell. In form edit module only once.
dataEvents | array | list of events to apply to the data element; uses jQuery bind like $(”#id”).bind(type, [data], fn) to bind events to data element.
defaultValue | mixed | The option can be string or function. This option is valid only in Form Editing module when used with editGridRow method in add mode. If defined the input element is set with this value if only element is empty. If used in selects the text should be provided and not the key. Also when a function is used the function should return value.
NullIfEmpty | boolean | If the property is set to true the empty values from inline and form editing are set/added into the database as NULLs.
other options | mixed | In this case you can set any other valid attribute for the editable element. By Example if the element is edittype:'text' we can set size, maxlenght and etc. attributes. Refer to the valid attributes of of the element

editrules

This option add additional properties to the editable element and should be used in colModel. Mostly it is used to validate the user input before submitting the value(s) to the server.

Syntax:

<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("editable"=>true, "editrules"=>array("edithidden"=>true, "required"=>true...), ..));
...

$grid->renderGrid(...);
...
?>

Below is the list of available options:
Option | Type | Description
edithidden | boolean | This option is valid only in form editing module. By default the hidden fields are not editable. If the field is hidden in the grid and edithidden is set to true, the field can be edited when add or edit methods are called.
required | boolean | (true or false) if set to true, the value will be checked and if empty, an error message will be displayed.
number | boolean | (true or false) if set to true, the value will be checked and if this is not a number, an error message will be displayed.
integer | boolean | (true or false) if set to true, the value will be checked and if this is not a integer, an error message will be displayed.
minValue | number(integer) | if set, the value will be checked and if the value is less than this, an error message will be displayed.
maxValue | number(integer) | if set, the value will be checked and if the value is more than this, an error message will be displayed.
email | boolean | if set to true, the value will be checked and if this is not valid e-mail, an error message will be displayed
url | boolean | if set to true, the value will be checked and if this is not valid url, an error message will be displayed
date | boolean | if set to true a value from datefmt option is get (if not set ISO date is used) and the value will be checked and if this is not valid date, an error message will be displayed
time | boolean | if set to true, the value will be checked and if this is not valid time, an error message will be displayed. Currently we support only hh:mm format and optional am/pm at the end
custom | boolean | if set to true allow definition of the custom checking rules via a custom function. See below
custom_func | function | this function should be used when a custom option is set to true. Parameters passed to this function are the value, which should be checked and the name - the property from colModel. The function should return array with the following parameters: first parameter - true or false. The value of true mean that the checking is successful false otherwise; the second parameter have sense only if the first value is false and represent the error message which will be displayed to the user. Typically this can look like this [false,”Please enter valid value”]

formoptions

This option is valid only in form editing. The purpose of these options is to reorder the elements in the form and to add some information before and after the editing element. Should be used in colModel array. Syntax:

<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("editable"=>true, "formoptions"=>array("elmprefix"=>"(*)", "rowpos"=>1, "colpos"=>2), ..));
...

$grid->renderGrid(...);
...
?>

Below is a list of available options

Option | Type | Description
elmprefix | string | if set, a text or html content appears before the input element
elmsuffix | string | if set, a text or html content appears after the input element
label | string | if set, this replace the name from colNames array that appears as label in the form.
rowpos | number | determines the row position of the element (again with the text-label) in the form; the count begins from 1
colpos | number | determines the column position of the element (again with thelabel) in the form beginning from 1

Two elements can have equal row position, but different column position. This will place the two elements in one row on the form.

Last Updated: 05/13/11 | © TriRand Ltd., 2011


 Formatters
Formatters
Formatter supports advanced formatting of the contents of cells in form, in-line and cell editing.
Formatter can be used in either of two ways: Predefined and Custom.
Here we describe the predefined formatters.

Default formatting functions are defined in the language files e.g., grid.locale-xx (where xx is your language). That mean that these formatter options are loaded when the grid java script files are loaded. See here

The default formatter options are different for different language files.

In the language file you will find all the settings that you may want to review or change before using the predefined formats. These settings can also be overridden for specific columns using the formatoptions parameter in colModel.

The second step is to set the desired formatting in colModel. This is done using the option formatter. For example.

<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"number"));
...

$grid->renderGrid(...);
...
?>

will format the contents of the 'somefield' column according to the rules set for 'number' in the active language file. For example, if the source value is “1234.1”, then the value that actually will be put in the grid will be “1 234.10” using the options above.

Column Specific Options

Formatter options can be defined for particular columns, overwriting the defaults from the language file. This is accomplished by using the formatoptions array in colModel. For example:

<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"currency", "formatoptions"=>array("prefix"=>"$ ")));
...

$grid->renderGrid(...);
...
?>

This definition will overwrite the default one from the language file. In formatoptions should be placed values appropriate for the particular format type

All predefined types are compatible with the editing modules. This means that the numbers, links, e-mails, etc., are converted so that they can be edited correctly.

Below is a list of the predefined format types

Type | Options | Description
integer | thousandsSeparator, defaulValue | thousandsSeparator determines the separator for the thousands, defaultValue set the default value if nothing in the data
number | decimalSeparator, thousandsSeparator, decimalPlaces, defaulValue | thousandsSeparator determines the separator for the thousands, decimalSeparator determines the separator for the decimals, decimalPlaces determine how many decimal places we should have for the number, defaultValue set the default value if nothing in the data
currency | decimalSeparator, thousandsSeparator, decimalPlaces, defaulValue, prefix, suffix | The same as number, but we add aditional two options - prefix a text the is puted before the number and suffix the text that is added after the number
date | srcformat, newformat | srcformat is the source format - i.e. the format of the date that should be converted, newformat is the new output format. The definition of the date format uses the PHP conversions. Also you can use a set of predefined date format - see the mask options in the default date formatting set
email | none | When a mail type is used we directly add a href with mailto: before the e-mail
link | target | The default value of the target options is null. When this options is set, we construct a link with the target property set and the cell value put in the href tag.
showlink | baseLinkUrl, showAction, addParam, target, idName | baseLinkUrl is the link. showAction is an additional value which is added after the baseLinkUrl. addParam is an additional parameter that can be added after the idName property. target, if set, is added as an additional attribute. idName is the first parameter that is added after the showAction. By default, this is id,
checkbox | disabled | The default value for the disabled is true. This option determines if the checkbox can be changed. If set to false, the values in checkbox can be changed
select | none | this is not a real select but a special case. See note below

There is a special type formatter called "actions".
With help of this formatter it is possible to place edit and delete buttons in certain column. These buttons are placed at each row so that if pressed the recod can be editred or deleted.
A inline editing is used when this formatter is set.
Below are the options available which can be set in formatoptions property.
Example:

$grid->addCol(array(
    "name"=>"actions",
    "formatter"=>"actions",
    "editable"=>false,
    "sortable"=>false,
    "resizable"=>false,
    "fixed"=>true,
    "width"=>60,
    "formatoptions"=>array("keys"=>true)
    ), "first");

Options available:

Option | Type | Description | Default
keys | boolean | When eset to false enables saving a record with pressing a Enter key | false
editbutton | boolean | When set to false disable editing | true
delbutton | boolean | When set to false disables the delet button | true
onEdit | function (javascript) | This event raises immediatley after editing the record - i.e the inlut fields are constructed. Prameters passed to this event is the rowid | null
onSuccess | function (javascript) | if defined, this function is called immediately after the request is successful. This function is passed the data returned from the server. Depending on the data from server; this function should return true or false | null
afterSave | function (javascript) | if defined, this function is called after the data is saved to the server. Parameters passed to this function are the rowid and the response from the server request. | null
onError | function (java script)) | if defined, this function is called when ajax error occur. Parameters passed to this function are the rowid and the the response from the server request. | null
afterRestore | function | if defined, this function is called in restoreRow (in case the row is not saved ) method after restoring the row. To this function we pass the rowid | null
url | String | if defined, this parameter replaces the editurl parameter from the options array. | Empty
delOptions | array | A set of delete options - See For editing Deleting | null

Last Updated: 01/12/11 | © TriRand Ltd., 2011


 Cell Attributes
Cell Attributes
With javascript function cellattr is possible to set attributes for a particular cell, which correspond to certain column in the grid.
Example: the cell is defined as following HTML in the grid :

... <td> My Content </td>

If the function return the string style='color:red' class='myclass', then the contents in the dom for that column will be

... <td style='color:red' class='myclass'> My Content </td>

As can be seen we can set any valid attribute for the cell including colspan and rowspan

In PHP this will look like this:

<?php
...
$mycellattr = <<< CELLATTR
function (rowid, value, rawObject, colModel, arraydata) {
    return "style='color:red' class='myclass' ";
}
CELLATTR;

$grid ->setColProperty('field', array("cellattr"=>"js:".$mycellattr));

...

?>

Parameters passed to this function are

  • rowId - the id of the row
  • value - the values of the cell after it is formated (if a formatter is used)
  • rawObject - the row data from the server response - either array or xml node
  • colModel - all colmodel optins for that field
  • arraydata - a pair name:value of the data which is already inserted in this row.
Last Updated: 03/18/11 | © TriRand Ltd., 2011


 Navigator and Buttons
Navigator and Buttons
Navigator is a method that can add predefined actions like editing, adding, deleting, and searching. It is also possible to add custom buttons with custom actions. The built in navigator should be applied to the pager element. In other words, the pager element should be defined. The built in navigator actions correspond to the form editing actions.

By default navigaror is disabled. To enable navigator just set the navigator variable to true

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->renderGrid(...);
?>

With this action we enable the following actions in pager - add, edit, del, search, refresh, export to excel.
The view action is disabled.
To disable some action in navigator use setNavOptions method specifiyng the word navigator. If by example we want to disable adding of records do this

<?php
...
// Create the jqGridRender instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('navigator',array('add'=>false));
$grid->renderGrid(...);
?>

Parameters

When we use the navigator the following options are included from the language file.
Below are the defaults for the English language file.

$.jgrid = {
...
   search : {
     caption: "Search...",
     Find: "Find",
     Reset: "Reset",
     odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'],
     groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ],
     matchText: " match",
     rulesText: " rules"
   },
   edit : {
     addCaption: "Add Record",
     editCaption: "Edit Record",
     bSubmit: "Submit",
     bCancel: "Cancel",
     bClose: "Close",
     saveData: "Data has been changed! Save changes?",
     bYes : "Yes",
     bNo : "No",
     bExit : "Cancel",
  },
  view : {
    caption: "View Record",
    bClose: "Close"
  },
  del : {
    caption: "Delete",
    msg: "Delete selected record(s)?",
    bSubmit: "Delete",
    bCancel: "Cancel"
  },
  nav : {
    edittext: "",
    edittitle: "Edit selected row",
    addtext:"",
    addtitle: "Add new row",
    deltext: "",
    deltitle: "Delete selected row",
    searchtext: "",
    searchtitle: "Find records",
    refreshtext: "",
    refreshtitle: "Reload Grid",
    alertcap: "Warning",
    alerttext: "Please, select row",
    viewtext: "",
    viewtitle: "View selected row"
  },
...

The options $.jgrid.edit, $.jgrid.add, $.jgrid.del and $.jgrid.search are included to tier modules if enabled.

The full list of the parameters is as follow:

Property | Type | Description | Default
add | boolean | Enables or disables the add action in the navigator. When the button is clicked a editGridRow with parameter new method is executed | true
addicon | string | Set a icon to be displayed if the add action is enabled. Note that currently only icons from UI theme images can be added | ui-icon-plus
addtext | string | The text than can be set in the add button | empty
addtitle | string | The title that appear when we mouse over to the add button (if enabled) | Add new row
alertcap | string | The header of the message that appear when we try to edit,delete or view a row without to select it | Warning
alerttext | string | The message text that appear when we try to edit,delete or view a row without to select it | Please, select row
cloneToTop | boolean | Clones all the actions from the bottom pager to the top pager if defined. Note that the navGrid can be applied to the top pager only. The id of the top pager is a combination of grid id and “_toppager” | false
closeOnEscape | boolean | Determine if the alert dialog can be closed if the user pres ESC key | true
del | boolean | Enables or disables the delete action in the navigator. When the button is clicked a delGridRow method is executed. | true
delicon | string | Set a icon to be displayed if the delete action is enabled. Note that currently only icons from UI theme images can be used | ui-icon-trash
deltext | string | The text than can be set in the delete button | empty
deltitle | string | The title that appear when we mouse over to the delete button (if enabled) | Delete selected row
edit | boolean | Enables or disables the edit action in the navigator. When the button is clicked a editGridRow method is executed with parameter the - current selected row | true
editicon | string | Set a icon to be displayed if the edit action is enabled. Note that currently only icons from UI theme images can be used | ui-icon-pencil
edittext | string | The text than can be set in the edit button | empty
edittitle | string | The title that appear when we mouse over to the edit button (if enabled) | Edit selected row
excel | boolean | Enables/Disables export to Excel | true
position | string | Determines the position of the navigator buttons in the pager. Can be left, center and right. | left
refresh | boolean | Enables or disables the refresh button in the pager. When the button is clicked a trigger(“reloadGrid”) is executed and the search parameters are cleared | true
refreshicon | string | Set a icon to be displayed if the refresh action is enabled. Note that currently only icons from UI theme images can be used | ui-icon-refresh
refreshtext | string | The text than can be set in the refresh button | empty
refreshtitle | string | The title that appear when we mouse over to the refresh button (if enabled) | Reload Grid
refreshstate | string | Determines how the grid should be reloaded - firstpage - the grid reload the data from the first page. - current - the reloading should save the current page and current selection | firstpage
afterRefresh | function | If defined this event fire after the refresh button is clicked | null
beforeRefresh | function | If defined this event fire before the refresh button is clicked | null
search | boolean | Enables or disables the search button in the pager.When the button is clicked a searchGrid method is executed | true
searchicon | string | Set a icon to be displayed if the search action is enabled. Note that currently only icons from UI theme images can be used | ui-icon-search
searchtext | string | The text than can be set in the search button | empty
searchtitle | string | The title that appear when we mouse over to the search button (if enabled) | Find records
view | boolean | Enables or disables the view button in the pager. When the button is clicked a viewGridRow method is executed | false
viewicon | string | Set a icon to be displayed if the search action is enabled. Note that currently only icons from UI theme images can be used | ui-icon-document
viewtext | string | The text that can be set in the view button | empty
viewtitle | string | The title that appear when we mouse over to the view button (if enabled) | View selected row

Additionally to this there is a way to add a custom button in the navigator with action defined from the developer

Custom Buttons

Custom Buttons are a way to define your own button and action in the pager.

The creation of custom button should be done with
callGridMethod where the seciond parameter is navButtonAdd

something like:

$grid->callGridMethod("#grid", "navButtonAdd", $buttonoptions);

where $buttonoptions is array containing the options

The default options are

Property | Type | Description | Default
caption | string | The caption of the button | New button
buttonicon | string | The ui icon name from UI theme icon set | ui-icon-newwin
onClickButton | function | Action to be performed when a button is clicked | null
position | string | (“first” or “last”) The position where the button will be added (i.e., before or after the standard buttons) | last
title | string | tooltip for the button | empty
cursor | string | Determines the cursor when we mouseover the element | pointer
id | string | if set defines the id of the button (actually the id of TD element) for future manipulation | empty

Last Updated: 06/12/10 | © TriRand Ltd., 2011


 Search Options and Events
Search Options and Events
As of version 4.0 the following new features are available

  • Support multiple grouping which means that a complex search crieteria can be build something like:
    WHERE ( (field1 > 1 AND field1 < 10) OR (field1 LIKE 'a%') )
  • Search templates which simplify the user searching on most used search expressions
  • Validating user input when search. In irder to do this a searchrules property should be set
  • Showing the builded query

Searching is a way to search data (at server) on one or more field(s) at a time. When using this method we construct a modal form where the user can select a field and condition to apply the search. By default the search dialog is configured to use searching on multiple fields.
In order to change a option or event connected with the serching the following two methods should be used

setNavEvent
setNavOptions

with first parameter 'search'

By example if you want that the modal window should be not draggable do this

$grid->setNavOptions('search',array("drag"=>false));

This method uses the following properties from language file grid.locale-xx and the can be passed in the options array of the serch method

$.jgrid = {
...
   search : {
     caption: "Search...",
     Find: "Find",
     Reset: "Reset",
     odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'],
     groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ],
     matchText: " match",
     rulesText: " rules"
   },
...

Option | Type | Description | Default
afterShowSearch | function | This event fires (if defined) every time after the search dialog is shown | null
beforeShowSearch | function | This event fires (if defined) every time before the search dialog is shown | null
drag | boolean | Enables or disables draging of the modal | true
caption | string | The caption of the modal | see lang file
closeAfterSearch | boolean | If set to true this closes the search dialog after the user apply a search - i.e. click on Find button | false
closeOnEscape | boolean | If set to true the dialog is closed when the user pres ESC key | false
Find | string | The text in the find button | see lang file
groupOps | array | translations strings used in advanced searching | see lang file
matchText | string | Translation text used in advanced searching | see lang file
modal | boolean | Set if the search dialog shopuld be modal | false
overlay | integer | Set the overlay of the search dialog. If set to 0 no overlay and the dialog can stay interactive allowing any other interactions into the page | 10
multipleSearch | boolean | If set to true this activates the advanced searching | false
multipleGroup | boolean | If set to true this activates searching with multiple complex groups | false
top | integer | The top position of the dialog relative to grid upper left corner | 0
left | integer | The left position of the dialog relative to grid upper left corner | 0
showQuery | boolean | If set to true show the builded query to the user below the caption of the modal | false
errorcheck | boolean | This option determines if the validation should be performed - i.e if a rules are defined and there is a error in user input then the search is not performed | true
showOnLoad | boolean | The option is valid if the dialog is a part of the pager. Setting this option to true activates the search dialog if the grid is constructed | false
tmplNames | array | The option should be used wit tmplFilters and sets the names of the user defined search template criterias | empty
tmplFilters | empty array | Stores the diffterent user defined templates. Every element in the array is object with the appropriate setting. See the exmples how to set up templates | empty array
odata | array | Translation strings that corresponds to the sopt options | see lang file
onClose | function | If defined this event fires when the dialog is closed. Can return true or false. If the event return false the dialog will not be closed | null
onInitializeSearch | function | This event occurs only once when the modal is created | null
recreateFilter | boolean | When set to true the entry filter is destroyed unbinding all the events and it is constructed again. Use this option if you change dynamically some properties in colModel, so that they have effect | false
Reset | string | The text for the clear (reset) button | see lang file
rulesText | string | Translation text used in advanced searching | see lang file
sField | string | See sopt description | searchField
sFilter | string | Aplicable to multiple searching. | filters
sOper | string | See sopt description | searchOper
sopt | array | Use this option to set common search rules. If not set all the available options will be used. All available option are: ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'] The corresponding texts are in language file and mean the following: ['equal','not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'] Note that the elements in sopt array can be mixed in any order. |
sValue | string | See sopt description | searchString

searchoptions hat can be set in colModel contain the following properties

Property

Type

Description

dataUrl

string

This option is valid only for the elements of type select - i.e stype:'select'. The option represent the url from where we load the select element. When this option is set the element will be filled with values from the ajax request. The data should be a valid html select element with the desired options. By example the request should contain <select><option value=“1”>One</option> <option value=“2”>Two</option></select>. This is called only once.

buildSelect

function

This option have sense only if the dataUrl parameter is set. In case where the server response can not build the select element you can use your on function to build the select. The function should return a string containing the select and options value(s) as described in dataUrl option. Parameter passed to this function is the server response

dataInit

function

If set this function is called only once when the element is created. To this function we pass the element object.
dataInit: function(elem) {
do something
}
Also use this function to attach datepicker, time picker and etc. Example:
dataInit : function (elem) {
$(elem).datepicker();
}

dataEvents

array

List of events to apply to the data element; uses $(”#id”).bind(type, [data], fn) to bind events to data element. Should be described like this:
dataEvents: [
{ type: 'click', data: { i: 7 }, fn: function(e) { console.log(e.data.i); }},
{ type: 'keypress', fn: function(e) { console.log('keypress'); } }
]

attr

object

attr is object where we can set valid attributes to the created element. By example:
attr : { title: “Some title” }
Will set a title of the searched element

searchhidden

boolean

By default hidden elemnts in the grid are not searchable . In order to enable searching when the field is hidden set this option to true

sopt

array

This option is used only in advanced single field searching and determines the operation that is applied to the element. If not set all the available options will be used. All available option are:
['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
The corresponding texts are in language file and mean the following:
['equal','not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain']
Note that the elements in sopt array can be mixed in any order.

defaultValue

string

If not empty set a default value in the search input element.

value

mixed

The option is used only for stype select and defines the select options in the search dialogs. When set for stype select and dataUrl option is not set, the value can be a string or object.
If the option is a string it must contain a set of value:label pairs with the value separated from the label with a colon (:) and ended with(;). The string should not ended with a (;)- editoptions:{value:“1:One;2:Two”}.If set as object it should be defined as pair name:value - editoptions:{value:{1:'One';2:'Two'}}

searchrules

This option add additional properties to the search element and should be used in colModel. It is used to validate the user input before submitting the search(s) to the server.

Syntax:

<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array( "searchrules"=>array("searchhidden"=>true, "required"=>true...), ..));
...

$grid->renderGrid(...);
...
?>

Below is the list of available options:
Option | Type | Description
searchhidden | boolean | This option is valid only in search module. By default the hidden fields are not searchable. If the field is hidden in the grid and searchhidden is set to true, the field appear in search
required | boolean | (true or false) if set to true, the value will be checked and if empty, an error message will be displayed.
number | boolean | (true or false) if set to true, the value will be checked and if this is not a number, an error message will be displayed.
integer | boolean | (true or false) if set to true, the value will be checked and if this is not a integer, an error message will be displayed.
minValue | number(integer) | if set, the value will be checked and if the value is less than this, an error message will be displayed.
maxValue | number(integer) | if set, the value will be checked and if the value is more than this, an error message will be displayed.
email | boolean | if set to true, the value will be checked and if this is not valid e-mail, an error message will be displayed
url | boolean | if set to true, the value will be checked and if this is not valid url, an error message will be displayed
date | boolean | if set to true a value from datefmt option is get (if not set ISO date is used) and the value will be checked and if this is not valid date, an error message will be displayed
time | boolean | if set to true, the value will be checked and if this is not valid time, an error message will be displayed. Currently we support only hh:mm format and optional am/pm at the end
custom | boolean | if set to true allow definition of the custom checking rules via a custom function. See below
custom_func | function | this function should be used when a custom option is set to true. Parameters passed to this function are the value, which should be checked and the name - the property from colModel. The function should return array with the following parameters: first parameter - true or false. The value of true mean that the checking is successful false otherwise; the second parameter have sense only if the first value is false and represent the error message which will be displayed to the user. Typically this can look like this [false,”Please enter valid value”]

Last Updated: 03/21/11 | © TriRand Ltd., 2011


 Toolbar Filter
Toolbar Filter
This method construct searching creating input elements just below the header elements of the grid. When the header elements are re sized the input search elements are also re sized according to the new width.

By default this feature is disabled. To enable the fature it is needed to set the toolbarfilter option to true.

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->toolbarfilter = true;
$grid->renderGrid(...);
?>

To change a option(s) (listed below) in toolbar filter a setFilterOptions method should be used. By default the search is performed when the user type the search word and press Enter. If we want to change this behaviour -i.e perform immediate search we can do this.

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->toolbarfilter = true;
$grid->setFilterOptions(array("searchOnEnter"=>false));
$grid->renderGrid(...);
?>

The options in filterToolbar method are:

Option | type | Description | Default
autosearch | boolean | Search is performed according to the following rules: for text element when a Enter key is pressed while inputting values and search is performed. For select element when the value changes. The search parameter in grid is set to true and ajax call is made. | true
beforeSearch | function | event which fires before a search. It is called before triggering the grid. If the event return true triggering does not occur. In this case you can construct your own search parameters and trigger the grid to search the data. Any other return value causes triggering. | null
afterSearch | function | event which fires after a search | null
beforeClear | function | event which fires before clearing entered values (i.e.,clearToolbar is activated).It is called before clearing the data from search elements. If the event return true triggering does not occur. In this case you can construct your own search parameters and trigger the grid. Any other return value causes triggering. | null
afterClear | function | event which fires after clearing entered values (i.e., clearToolbar activated) | null
searchOnEnter | boolean | Determines how the search should be applied. If this option is true see the autosearch option. If the option is false then the search is performed immediately when the user pres some character | true
stringResult | boolean | Determines how to post the data on which we perform searching. When the this option is false the posted data is in key:value pair, if the option is true, the posted data is equal on those as in searchGrid method | true
groupOp | string | This option is valid only if the option stringReasult is set to true and determines the group operation. Can have values AND and OR. | AND

When we create toolbar search with filterToolbar we create additional methods as follow. The method should be called with JavaScript code.

Method | Description
triggerToolbar | When this method is called a search is performed, the search parameter in grid becomes true and ajax call is made to the server
clearToolbar | When called clear the search values send a request with search option set to false and set the default one if available
toggleToolbar | Toggeles the toolbar with the search elements

Using the additional methods

The methods listed above should be used this way:

...
var sgrid = $("#grid")[0];
sgrid.triggerToolbar();
...

This will perform a search dynamically.

Last Updated: 06/12/10 | © TriRand Ltd., 2011


 Editing
Editing

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Cell Editing options and events
Cell Editing options and events
cellEditing supports key navigation and editing individual cells, with the following behaviour:

  • When we click on a cell that is not editable, the cell is selected and we can use the up, down, left and right keys to navigate through the cells.
  • If we move to a cell that is editable, we can press [Enter] to edit the cell. The cell is saved when we press [Enter] again, when we press [Tab], or when we click on another cell. If we press [ESC], the cell is not saved. When editing a cell, the cursor keys move only within the cell.
  • When we click on cell that is editable, then we go directly into edit mode.
  • The cell is not editable if it has a class 'not-editable-cell', instead that in colModel is set to be editable

The properties, events and methods used in cell editing are a sub-set of those of the parent grid, and described below.
The above mean that when cell editing is used the following method should be used

setGridOptions - to set a option for cell editing
setGridEvent - to set a event related to cell editing.

Properties

Property | Type | Description | Default
cellEdit | boolean | Enables (disables) cell editing. When this option is set to true, onSelectRow event can not be used, and hovering is disabled (when mouseover on the rows). | false
cellsubmit | string | Determines where the contents of the cell are saved - can have two values: 'remote' or 'clientArray'. If remote the content is immediately saved to the server using the cellurl property, via ajax. The rowid and the cell content are added to the url as name:value pairs. For example, if we save the cell named mycell,{id: rowid, mycell: cellvalue} is added to the url. If 'clientArray', no ajax request is made and the content of the changed cell can be obtained via the method getChangedCells | remote
cellurl | string | the url where the cell is to be saved | null
ajaxCellOptions | array | This option allow to set global ajax settings for the cell editiing when we save the data to the server. Note that with this option is possible to overwrite all current ajax setting in the save request including the complete event. | empty array

Events

Many of the following events use the parameters defined here:

  • rowid - is the id of the row
  • cellname is the name of the cell (name from colModel)
  • value - the value of the cell
  • iRow - the index of the row (do not mix with rowid)
  • iCol - the index of the column

Event

Parameters

Description

afterEditCell

rowid, cellname, value, iRow, iCol

applies only to a cell that is editable; this event fires after the edited cell is edited - i.e. after the element is inserted into the DOM

afterSaveCell

rowid, cellname, value, iRow, iCol

applies only to a cell that is editable; this event fires after the cell has been successfully saved. This is the ideal place to change other content.

afterSubmitCell

serverresponse, rowid, cellname, value, iRow, iCol

applies only to a cell that is editable; this event Fires after the cell and other data is posted to the server Should return array of type [success(boolean),message] when return [true,””] all is ok and the cellcontent is saved [false,”Error message”] then a dialog appears with the “Error message” and the cell content is not saved. servereresponse is the response from the server. To use this we should use serverresponse.responseText to obtain the text message from the server.

beforeEditCell

rowid, cellname, value, iRow, iCol

applies only to a cell that is editable; this event fires before editing the cell.

beforeSaveCell

rowid, cellname, value, iRow, iCol

applies only to a cell that is editable; this event fires before validation of values if any. This event can return the new value which value can replace the edited one
beforeSaveCell : function(rowid,celname,value,iRow,iCol) {
if( some_condition )
{ return “new value”; }
}
The value will be replaced with “new value”

beforeSubmitCell

rowid, cellname, value, iRow, iCol

applies only to a cell that is editable; this event fires before submit the cell content to the server (valid only if cellsubmit : 'remote'). Can return new array that will be posted to the server.
beforeSubmitCell : function(rowid,celname,value,iRow,iCol) {
if( some_condition ) {
return {name1:value1,name2:value2}
}
else
{ return {} }
}
The returned array will be added to the cellurl posted data.

errorCell

serverresponse, status

fires if there is a server error; servereresponse is the response from the server. To use this we should apply serverresponse.responseText to obtain the text message from the server. status is the status of the error. If not set a modal dialog apper.

formatCell

rowid, cellname, value, iRow, iCol

applies only to a cell that is editable; this event allows formatting the cell content before editing, and returns the formatted value

onSelectCell

rowid, celname, value, iRow, iCol

applies only to cells that are not editable; fires after the cell is selected

serializeCellData

postdata

If set this event can serialize the data passed to the ajax request when we save a cell. The function should return the serialized data. This event can be used when a custom data should be passed to the server - e.g - JSON string, XML string and etc. To this event is passed the data which will be posted to the server

Below is the order of which the events are called when the cellsubmit option is 'remote'

if a cell is editable then
1. formatCell - format and the value of the cell can be changed before editing
2. beforeEditCell
3. afterEditCell - after the input element is created
4. beforeSaveCell
5. beforeSubmitCell
if the submit is successfully
6. afterSubmitCell
7. afterSaveCell
else
6. errorCell
else if the cell is not editable
1. onSelectCell

If the cellsubmit is 'clientArray' then
if a cell is editable then
1. formatCell - format and the value of the cell can be changed before editing
2. beforeEditCell
3. afterEditCell - after the input element is created
4. beforeSaveCell
5. beforeSubmitCell
6. afterSaveCell
else if the cell is not editable
1. onSelectCell

How is the data organized

When the cell is edited and the input elements is created we set the following rules:

  • The id of the editable cell element is constructed as 'iRow_'+ the name from the colModel array - where the iRow is the index of the row (not rowid) Example if we edit cell with index=20 and editable element has name 'myname' (from colModel) then the id becomes 20_myname.
  • The name of the editable element is constructed from the name of the colModel array - property - name

What is posted to the server?

When the data is posted to the server we construct object {} that contain:

  • the name:value pair where the name is the name of the input element represented in the cell
  • additionally we add a pair id:rowid where the rowid is the id of the row
  • if the returned data from beforeSubmitCell event is not empty we extend this data with the posted data.

Last Updated: 11/03/10 | © TriRand Ltd., 2011


 Inline Editing options
Inline Editing options
Inline editing is a quick way to update database information by supporting editing directly in the row of the grid.
In order to integrate this feature easy with PHP we have created a formatter named actions where with a single line of code this feature can meet your requirments. See the implementation here

If you want to use this feature in your application with logic different in the one that is provided in the formatter actions, you should write a custom Java Script code.

In this case you can use one of the following PHP methods

setGridEvent
callGridMethod
setJSCode

Below we list the JavaScript Methods that can be used.

editRow

Calling conventions (JavaScript):

jQuery("#grid_id").jqGrid('editRow',rowid, keys, oneditfunc, succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);

where
  • grid_id is the already constructed grid
  • rowid: the id of the row to edit
  • keys: when set to true we can use [Enter] key to save the row and [Esc] to cancel editing.
  • oneditfunc: fires after successfully accessing the row for editing, prior to allowing user access to the input fields. The row's id is passed as a parameter to this function.

The row can not be edited if it has class 'not-editable-row' instead that in colModel some fields can have a property editable set to true.

When set in the editRow the parameter function oneditfunc should not be enclosed in quotes and not entered with () - show just the name of the function.

If keys is true, then the remaining settings – succesfunc, url, extraparam, aftersavefunc, errorfunc and afterrestorefunc - are passed as parameters to the saveRow method when the [Enter] key is pressed (saveRow does not need to be defined as jqGrid calls it automatically). For more information see saveRow method below.

When this method is called on particular row, jqGrid reads the data for the editable fields and constructs the appropriate elements defined in edittype and editoptions

saveRow

Saves the edited row.

jQuery("#grid_id").jqGrid('saveRow',rowid, succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);

where

  • rowid: the id of the row to save
  • succesfunc: if defined, this function is called immediately after the request is successful. This function is passed the data returned from the server. Depending on the data from server; this function should return true or false.
  • url: if defined, this parameter replaces the editurl parameter from the options array. If set to 'clientArray', the data is not posted to the server but rather is saved only to the grid (presumably for later manual saving).
  • extraparam: an array of type name: value. When set these values are posted along with the other values to the server.
  • aftersavefunc: if defined, this function is called after the data is saved to the server. Parameters passed to this function are the rowid and the response from the server request.
  • errorfunc: if defined, this function is called after the data is saved to the server. Parameters passed to this function are the rowid and the the response from the server request.
  • afterrestorefunc if defined, this function is called in restoreRow (in case the row is not saved with success) method after restoring the row. To this function we pass the rowid

When set in the saveRow the parameters functions should not be enclosed in quotes and not entered with () - show just the name of the function.

Except when url (or editurl) is 'clientArray', when this method is called, the data from the particular row is POSTED to the server in format name: value, where the name is a name from colModel and the value is the new value. jqGrid also adds, to the posted data, the pair id: rowid. For example,

jQuery("#grid_id").jqGrid('saveRow',"rowid", false);

will save the data to the grid and to the server, while

jQuery("#grid_id").jqGrid('saveRow',"rowid", false, 'clientArray');

will save the data to the grid without an ajax call to the server.

restoreRow

This method restores the data to original values before the editing of the row.

Calling convention:

jQuery("#grid_id").jqGrid('restoreRow',rowid, afterrestorefunc);

where

  • rowid is the row to restore
  • afterrestorefunc if defined this function is called in after the row is restored. To this function we pas the rowid

Remarks

How is the data organized

When the row is edited and the input elements are created we set the following rules:

  • the table row becomes attribute editable=“1”
  • the array savedRow (option in the grid) is filled with the values before the editing. This is a name:value pair array with additional pair id:rowid
  • Hidden fields are not included
  • The id of the editable element is constructed as 'rowid_'+ the name from the colModel array. Example if we edit row with id=10 and the only editable element is 'myname' (from colModel) then the id becomes 10_myname.
  • The name of the editable element is constructed from the name of the colModel array - property - name
  • after the row is saved or restored the editable attribute is set to “0” and the savedRow item with id=rowid is deleted

What is posted to the server?

When the data is posted to the server we construct an object {} that contain(s):

  • the name:value pair where the name is the name of the input element represented in the row (this is for all input elements)
  • additionally we add a pair id:rowid where the rowid is the id of the row
  • if the extraparam parameter is not empty we extend this data with the posted data
Last Updated: 05/02/10 | © TriRand Ltd., 2011


 Form Editing
Form Editing
jqGrid supports creating a form “on the fly” to view, add, edit, or delete grid data. The methods listed below are included in the navGrid (navigator method)
By default navigaror is disabled. To enable navigator just set the navigator variable to true

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->renderGrid(...);
?>

With this action we enable the following actions in pager - add, edit, del, search, refresh, export to excel.
The view action is disabled.
To disable some action in navigator use setNavOptions method specifiyng the word navigator. If by example we want to disable adding of records do this

<?php
...
// Create the jqGridRender instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('navigator',array('add'=>false));
$grid->renderGrid(...);
?>

To change a option in some module use the following methods

setNavOptions(...)
setNavEvent(...)

with first parameter refering to the desired module.
By example if we want to change the width and height of the form and want this to be constant in editing adding records do the following.

<?php
...
// Create the jqGridRender instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('edit',array("width"=>500, "height"=>300, "recreateForm"=>true));
$grid->renderGrid(...);
?>

editGridRow

Editing by default is disabled when the grid is created. To enable set navigator variable to true.
<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->renderGrid(...);
?>

To disable a editing in already created navigator you should use navigator property to disable the method
<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('navigator',araray("edit"=>false));
$grid->renderGrid(...);
?>

To set a particular option and event in the edit form use

setNavOptions(...)
setNavEvent(...)

with first parameter edit. i.e

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('edit',araray(...));
$grid->setNavEvent('edit',araray(...));
$grid->renderGrid(...);
?>

To call a method in custom java script code use the following convension.

jQuery("#grid_id").jqGrid('editGridRow', rowid, properties );

Where

  • grid_id: the id of the parent grid
  • rowid: the id of the row to edit
  • properties: an array of key => value pairs, including any of the following properties or events.

The method uses the following properties from language file:

$.jgrid = {
...
   edit : {
      addCaption: "Add Record",
      editCaption: "Edit Record",
      bSubmit: "Submit",
      bCancel: "Cancel",
      bClose: "Close",
      saveData: "Data has been changed! Save changes?",
      bYes : "Yes",
      bNo : "No",
      bExit : "Cancel",
...
   },
...
}

These options can be overwritten when passed as options to the method. When passed to the method we should use by example "bSubmit" => “Submit” and not "$.jgrid.edit.bSubmit" => “Submit”

Properties

Property | Description | Default
top | the initial top position of modal dialog. The default value of 0 mean the top position from the upper left corner of the grid. When jqModal option is true (see below) and jqModal plugin is present any value different from 0 mean the top position from upper left corner of the window. | 0
left | the initial left position of modal dialog. The default value of 0 mean the left position from the upper left corner of the grid. When jqModal option is true (see below) and jqModal plugin is present any value different from 0 mean the left position from upper left corner of the window. | 0
width | the width of confirmation dialog | 300
height | the entry height of confirmation dialog | auto
dataheight | the parameter control the scrolling content - i.e between the modal header and modal footer. | auto
modal | determines if the dialog will be modal. Also works only if jqModal plugin is present | false
overlay | Determines the overlay of the modal. Also works only if jqModal plugin is present | 10
drag | Determines if the dialog is dragabale. Works only if jqDnR plugin is present or if the dragable widget is present from jQuery UI | true
resize | determines if the dialog can be resized. Works only is jqDnR plugin is available or resizable widget is present from jQuery UI | true
url | url where to post data. If set, replaces the editurl | null
mtype | Defines the type of request to make (“POST” or “GET”) when data is sent to the server | POST
editData | an array used to add content to the data posted to the server | empty
recreateForm | when set to true the form is recreated every time the dialog is activeted with the new options from colModel (if they are changed) | false
jqModal | If set to true uses jqModal plugin (if present) to creat the dialogs. If set to true and the plugin is not present jqGrid uses its internal function to create dialog | true
addedrow | Controls where the row just added is placed: 'first' at the top of the gird, 'last' at the bottom. Where the new row is to appear in its natural sort order, set reloadAfterSubmit: true | first
topinfo | When set this information is placed just after the modal header as additional row | empty string
bottominfo | When set this information is placed just after the buttons of the form as additional row | empty string
saveicon | array. Determines the icon of the submit button. The default value is [true,”left”,”ui-icon-disk”]. The first item enables/disables the icon. The second item tells where to put the icon to left or to right of the text. The third item corresponds to valid ui icon from theme roller |
closeicon | Array. Determines the icon of the cancel button. The default values are [true,”left”,”ui-icon-close”]. For description of these see saveicon |
savekey | array. Determines the possibility to save the form with pressing a certain key.The first item enables/disables saving with pressing certain key. The second item corresponds to key code for saving. If enabled the default value for saving is [Enter]. Note that this binding should be used for both adding and editing a row. Since the binding is for the form, there is no possibility to have one key in add and another in edit mode. | [false,13]
navkeys | array. This option works only in edit mode and add keyboard navigation, which allow us to navigate through the records while in form editing pressing certain keys. The default state is disabled. The first item enables/disables the navigation. The second item corresponds to reccord up and by default is the the key code for Up key. The third item corresponds to reccord down and by default is the key code for Down key | [false,38,40]
checkOnSubmit | This option work only in editing mode. If Set to true this option will work only when a submit button is clicked and if any data is changed in the form. If the data is changed a dilog message appear where the user is asked to confirm the changes or cancel it. Pressing cancel button of the new dialog will return to the form, but does not set the values to its original state. | false
checkOnUpdate | This option is applicable in add and edit mode. When this option is set to true the behaviour as follow: when something is changed in the form and the user click on Cancel button, navigator buttons, close button (on upper right corner of the form), in overlay (if available) or press Esc key (if set) a message box appear asking the user to save the changes, not to save the changes or go back in the grid cancel all changes (this will close the modal form) | false
closeAfterAdd | when add mode, close the dialog after add record | false
clearAfterAdd | when add mode, clear the data after adding data | true
closeAfterEdit | when in edit mode, close the dialog after editing | false
reloadAfterSubmit | reload grid data after posting | true
closeOnEscape | When set to true the modal window can be closed with ESC key from the user. | false
ajaxEditOptions | This option allow to set global ajax settings for the form editiing when we save the data to the server. Note that with this option is possible to overwrite all current ajax setting in the save request including the complete event. | empty array
viewPagerButtons | This option enable or disable the appearing of the previous and next buttons (pager buttons) in the form | true

Events

Event

Description

afterclickPgButtons

This event can be used only when we are in edit mode and the navigator buttons are enabled; it fires after the data for the new row is loaded from the grid, allowing modification of the data or form before the form is redisplayed.
afterclickPgButtons : function(whichbutton, formid, rowid) {…}
where
whichbutton is either 'prev' or 'next'
formid is the id of the form
rowid is the id of the current row

afterComplete

This event fires immediately after all actions and events are completed and the row is inserted or updated in the grid.
afterComplete : function (response, postdata, formid) {…}
where
response is the data returned from the server (if any)
postdata an array, is the data sent to the server
formid is the id of the form

afterShowForm

fires after showing the form; receives as Parameter the id of the constructed form.
afterShowForm : finction (formid) {…}

afterSubmit

fires after response has been received from server. Typically used to display status from server (e.g., the data is successfully saved or the save cancelled for server-side editing reasons). Receives as parameters the data returned from the request and an array of the posted values of type id=value1,value2.
When used this event should return array with the following items [success, message, new_id]
where
success is a boolean value if true the process continues, if false a error message appear and all other processing is stopped. (message is ignored if success is true).
new_id can be used to set the new row id in the grid when we are in add mode.
afterSubmit : function(response, postdata)
{
…
return [success,message,new_id]
}

beforeCheckValues

This event fires before checking the values (if checking is defined in colModel via editrules option).
To this event we pass the following parameters:
1. posdata - the array of values which should be chaced in name:value pair, where the name is the name from colModel.
2. formid - the form id object.
3. mode - the current mode in which we are - can be add or edit.
In all cases the event should return object in name value pair which then will be posted to the server.

beforeInitData

fires before initialize the new form data. Receives, as parameter, the id of the constructed form.
beforeInitData : function(formid) {…}

beforeShowForm

fires before showing the form with the new data; receives as Parameter the id of the constructed form.
beforeShowForm : function(formid) {…}

beforeSubmit

fires before the data is submitted to the server. Recieves as parameter the posted data array and the formid.
beforeSubmit : function(postdata, formid) {
…
return[success,message];
}
When defined this event should return array with the following values
success boolean indicating if the proccess should continue (true) or a error (false) message should appear to the user

onclickPgButtons

This event can be used only when we are in edit mode; it fires immediately after the previous or next button is clicked, before leaving the current row, allowing working with (e.g., saving) the currently loaded values in the form.
onclickPgButtons : function (whichbutton, formid, rowid) {…}
where
whichbutton is either 'prev' or 'next'
formid is the id of the form
rowid is the id of the current row

onclickSubmit

fires after the submit button is clicked and the postdata is constructed. Parameters passed to this event are: a options array of the method and the posted data array. The event should return array of type {} which extends the postdata array.
onclickSubmit : function(params, posdata) {
…
return {add_data}
}

onInitializeForm

fires only once when creating the data for editing and adding. Receives, as parameter, the id of the constructed form.
onInitializeForm : function(formid) {…}

onClose

This event is called just before closing the form and when a close icon is clicked, a cancel button is clicked, ESC key is pressed or click on overlay (if jqModal is present). The event can return (optionally) true or false. If the return value is true the form is closed, if false the form does not close. If nothing is returned the form is closed

errorTextFormat

The event (can) fire when error occurs from the ajax call and can be used for better formatting of the error messages. To this event is passed response from the server. The event should return single message (not array), which then is displayed to the user.

serializeEditData

If set this event can serialize the data passed to the ajax request when we save a form data. The function should return the serialized data. This event can be used when a custom data should be passed to the server - e.g - JSON string, XML string and etc. To this event is passed the data which will be posted to the server

How is the form constructed

When the form is constructed we set the following rules:

  • Hidden fields are included in the form with the display:none property of the table row
  • The id of the editable element is constructed from the name of the colModel array - propery - name
  • The name of the editable element is constructed from the name of the colModel array - propery - name
  • For ease in manipulating the elements in an edit form, every table row in the form that holds the data for the edit has a id which is a combination of “tr_” + name (from colmodel). Example:

<form ....>
  <table>
    <tr id='tr_myfield'>
      <td> Caption</td> <td>edited element named, in colModel, as "myfield"</td>
    </tr> ...
  </table>
</form>

This allow us to easily show or hide some table rows depending on conditions using beforeShowForm event
What is posted to the server

When we are in editing mode the data that is posted to the server is object {} that contain:

  • the name:value pair where the name is the name of the input element represented in the form (this is for all input elements)
  • additionally we add a pair id:rowid where the rowid is the id of the edited row (the name id is replaced automatically with the primaryKey name)
  • additionally we add a pair oper:edit to indicate the edit mode
  • if the editData object is not empty we extend this data with the posted data
  • if the returned object from onclickSubmit event is not empty we extend the posted data with this object

Adding Row

Adding by default is disabled when the grid is created. To enable set navigator variable to true.
<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->renderGrid(...);
?>

To disable a adding in already created navigator you should use navigator property to disable the method

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('navigator',araray("add"=>false));
$grid->renderGrid(...);
?>

To set a particular option and event in the add form use

setNavOptions(...)
setNavEvent(...)

with first parameter add. i.e

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('add',araray(...));
$grid->setNavEvent('add',araray(...));
$grid->renderGrid(...);
?>

This method uses Common Editing Properties from colModel and editurl option from jqGrid

The editGridRow method is also used to add data to the server, by passing “new” as the rowid when called in custom JavaScript code

This method uses Common Editing Properties from colModel and editurl option from jqGrid.

Calling convention:

jQuery("#grid_id").jqGrid('editGridRow, "new", properties );

Where

  • grid_id: the id of the parent grid
  • properties: an array of name: value pairs, including any of the following properties or events.

The method uses the following properties from language file:

$.jgrid = {
...
   edit : {
      addCaption: "Add Record",
      editCaption: "Edit Record",
      bSubmit: "Submit",
      bCancel: "Cancel",
      bClose: "Close",
      saveData: "Data has been changed! Save changes?",
      bYes : "Yes",
      bNo : "No",
      bExit : "Cancel",
...
   },
...
}

The options are the same as those in editng row - See above.

How is the form constructed

When the form is constructed we set the following rules:

  • Hidden fields are included in the form with the display:none property of the table row
  • The id of the editable element is constructed from the name of the colModel array - propery - name
  • The name of the editable element is constructed from the name of the colModel array - propery - name
  • For ease in manipulating the elements in an edit form, every table row in the form that holds the data for the edit has a id which is a combination of “tr_” + name (from colmodel). Example:

<form ....>
  <table>
    <tr id='tr_myfield'>
      <td> Caption</td> <td>edited element named, in colModel, as "myfield"</td>
    </tr> ...
  </table>
</form>

This allow us to easily show or hide some table rows depending on conditions using beforeShowForm event
What is posted to the server

When we are in add mode the data that is posted to the server is object {} that contain:

  • the name:value pair where the name is the name of the input element represented in the form (this is for all input elements)
  • additionally we add a pair id:_empty where the _empty indicates that new row is inserted
  • additionally we add a pair oper:add to indicate the add mode
  • if the editData object is not empty we extend this data with the posted data
  • if the returned object from onclickSubmit event is not empty we extend the posted data with this object

viewGridRow

This method is similar to the editGridRow method except that the fields are not editable.
View by default is disabled when the grid is created. To enable set navigator variable to true and navigator property to enable the method

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('navigator',araray("view"=>true));
$grid->renderGrid(...);
?>

To set a particular option and event in the view form use

setNavOptions(...)
setNavEvent(...)

with first parameter view. i.e

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('view',araray(...));
$grid->setNavEvent('view',araray(...));
$grid->renderGrid(...);
?>

To call a method in custom java script code use the following convension.

jQuery("#grid_id").jqGrid('viewGridRow', rowid, properties );

Where

  • grid_id: the id of the parent grid
  • rowid: the id of the row to edit
  • properties: an array of name: value pairs, including any of the following properties or events.

The method uses the following properties from language file:

$.jgrid = {
...
   view : {
      caption: "View Record",
      bClose: "Close"
   },
...

Properties

Property | Description | Default
top | the initial top position of modal dialog. The default value of 0 mean the top position from the upper left corner of the grid. When jqModal option is true (see below) and jqModal plugin is present any value different from 0 mean the top position from upper left corner of the window. | 0
left | the initial left position of modal dialog. The default value of 0 mean the left position from the upper left corner of the grid. When jqModal option is true (see below) and jqModal plugin is present any value different from 0 mean the left position from upper left corner of the window. | 0
width | the width of confirmation dialog | 300
height | the entry height of confirmation dialog | auto
dataheight | the parameter control the scrolling content - i.e between the modal header and modal footer. | auto
modal | determines if the dialog will be modal. Also works only if jqModal plugin is present | false
drag | Determines if the dialog is dragabale. Works only if jqDnR plugin is present or if the dragable widget is present from jQuery UI | true
resize | determines if the dialog can be resized. Works only is jqDnR plugin is available or resizable widget is present from jQuery UI | true
jqModal | If set to true uses jqModal plugin (if present) to creat the dialogs. If set to true and the plugin is not present jqGrid uses its internal function to create dialog | true
topinfo | When set this information is placed just after the modal header as additional row | empty string
bottominfo | When set this information is placed just after the buttons of the form as additional row | empty string
closeicon | Array. Determines the icon of the cancel button. The default values are [true,”left”,”ui-icon-close”]. For description of these see saveicon |
navkeys | array. This option works only in edit mode and add keyboard navigation, which allow us to navigate through the records while in form editing pressing certain keys. The default state is disabled. The first item enables/disables the navigation. The second item corresponds to reccord up and by default is the the key code for Up key. The third item corresponds to reccord down and by default is the key code for Down key | [false,38,40]
closeOnEscape | When set to true the modal window can be closed with ESC key from the user. | false
labelswidth | Since we construct the view with table element it is difficult to calculate, in this case, how much width is needed for the labels. Depending on the needs this value can be increased or decreased | 30%
viewPagerButtons | This option enable or disable the appearing of the previous and next buttons (pager buttons) in the form | true

Events

Event | Description
onClose | This event is called just before closing the form and when a close icon is clicked, a cancel button is clicked, ESC key is pressed or click on overlay (if jqModal is present). The event can return (optionally) true or false. If the return value is true the form is closed, if false the form does not close. If nothing is returned the form is closed
beforeShowForm | fires before showing the form with the new data; receives as Parameter the id of the constructed form. beforeShowForm : function(formid) {…}

When the form is constructed we set the following rules:

  • No input elements are created
  • Hidden fields are included in the form with the display:none property of the table row
  • The id of the viewed element is constructed from “v_” + the name of the colModel array - propery - name
  • For ease in manipulating the elements in an edit form, every table row in the form that holds the data for the edit has a id which is a combination of “trv_” + name (from colmodel). Example:

<form ....>
  <table>
    <tr id='trv_myfield'>
      <td> Caption</td> <td id="v_myfield"><span>content of"myfield"</span></td>
    </tr> ...
  </table>
</form>

delGridRow - deleting a row

With this method we can perform a delete operation at server side.
This method uses colModel and editurl parameters from jqGrid

Deleting by default is disabled when the grid is created. To enable set navigator variable to true.

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->renderGrid(...);
?>

To disable a deleting in already created navigator you should use navigator property to disable the method
<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('navigator',araray("del"=>false));
$grid->renderGrid(...);
?>

To set a particular option and event in the delete form use

setNavOptions(...)
setNavEvent(...)

with first parameter del. i.e

<?php
...
// Create the jqGrid instance
$grid = new jqGridRender($conn);
...
$grid->navigator = true;
$grid->setNavOptions('del',araray(...));
$grid->setNavEvent('del',araray(...));
$grid->renderGrid(...);
?>

To call a method in custom java script code use the following convension.

jQuery("#grid_id").jqGrid('delGridRow', row_id_s, options );

Where:

  • grid_id: the id of the parent grid
  • row_id_s: the id of the row(s) to delete; can be a single value or list of ids separated by comma
  • options: an array of name: value pairs, including any of the following properties or events.

The method uses the following properties from language file:

$.jgrid = {
...
   del : {
      caption: "Delete",
      msg: "Delete selected record(s)?",
      bSubmit: "Delete",
      bCancel: "Cancel"
   },
...

These options can be overwritten when passed as options to the method. When passed to the method we should use by example "bSubmit" => “Delete” and not "$.jgrid.del.bSubmit" => “Delete”

Properties

Property | Description | Default
top | the initial top position of modal dialog. The default value of 0 mean the top position from the upper left corner of the grid. When jqModal option is true (see below) and jqModal plugin is present any value different from 0 mean the top position from upper left corner of the window. | 0
left | the initial left position of modal dialog. The default value of 0 mean the left position from the upper left corner of the grid. When jqModal option is true (see below) and jqModal plugin is present any value different from 0 mean the left position from upper left corner of the window. | 0
width | the width of confirmation dialog | 300
height | the entry height of confirmation dialog | auto
dataheight | the parameter control the scrolling content - i.e between the modal header and modal footer. | auto
modal | determines if the dialog will be modal. Also works only if jqModal plugin is present | false
drag | Determines if the dialog is dragabale. Works only if jqDnR plugin is present or if the dragable widget is present from jQuery UI | true
resize | determines if the dialog can be resized. Works only is jqDnR plugin is available or resizable widget is present from jQuery UI | true
url | url where to post data. If set, replaces the editurl | null
mtype | Defines the type of request to make (“POST” or “GET”) when data is sent to the server | POST
delData | an array used to add content to the data posted to the server | empty
jqModal | If set to true uses jqModal plugin (if present) to creat the dialogs. If set to true and the plugin is not present jqGrid uses its internal function to create dialog | true
delicon | array. Determines the icon of the submit button. The default value is [true,”left”,”ui-icon-delete”]. The first item enables/disables the icon. The second item tells where to put the icon to left or to right of the text. The third item corresponds to valid ui icon from theme roller |
cancelicon | Array. Determines the icon of the cancel button. The default values are [true,”left”,”ui-icon-cancel”]. For description of these see delicon |
reloadAfterSubmit | reload grid data after posting | true
closeOnEscape | When set to true the modal window can be closed with ESC key from the user. | false
ajaxDelOptions | This option allow to set global ajax settings for the form editiing when we delete the data to the server. Note that with this option is possible to overwrite all current ajax setting in the delete request including the complete event. | empty array

Events

Event

Description

afterComplete

This event fires immediately after all actions and events are completed and the row is inserted or updated in the grid.
afterComplete : function (response, postdata, formid) {…}
where
response is the data returned from the server (if any)
postdata an array, is the data sent to the server
formid is the id of the form

afterShowForm

fires after showing the form; receives as Parameter the id of the constructed form.
afterShowForm : finction (formid) {…}

afterSubmit

fires after response has been received from server. Typically used to display status from server (e.g., the data is successfully deleted or the delete cancelled for server-side reasons). Receives as parameters the data returned from the request and an array of the posted values of type id=value1,value2.
When used this event should return array with the following items [success, message]
where
success is a boolean value if true the process continues, if false a error message appear and all other processing is stoped.
afterSubmit : function(response, postdata)
{
…
return [succes,message]
}

beforeShowForm

fires before showing the form with the new data; receives as Parameter the id of the constructed form.
beforeShowForm : function(formid) {…}

beforeSubmit

fires before the data is submitted to the server. Recieves as parameter the posted data array and the formid.
beforeSubmit : function(postdata, formid) {
…
return[success,message];
}
When defined this event should return array with the following values
success boolean indicating if the proccess should continue (true) or a error (false) message should appear to the user

onclickSubmit

fires after the submit button is clicked and the postdata is constructed. Parameters passed to this event is a options array of the method. The event should return array of type {} which extends the postdata array.
onclickSubmit : function(params) {
…
return {add_data}
}

onClose

This event is called just before closing the form and when a close icon is clicked, a cancel button is clicked, ESC key is pressed or click on overlay (if jqModal is present). The event can return (optionally) true or false. If the return value is true the form is closed, if false the form does not close. If nothing is returned the form is closed

What is posted to the server

When we are in delete mode the data that is posted to the server is object {} that contain:

  • the pair id:rowids where the rowids can be a single value a value string separated with comma in case of multiple selection (The name id is automatically replaced with the primaryKey from scrip)
  • additionally we add a pair oper:del to indicate the delete mode
  • if the delData object is not empty we extend this data with the posted data
  • if the returned object from onclickSubmit event is not empty we extend the posted data with this object

Last Updated: 01/12/11 | © TriRand Ltd., 2011


 Java Script Grid Methods
Java Script Grid Methods
Below is the list of Java Script jqGrid methods. These methods can be either called with callGridMethod or setJSCode

Method | Parameters | Returns | Description
addRowData | rowid, data, position, srcrowid | true on success, false otherwise | Inserts a new row with id = rowid containing the data in data (an object) at the position specified (first in the table, last in the table or before or after the row specified in srcrowid). The syntax of the data object is: {name1:value1,name2: value2…} where name is the name of the column as described in the colModel and the value is the value. This method can insert multiple rows at once. In this case the data parameter should be array defined as [{name1:value1,name2: value2…}, {name1:value1,name2: value2…} ] and the first option rowid should contain the name from data object which should act as id of the row. It is not necessary that the name of the rowid in this case should be a part from colModel.
clearGridData | clearfooter | jqGrid object | Clears the currently loaded data from grid. If the clearfooter parameter is set to true, the method clears the data placed on the footer row.
delRowData | rowid | true on success, false otherwise | Deletes the row with the id = rowid. This operation does not delete data from the server.
footerData | action, data, format | jqGrid object | This method gets or sets data on footer. See footerrow in options array. action - can be 'get' or 'set'. The default is get. 'get' returns an object of type name:value, where the name is a name from colModel. This will return data from the footer. The other two options have no effect in this case. 'set' takes a data array (object) and places the values in the footer. The object should be in name:value pair, where the name is the name from colModel format - default is true. This instruct the method to use the formatter (if set in colModel) when new values are set. A value of false will disable the using of formatter
getCell | rowid, iCol | cell content | Returns the content of the cell specified by id = rowid and column = iCol. iCol can be either the column index or the name specified in colModel.
getCol | colname, returntype, mathoperation | array[] or value | This method returns an array with the values from the column. colname can be either a number that represents the index of the column or a name from colModel. returntype determines the type of the returned array. When set to false (default) the array contain only the values. When set to true the array contain a set of objects. The object is defined as {id:rowid, value:cellvalue} where the rowid is the id of the row and cellvalue is the value of the cell. For example, such output can be [{id:1,value:1},{id:2,value:2}…] The valid options for mathoperation are - 'sum, 'avg', 'count'. If this parameter is set and is valid, the returned value is a scalar representing the operation applied to the all values in the column. If the parameter is not valid the returned value is empty array
getLocalRow | rowid | object | Returns an array with data of the requested id = rowid. from the local data array.The returned array is of type name:value, where the name is a name from colModel and the value from the associated column in that row. It returns false if the rowid can not be found. The difference from getRowData ia that getRowData returns data in the table, while the getLocal data returns the data from the local data array if any.
getDataIDs | none | array[] | This method returns an array of the id's in the current grid view. It returns an empty array if no data is available.
getGridParam | name | mixed value | Returns the value of the requested parameter. name is the name from the options array. If the name is not set, the entry options are returned. For available options, see options.
getInd | rowid, rowcontent | mixed | This method returns the index of the row in the grid table specified by id= rowid when rowcontent set to false (default). If rowcontent is set to true, it returns the entry row object. If the rowid can not be found, the function returns false.
getRowData | rowid or none | array{} | Returns an array with data of the requested id = rowid. The returned array is of type name:value, where the name is a name from colModel and the value from the associated column in that row. It returns an empty array if the rowid can not be found. If the rowid is not set the method return all the data from the grid in array
hideCol | colname or [colnames] | jqGrid object | Given a single colname, it hides the column with that name. Given an array of colnames [“name1”,”name2”], it hides the columns with those names, 'name1' and 'name2', in the example. The names in colname or colnames must all be valid names from the colModel. NB: The width of the grid is not changed.
remapColumns | permutation, updateCells, keepHeader | none | Reorder the grid columns based on the permutation array. The indexes of the permutation array are the current order, the values are the new order. By example if the array has values [1,0,2] after calling this method the first column will be reordered as second. updateCells if set to true will reorder the cell data. keepHeader if set to true will reorder the data above the header cells.
resetSelection | none | jqGrid object | Resets (unselects) the selected row(s). Also works in multiselect mode.
setCaption | caption | jqGrid object | Sets a new caption of the grid. If the Caption layer was hidden, it is shown.
setCell | rowid, colname, data, class, properties, forceup | jqGrid object | This method can change the content of particular cell and can set class or style properties. Where: rowid the id of the row, colname the name of the column (this parameter can be a number (the index of the column) beginning from 0 data the content that can be put into the cell. If empty string the content will not be changed class if class is string then we add a class to the cell using addClass; if class is an array we set the new css properties via css properties sets the attribute properies of the cell, forceup If the parameter is set to true we perform update of the cell instead that the value is empty
setGridParam | object | jqGrid object | Sets a particular parameter. Note - for some parameters to take effect a trigger(“reloadGrid”) should be executed. Note that with this method we can override events. The name (in the name:value pair) is the name from options array. For a particular options, see options.
setGridHeight | new_height | jqGrid object | Sets the new height of the grid dynamically. Note that the height is set only to the grid cells and not to the grid. new_height can be in pixels, percentage, or 'auto'.
setGridWidth | new_width, shrink | jqGrid object | Sets a new width to the grid dynamically. The parameters are: new_width is the new width in pixels. shrink (true or false) has the same behavior as shrinkToFit - see options. If this parameter is not set we take the value of shrinkToFit.
setLabel | colname, data, class, properties | jqGrid object | Sets a new label in the header for the specified column; can also set attributes and classes . The parameters are: colname the name of the column (this parameter can be a number (the index of the column) beginning from 0 data the content that can be put into the label. If empty string the content will not be changed class if class is string then we add a class to the label using addClass; if class is an array we set the new css properties via css properties sets the attribute properies of the label
setRowData | rowid, data, cssprop | true on success, false otherwise | Updates the values (using the data array) in the row with rowid. The syntax of data array is: {name1:value1,name2: value2…} where the name is the name of the column as described in the colModel and the value is the new value. If the cssprop parameter is string we use addClass to add classes to the row. If the parameter is object we use css to add css properties. Note that we can set properties and classes without data, in this case we should set data to false
setSelection | rowid, onselectrow | jqGrid object | Toggles a selection of the row with id = rowid; if onselectrow is true (the default) then the event onSelectRow is launched, otherwise it is not.
showCol | colname | jqGrid object | Shows a column with a given colname. If the colname is a string we show only the specified column. If colname is array of type [“name1”,”name2”] then the columns with names 'name1' and 'name2' will be shown at the same time The names in colname must be valid names from colModel. The width does not change.
trigger(“reloadGrid”) | none | none | Reloads the grid with the current settings. This means that a new request is send to the server if datatype is xml or json. This method should be applied to an already-constructed grid. Pay attention that this method does not change HEADER information, that means that any changes to colModel would not be affected. You should use gridUnload to reload new configuration with different colModel
filterGrid | grid_id, params | HTML object | This method can be called to construct an custom search form for the grid and should be not applied to the grid but to a valid HTML element. grid_id is the id of the grid to which the search will be applied. parms is an array of parameters (see below). For more details refer to custom searching
filterToolbar | params | jqGrid object | This method is the same as filterGrid, except that the search input elements are placed in the grid just below the header elements. When the header elements are resized the input search elements are also resized according to the new width. Another difference to the filterGrid is that the filter toolbar uses definitions from colModel. For more information refer to Toolbar searching
getColProp | colname | array{} | Return an array of the properties of the given column name from colModel
GridDestroy | grid_id | true on success, false otherwise | Destroys the entry grid with id= grid_id from the DOM (clears all the html associated with the grid and unbinds all events)
GridUnload | grid_id | true on success, false otherwise | The only difference to previous method is that the grid is destroyed, but the table element and pager (if any) are left ready to be used again.
setGridState | state | jGrid object | Show or hide the grid depending and state parameter. When the state is set to 'visible' the grid will be shown. When the parameter is set to 'hidden' the grid will be hidden. Note that the method does not call onHeaderClick event and the caption of the grid is allway visible
setColProp | colname, properties | jGrid object | Sets new properties in colModel. This method is ideal for dynamically changing properties of the column. Note that some properties - have no effect see colModel options. For example: jQuery(”#grid_id”).setColProp('colname',{editoptions:{value:“True:False”}}); will change the editoptions values.
sortGrid | colname, reload | jqGrid object | Sorts the given colname and shows the appropriate sort icon. The same (without sorting icon) can be done using setGridParam({sortname:'myname'}).trigger('reloadGrid'). If the reload is set to true, the grid reloads with the current page and sortorder settings.
updateGridRows | data, rowidname, jsonreader | true on success, false otherwise | This method update the existing data in the grid by given rowidname. data is a array of data in format [{name:value,name1:value1…}, {name:value,name2:value2…}] where the name is the name from colModel and value is the actuall value. It is not neccessary that all columns are present in the data item object (the same as setRowData method) rowidname (string) - is the name of the row which should acts as id If not set the name “id” is used. jsonreader (boolean) default false. If set to true a jsonReader definition is used to set the data. Note that this work only if the item in jsonReader object 'repeatitems' is set to true.In this case the data should be not in pair name:value, but only values where the number of columns should be equal of those in colModel.
groupingGroupBy | groupname, groupoptions | jqGrid object | This method set a new grouping field. groupname is the name on which we want to group by, groupoptions is object which replaces the groupingView object.
groupingRemove | current | jqGrid object | Remove the current grouping and clear the grid related grouping rows. If current is set to true only the group rows are removed. If set to false the group rows are removed and the grid is reloaded with the current settings
bindKeys | Object | jqGrid object | This function add a keyboard navigation in the grid and in the tree grid. Parameter passsed to this method is a object which contain the follwing properties : { onEnter: null, onSpace: null, onLeftKey:null, onRightKey: null, scrolingRows : true } . The onEnterl, onSpace, onLeftKey, onRightKey are events which define what should happen when the appropriate key is pressed. scrolingRows defines if the grid should do automatick scrolling is a vertical scrollbar is available.
Last Updated: 03/21/11 | © TriRand Ltd., 2011


 Methods requiering jQuery UI library
Methods requiering jQuery UI library

Requirements and installation

In order to use these methods is necessary to include additionally the jQuery UI library in the head section of the document. For more information how to download the jQuery UI library visit here
After downloading the jQuery UI your configuration can look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First Grid</title>

<link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.8.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>

</head>
<body>
...
</body>
</html>

Where jquery-ui-1.8.2.custom.min.js is the jQuery UI library.
In order to overcome some confusions we recommend to download the full version of the UI library.

Column Chooser

With this method we can reorder columns and set visible and hidden columns in the grid.
Calling convetions:

$grid->callGridMethod('#grid','columnChooser');
or
$grid->callGridMethod('#grid','columnChooser', array(options));

where options is a array with properties listed below #grid is the id of the grid anf $grid is the grid object created with jqGridRender method

To see Column Chooser dialog like on the picture above, one should include ui.multiselect.css and ui.multiselect.js before jqGrid.
The plugin and the CSS file are bounded with the package, so there is no need to download it separatley.

After calling this a modal dialog appear where the user can reorder columns and set which of them can be visible and which of them can be hidden.

Since the method usually is a attched to button click it can be used with setJSCode methods.
Another possibility is to add a button at pager and call the grid method navButtonAdd. Below is example how to do this using the following tutorial

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
....
// add a custom button via the build in callGridMethod
// note the js: before the function
$colChooser = << COLCH
function()
{
jQuery("#grid").jqGrid('columnChooser',{title:'My Column Chooser'});
}
COLCH;
$buttonoptions = array("#pager",
    array("caption"=>"Column Chooser", "onClickButton"=>"js:".$colChooser)
);
$grid->callGridMethod("#grid", "navButtonAdd", $buttonoptions);

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

Below is the list of options that can be used for this method

Name | Type | Description | Default
title | string | Title of the modal dialog | See $.jgrid.col.title in language file
width | number | Set the width of the dialog in pixels | 420
height | number | Set the height of the dialog in pixels | 240
classname | string | Class which will be added to the selector where the selects are build | null
done | function | Function which will be called when the user press Ok button. In the current implementation we cal remapColumns method in order to reorder the columns |
msel | mixed | msel is either the name of a ui widget class that extends a multiselect, or a function that supports creating a multiselect object (with no argument, or when passed an object), and destroying it (when passed the string “destroy”) | multiselect
dlog | mixed | dlog is either the name of a ui widget class that behaves in a dialog-like way, or a function, that supports creating a dialog (when passed dlog_opts) or destroying a dialog (when passed the string “destroy”) | dialog
dlog_opts | mixed | dlog_opts is either an option object to be passed to “dlog”, or (more likely) a function that creates the options object. The default produces a suitable options object for ui.dialog |
cleanup | function | Function to cleanup the dialog, and select. Also calls the done function with no permutation (to indicate that the columnChooser was aborted |

Sortable Rows

This method allows reordering (sorting) grid rows in a visual manner using a mouse.
Calling convetions:

$grid->callGridMethod('#grid','sortableRows', array(options));

where options is a array with properties listed below #grid is the id of the grid anf $grid is the grid object created with jqGridRender method
The method is fully compatible with jQuery UI sortable widget. This means that we can set any option and event available in this widget. For more information on the options and events look here
Method can be calles using the setJSCode method.

Known problems

  • Currently this method does not work correct in FireFox versions 3.0.x, Chrome and Safari browsers due to little problem in sortable widget, which we hope they will be corrected in future release of jQuery UI.
  • Method does not work currently when treeGrid is enabled - i.e. you can not use the method to reorder tree rows.

Resizable Grid

This method allow to re size the grid width and/or height in visual manner using a mouse.
Calling convetions:

$grid->callGridMethod("#grid,'gridResize', array(options));

where options is a array with properties listed below #grid is the id of the grid anf $grid is the grid object created with jqGridRender method
The method is fully compatible with jQuery UI resizable widget. This means that we can set any option and event available in this widget. For more information on the options and events look here
Method can be calles using the setJSCode method.

Known problems

  • Using the grid hide button (the button in the caption) does not hide the content created from the resizable widget. This cause appearing of borders of the grid after it is hidden.

Drag and Drop rows between grids

This method allow drag and drop rows between two or more grids using a mouse.

Calling convetions:

$grid->callGridMethod('#grid','gridDnD', array(options));

where options is a array with properties listed below #grid is the id of the grid anf $grid is the grid object created with jqGridRender method

Name | Type | Description | Default
connectWith | string | Determines the target grid(s) to which the row should be dropped. The option is a string. In case of more than one grid the ids should be delemited with comma - i.e ”#grid1, #grid2” | empty string
onstart | function | This event raises when we start drag a row from the source grid (i.e. to which this method is applied). Parameters passed to this event are the event handler and a prepared ui object. For more information refer to jQuery UI draggable events | null
onstop | function | This event is triggered when dragging stops. Parameters passed to this even are the event handler and a prepared ui object. For more information refer to jQuery UI draggable events | null
beforedrop | function | This event raises before droping the row to the grid specified in connectWith option. Parameters passed to this event are the event handler, prepared ui object, data which will be inserted into the grid in name value pair, source grid object and target(this) grid object. If the event return object in value name pair this object will be inserted into the target grid. | null
ondrop | function | This event raises after the droping the row to the grid specified in connectWith option. Parameters passed to this event are the event handler, prepared ui object, data which is inserted into the grid in name value pair. For more information refer to jQuery UI droppable events | null
drop_opts | object | Predefined options which can be applied to the droppable grid (specified with connectWith option above). Also you can set any option and event (except drop event which is replaced with ondrop event listed above). For more information refer to jQuery UI droppable | { activeClass : “ui-state-active”, hoverClass : “ui-state-hover” }
drag_opts | object | Predefined options which can be applied to the draggable grid (i.e. to which this method is applied). Also you can set any option and event (except start and stop events which are replaced with onstart and onstop events listed above). For more information refer to jQuery UI draggable | { revert: “invalid”, helper: “clone”, cursor: “move”, appendTo : ”#jqgrid_dnd”, zIndex: 5000 }
dropbyname | boolean | If set to true this means that only fields that have equal names will be added to the target grid. Note that we use addRowData to insert new row, which means that if some field with name “a” on source grid is hidden they can appear on the target grid. The default value of false mean that the grid data will be added to the target counted from the first column from source. | false
droppos | string | Determines where to add the new row. Can be first which mean as first row of the grid and last - as last row in the target grid. | first
autoid | boolean | This option determines how the new row id should be generated. If this option is true we generate a id wich begin with string setted with the option autoidprefix (see below) and a random number. If this option is false the id can be either the the next record count or value determined by key property in colModel. If the parameter is defined as function this function should return value which will act as id to the target grid. Parameters passed in this case is the data array which will be inserted into the target grid row | true
autoidprefix | string | This option have sense only if the option autoid is set to true and determines the prefix of the new genearted id. | dnd_

Known problems

  • The method does not work well in Safari and Chrome because of the bug in the draggable widget. The effect is that the entry text is selected bellow the draggable row

Example:

Let suppose that two grids are created with grid1.php and grid2.php files and the ids of the grids are respectivley #grid1 and #grid2.
Lets suppose that the file grid2.php is included after the file grid1.php, then in file grid2.php the following code will connect both grids, so that we can drag and drop rows between them

// file grid2.php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
....

$grid->callGridMethod('#grid1','gridDnD', array(array("connectWith"=>"#grid2")));
$grid->callGridMethod('#grid2','gridDnD', array(array("connectWith"=>"#grid1")));
$grid->renderGrid('#grid2','#pager',true, null, null, true,true);
Last Updated: 03/18/11 | © TriRand Ltd., 2011


 Tutorials
Tutorials

The tutorials in this chapter are using only the most advanced and feature rich jqGridRender PHP class provided by jqGrid. For information on the base classes jqGrid and jqGridEdit please refer to the appropriate topics in the Architecture and classes guide chapter of the documentation and the additional client-side documentation here.

We are using the "Northwind" database in all tutorials. You can find the SQL dump and schema of the Northwind database in the installation package of the product.

We will use the following base PHP page as a starting point for all tutorials. The base code for the grid itself is in the "grid.php" file. All subsequent tutorials are built using these files (changes and additions will be shown in each tutorial based on the topic of the tutorial).

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>jqGrid PHP Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.multiselect.css" />
    <style type="text/css">
        html, body {
        margin: 0;         /* Remove body margin/padding */
        padding: 0;
        overflow: hidden;   /* Remove scroll bars on browser window */
        font-size: 75%;
        }
    </style>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
   <script type="text/javascript">
   $.jgrid.no_legacy_api = true;
   $.jgrid.useJSON = true;
   </script>
    <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
    <script src="js/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
  </head>
  <body>
      <div>
          <?php include ("grid.php");?>
      </div>
   </body>
</html>

grid.php

<?php
// include the database connection settings/configuration
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// instruct the database that we use utf-8 encoding
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// set the SQL select query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid automatically create the model based on the SQL query
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

Last Updated: 03/21/11 | © TriRand Ltd., 2011


 Using the grid in different contexts
Using the grid in different contexts
Depending on where and how jqGrid for PHP is used, there are several approaches that can be used for placing the grid inside your page.

Approach #1: The script creates automatically the HTML placeholders and javascript needed by jqGrid

You can see in our Quick installiation guide that you can include the jqGrid PHP script in any place of the HTML document allowing the script to handle everything related to jqGrid itself. This is done using the parameters of the renderGrid method. Lets considers these parameters:

renderGrid( $tblelement, $pager , $script , $summary, $params , $createtbl , $createpg , $echo );

The first parameter is the ID of the table HTML element which will be used for the grid. The second parameter is the ID of HTML element the will be placed as a pager for the grid. These parameters may contain the jQuery selector "#" as the first character of the ID, but this is not required (jqGrid will do that automatically if not specified - e.g. both "#jqGridTable" and "jqGridTable" are allowed). If you do not wish to use pager in the grid, the second parameter should be set to an empty string. These HTML elements should be manually defined on the page, e.g.

<table id="jqGridTable"></table>
<div id="jqGridTableDiv"></div>

The third parameter $script tells the method if the javascript code needed for jqGrid should be autogenerated and automatically included in the file hosting the jqGrid instance. This will automatically create the javascript, for example:

...
<script type="text/javascript">
jQuery(document).ready(function() {
$("#grid").jqGrid({...});
});
</script>
...

The sixth and seventh parameters tell the method if the HTML elements needed by the grid (table and pager) should be created by the grid itself or are already available on the page. This means that you do not need to explicitly create the HTML placeholders for the grid and pager, the jqGrid runtime will create them for you automatically if these paramaters are set to true, for example:

<?php
...
$grid = new jqGridRender($conn);
...

$grid->renderGrid("grid","pager",true,null,null,true, true, true);
?>

then the following content will be generated:

...
<table id="grid"></table>
<div id="pager"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
$("#grid").jqGrid({...});
});
</script>
...

Approach #2: Table and pager are explicitly defined as HTML, but the javascript of the grid should be autogenerated

In a complex application the position of the grid in the HTML page should be fixed at a certain place. In this case the table and/or pager should exists in the DOM and be explicitly defined in the HTML. For this purpose the sixth and seventh parameters should be set to false and you need to manually define them in the HTML where needed.

<?php
...
$grid = new jqGridRender($conn);
...

$grid->renderGrid("grid","pager",true,null,null,false, false, true);
?>

...
<script type="text/javascript">
jQuery(document).ready(function() {
$("#grid").jqGrid({...});
});
</script>
...
...
<table id="grid"></table>
<div id="pager"></div>

Approach #3: Using jqGrid from the JQuery.ready event

In the cases where you are already using the jQuery "ready" event (document.ready), it is more efficent to include the jqGrid script from within the event itself.

The code should look like this:

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqGrid </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
...
<?php include "grid.php";?>
...
});
</script>
</head>
<body>
...
...
<table id="grid"></table>
<div id="pager"></div>
...
</body>
</html>

The grid.php file should be (i.e the third, six and seven parameters should be set to false)

<?php
...
$grid = new jqGridRender($conn);
...

$grid->renderGrid("grid","pager",false,null,null,false, false, true);
?>

Approach #4: Loading jqGrid via AJAX

You can also load the jqGrid script via ajax . In this case the third parameter of the renderGrid method should be set to true. Below is example where the script is called on button click which then is removed from the DOM. The sixth and seventh parameters can be set to false if the elements (for table and pager) exist on the page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqGrid </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
...
jQuery("#mybutton").click(function(){
   jQuery("#mycontent").load("grid.php");
   return false;
   jQuery(this).remove();
});
...
});
</script>
</head>
<body>
...
...
<button id="mybutton">Create Grid</button>
...

<div id="mycontent"></div>
...
</body>
</html>

and the grid.php file

<?php
...
$grid = new jqGridRender($conn);
...

$grid->renderGrid("grid","pager",true,null,null,true, true, true);
?>

Last Updated: 05/05/10 | © TriRand Ltd., 2011


 Working with javascript
Working with javascript
jqGrid for PHP supports adding javascript from within your PHP script. This is done with the special prefix "js:" before the script.
It is very important to note that there are exceptions to this rule when the following methods are used:
  • setGridEvent
  • setNavEvent
  • setJSCode

placing a "js:" prefix before the code will not run the script. These methods add the "js:" prefix automatically before the code

When should the "js:" prefix be used?

The "js:" prefix should be used when the type definition is function and in the following options - Column Model Options for extending the editing properties,in Formatters to define custom formatter and in Toolbar Filter.

If the javascript code is complex and spans several lines, we recommend using the following syntax:

$mycode = <<<CUSTOMCODE
//
// here JavaScript code

CUSTOMCODE;

Using this syntax will prevent PHP errors with unescaped single and double brackets, which will otherwise cause errors in the PHP script.
You can see an example of this here

setGridEvent

With the setGridEvent method we add client-side javascript events related to the grid. The method accepts two parameters - the first parameter is the valid event name listed here and the second parameter is the javascript code which should begin with function and the parameters which the event accepts.

Let suppose that we want to alert a message with the OrderID when a row in the grid is selected (OrderID is a column in the grid). Using our example the change in the code should be:

<?php
...
$onselect = <<<ONSELECTROW
function(rowid, selected)
{
   alert(rowid);
}
ONSELECTROW;

$grid->setGridEvent('onSelectRow',$onselect);

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

setNavEvent

setNavEvent works in the same way as setGridEvent, but it adds a javascript events to the navigator or/and form-editing modules.

setJSCode
setJSCode adds code written in javascript just after the creation of jqGrid instance. Use this method to emit custom javascript related to your jqGrid instance.

Last Updated: 03/18/11 | © TriRand Ltd., 2011


 Adding datepicker
Adding datepicker
This is an example of how you can add a datepicker, timepicker or in fact any custom 3rd party control as an editing or searching control in jqGrid. In our case we will use the jQuery UI datepicker widget. Before using the script make sure that you have included the jQuery UI datapicker javascript in the script tag of your page.

Our goal is to use a datepicker for both editing and serching, but before doing this please take a look at the following help topic: configure the dates

In our case, we will use the default settings for the server and client side dates. To attach the datepicker, we will use dataInit event - either in editoptions and in searchoptions. For this purpose it is needed to enable the jqGrid navigator too. We will use this example as a starting point.

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));

// javascriptCode for the datepicker
$mydatepicker = <<<DATEPICK
function(el)
{
   setTimeout(function(){
      jQuery(el).datepicker({dateFormat:'dd/mm/yy'});
   },200);
}
DETEPICK;

// Set the column property
$grid->setColProperty('OrderDate', array(
   "formatter"=>'date',
   "editoptions"=>array("dataInit"=>"js:".$mydatepicker),
   "searchoptions"=>array("dataInit"=>"js:".$mydatepicker)
));

// add navigator with the default properties
$grid->navigator = true;

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

Please, note the setTimeout javascript function in our code. The reason we are using it is that dataInit event is executed before the element is inserted to the DOM, and we need the timeout to make sure the element is attached to the DOM before proceeding with attaching the datepicker.

Last Updated: 06/05/10 | © TriRand Ltd., 2011


 Setting column headers
Setting column headers
The setColModel method uses the names of the database columns (fields) as default column header labels. In some cases when the number of columns is relatively big, you can use the third parameter in the method to add custom column headers instead of calling setColProperty with the label attribute.

The array used as a parameter should be an associative array - the key should correspond to the name of the database column (field) in the query and the value should be the desired column header corresponding to that column. It is not neccessary that the length of the array corresponds to the length of colModel.

Let suppose that in our example we want to change "OrderID" to "Id" and "OrderDate" to "Date".

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';

// Definition of the labels
$mylabels = array("OrderID"=>"Id", "OrderDate"=>"Date");

// Let the grid create the model with the desired labels
$grid->setColModel(null, null, $mylabels);

// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
Last Updated: 06/05/10 | © TriRand Ltd., 2011


 Custom formatter
Custom formatter
A "formatter" is a simple javascript function that formats a cell in your jqGrid instance to a different value, based on certain criteria. By default, the value from the database will be used in the grid cell verbatim. There are cases, where the default formatters do not meet the requirments of the project. jqGrid has a built-in property to define custom formatters with custom javascript.

Let suppose that in our example we want to display in red the values in the Freight column that have values less than 100. For this purpose, we need to write a small javascript formatting function. We can use the approach from this topic - i.e using the "js:" prefix, but for demonstartion purposes we will use setJSCode method instead. When using this approach we just need to set the formatter to use the desired javascript custom function and output this function with the setJSCode method.

Here is the example:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();

// point to Fright column to use the function named MyFormatter
$grid->setColProperty('Fright', array('formatter'=>'js:MyFormatter'));

// Writh the MyFormatter function

$myformat = <<<FORMATFREIGHT
function MyFormatter (cellValue, options, rowdata)
{
    var color = (parseFloat(cellValue) > 100) ? " style='color=red'" : "";
    var cellHtml = "<span" + color +">" + cellValue + "</span>";
    return cellHtml;
}
FORMATFREIGHT;

// Output the function with setJSCode
$grid->setJSCode($myformat);

// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

Last Updated: 06/05/10 | © TriRand Ltd., 2011


 Adding custom button
Adding custom button
You can add any number of custom buttons to the grid toolbar using the callGridMethod. callGridMethod executes jqGrid client-side javascript methods from within your PHP code. In our case, we will use the client-side "navButtonAdd" method to add a custom button to the toolbar. In order for this to happen, navigator should be enabled.

In the code sample below, we will add a custom button and when we click on it, an alert message is displayed.

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));

// Enable navigator
$grid->navigator = true;
// Disable some actions
$grid->setNavOptions('navigator', array("excel"=>false,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
// add a custom button via the build in callGridMethod
// note the js: before the function
$buttonoptions = array("#pager",
    array("caption"=>"Custom Button", "onClickButton"=>"js: function(){alert('Custom Button clicked')}")
);
$grid->callGridMethod("#grid", "navButtonAdd", $buttonoptions);

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
Last Updated: 10/24/11 | © TriRand Ltd., 2011


 Export to excel
Export to excel
By default export to excel is enabled when navigator is enabled. The difference in using export to excel in the jqGridRender class, as opposed to export to excel in the jqGridClass, is that the names in header, width and initially hidden columns are taken from column model generated in the jqGridRender class. In that respect, you have more control on the export and how the Excel spreadsheet is formatted upon exporting.

To disable the export to excel in navigator you should set the excel property to false.

$grid->setNavOptions('navigator', array("excel"=>false));

Additionaly you can overwrite the export file name to excel using the exportfile variable:

$grid->exportfile ='myexcelfile';

Last Updated: 11/06/10 | © TriRand Ltd., 2011


 Export to PDF
Export to PDF
Enable PDF export

By default export to PDF is disabled when navigator is enabled. The difference in using export to PDF in the jqGridRender class, as opposed to export to PDF in the jqGridClass, is that the names in header, width and initially hidden columns are taken from column model generated in the jqGridRender class. In that respect, you have more control on the export and how the PDF is formatted upon exporting.

To enable the export to PDF in navigator you should set the pdf property to true.
$grid->setNavOptions('navigator', array("pdf"=>true));
Additionaly you can overwrite the export file name to pdf using the pdffile variable:

$grid->pdffile ='mypdffile.pdf';

Additionally you can use setPdfOptions method to set various option of the Export To Pdf

Enable UTF in PDF export

By default the export to PDF in not utf.
In order to enable utf data you will need to change the font names in pdf options.

The default settings for these are as follow

$PDF = array(
"font_name_main"=>"helvetica",
"font_monospaced"=>"courier",
"font_name_data"=>"helvetica",
...
);

jqGrid comes only with one font whch support utf - freeserif.

In order to enable utf you will need to

...
$grid = new jqGridRender($conn);
...

$grid->setPdfOptions(array(
    "font_name_data"=>"freeserif",
    "font_name_main"=>"freeserif",
    "font_monospaced"=>"freeserif",
));
...

If you want to use other utf fonts you will need to download it from this location:

and put them in the tcpdf fonts directory

Last Updated: 01/21/11 | © TriRand Ltd., 2011


 Export to CSV
Export to CSV
By default export to CSV is disabled when navigator is enabled. The difference in using export to CSV in the jqGridRender class, as opposed to export to CSV in the jqGridClass, is that the names in header and initially hidden columns are taken from column model generated in the jqGridRender class. In that respect, you have more control on the export and how the CSV is formatted upon exporting.

To enable the export to CSV in navigator you should set the csv property to true.

$grid->setNavOptions('navigator', array("csv"=>true));

Additionaly you can overwrite the export file name to csv using the csvfile variable:

$grid->csvfile ='mycsvfile.csv';

You can use the csvsep variable to define the separator for the exported data

$grid->csvsep =",";

Last Updated: 11/06/10 | © TriRand Ltd., 2011


 DropDowns/Selects for editing & searching
DropDowns/Selects for editing & searching
DropDowns (Selects) are commonly used elements in the web. jqGrid supports dropdowns as editing/searching controls in an elegant way using the setSelectmethod. With this method you can attach dropdowns to all editing and serching forms. The method supports getting dropdown data directly from an SQL query or from pre-defined arrays.

The syntax of method is

setSelect( $colname, $data, $formatter , $editing , $searching , $defvals );

The method should be called after setColModel method.

The first parameter is the column name generated from colModel.
The second parameter can be SQL query or associative array.

  • In case of SQL query, the first field should be the key which the will be posted or searched (e.g. "OrderID") and the second field should be the displayed name.
  • In case of associative array, the key element should correspond to the key (e.g. "OrderID") which then will be posted or searched and the value will correspond to the display name

The third parameter is formatter - default value is true. This tells the script that it should connect the key value with the name specified as first parameter. This allows you to not write SQL JOIN command to associate the key (column name) with another from other table. To disable this feature just set the parameter to false.

The fourth parameter is $editing,, which defaults to true. This tells the script that the select (dropdown) element will be used in editing modules. To disable this feature just set the parameter to false.

The fifth parameter is $searching , which defaults value to true. This tells the script that the select(dropdown) element will be used when we perform serching. To disable this feature just set the parameter to false.

The sixth parameters is $defvals. This parameter represents the default value, if none is selected. The parameter is used only in search modules. Can be something like arrary(""=>"All"); which will add additinal element to the select and they will appear at first place.

In order to demonstrate this feature we will include additional field in the SelectCommand ShipCity and will allow the user to filter the cities with select control. Here is the code:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, ShipCity, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));

// Enable filter toolbar searching
$grid->toolbarfilter = true;
// we set the select for ship city
$grid->setSelect("ShipCity", "SELECT DISTINCT ShipCity, ShipCity AS CityName FROM orders ORDER BY 2", false, false, true, array(""=>"All"));

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

If the requierment is to search just on several citys we can pass a array with predefined values.
The code will look like this

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, ShipCity, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));

// Enable filter toolbar searching
$grid->toolbarfilter = true;
// we set the select for ship city

// array tha holds the limitted citys
$mycity = array("London"=>"London", "Paris"=>"Paris", "Torino"=>"Torino");

$grid->setSelect("ShipCity", $mycity , false, false, true, array(""=>"All"));

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

Last Updated: 06/12/10 | © TriRand Ltd., 2011


 Searching (Search Dialog)
Searching (Search Dialog)
Searching is enabled by default, when the navigator option is set to true. In order to customize the search options and events you can use two available methods - setNavEvent and setNavOptions.

Since both methods are general methods for customizing the "navigator" (toolbar) functionality of jqGrid, the first parameter of these methods should refer to searching - i.e the parameter should be a string - "search".

$grid->setNavOptions('search',array(...));
$grid->setNavEvent('search','java_script_code_here');

By default, the searching feature is set to search on multiple fields. If you want to allow searching just on one field at a time, you can set the multipleSearch options to false.

Here is an example:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));

// add navigator with the default properties
$grid->navigator = true;

//but use single search
$grid->setNavOptions('search',array("multipleSearch"=>false));

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
Last Updated: 06/05/10 | © TriRand Ltd., 2011


 Searching (ToolBar)
Searching (ToolBar)
The default behavior of the toolbar searching operation (when stringResult is on) is to search fields with SQL command coresponding to the LIKE operator (begins with). For example:

SELECT id, name FROM table WHERE name LIKE a%

To change this behaviour, you will need to change sopt parameter in searchoptions in your colModel.
Lets suppose that we want to change the default LIKE a% operator (begins with) with "contains" - i.e LIKE %a% on the field "CustomerID".

Sample code:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));

//enable toolbarsearch
$grid->toolbarfilter = true;

//CoustomerID field should be serched with contain operator
$grid->setColProperty('CustomerID',array("searchoptions"=>array("sopt"=>array("cn"))));

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
Last Updated: 06/05/10 | © TriRand Ltd., 2011


 Form Editing (Edit Dialog)
Form Editing (Edit Dialog)
Form editing is enabled by default when the navigator option is set to true. In order to customize the form editing options and events, you can use two available methods - setNavEvent and setNavOptions.

In this case the first parameter of these methods should refer to to the appropriate editing module (add, edit, del).

$grid->setNavOptions('add',array(...));
$grid->setNavOptions('edit',array(...));

or

$grid->setNavEvent('add','java_script_code_here');
$grid->setNavEvent('edit','java_script_code_here');

The list of available editing options are:

  • add - for adding a record
  • edit - for deleting a record
  • del - for deleting a record.

For the full list of available options and events, please refer to the appropriate topics in jqGridRender Class

In this Tutorial we will consider two common tasks:

1. Editing a record when the primary key is serial (autoincremet) and there is a need to show it in the grid, but not in the editing form.

For this purpose we will use this example as a starting point.

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';

//set a table to be manipulated
$grid->table = 'orders';

// set the primary key - it is serial
$grid->setPrimaryKeyId('OrderID');

// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain and edit the data
$grid->setUrl('grid.php');

//do not allow this field to be editable
$grid->setColProperty('OrderID',array("editable"=>false));

// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));

// enable form editing
$grid->navigator = true;

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

Lets consider the script with the commands:

$grid->table = 'orders';
$grid->setPrimaryKeyId('OrderID');

We tell the script which is the table against which we should perform CRUD operation. We also define the primary key and that the key is serial (autoincrement)

$grid->setUrl('grid.php');

We tell the script that CRUD operations and query operations will be handled by the "grid.php" code file.

$grid->setColProperty('OrderID',array("editable"=>false));

With this command we disable the editing of the primary key, but the field is still visible in the grid.

This is all the is needed to get automatic CRUD operation with jqGrid for PHP. The key command that does the magic here is:

$grid->setPrimaryKeyId('OrderID');

Setting this in the script tells the grid to post the appropriate values when a CRUD operation is in action.

2.Editing a record when the primary key is not serial (autoincremet) and there is need to show the key in adding new record, but disable the key in edit mode.

For this purpose we will use the table "customers", where the table has a primary key, but this primary key is not serial and when the data is inserted the user should fill this key.

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT CustomerID, CompanyName, Phone, PostalCode, City FROM customers';
// Set the table to where you update the data
$grid->table = 'customers';

$grid->setPrimaryKeyId('CustomerID');
$grid->serialKey = false;

// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"CustomerID"
));
$grid->setColProperty('CustomerID', array("editoptions"=>array("readonly"=>true), "editrules"=>array("required"=>true)));

$enableadd = <<<ENBLADD;
function(formid)
{
   jQuery('#CustomerID',formid).removeAttr("readonly");
}
ENBLADD;

$disableedit = <<<DSBLEDIT;
function(formid)
{
   jQuery('#CustomerID',formid).attr("readonly","readonly");
}
DSBLEDIT;

$grid->setNavEvent('add','beforeShowForm',$enableadd);
$grid->setNavEvent('edit','beforeShowForm',$disableedit);

// Enable navigator
$grid->navigator = true;

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

The only diffrence with the first tutorial is that in this case we set two custom events in add and edit mode. In this case we use beforeShowForm. In add mode we enable the input in the element removing the readonly attribute.
In edit mode we disable the input using setting the input element to have readonly attribute.

Last Updated: 06/05/10 | © TriRand Ltd., 2011


 Inline editing
Inline editing
Inline editing is another editing mode of jqGrid. To invoke inline editing, just call the client-side jqGrid editRow method.

In this particular example, we show the built-in formatter actions, which are designed to automatically place edit/save/cancel buttons at the end of each grid row. In addition to this, we will attach a datepicker to the OrderDate column.

Starting from our example, the PHP code is:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain and edit data
$grid->setUrl('grid.php');

// we add actions column at first place
$grid->addCol(array(
    "name"=>"actions",
    "formatter"=>"actions",
    "editable"=>false,
    "sortable"=>false,
    "resizable"=>false,
    "fixed"=>true,
    "width"=>60,
    "formatoptions"=>array("keys"=>true)
    ), "first");

//disable the editing of the first column
$grid->setColProperty('OrderID', array("editable"=>false));

//add datepicker for order data
$grid->setColProperty("OrderDate",array("editoptions"=>array("dataInit"=>"js:function(el){ setTimeout(function(){jQuery(el).datepicker();},100) }" )));
// format the date field using default formatter options
$grid->setColProperty("OrderDate",array("formatter"=>"date"));

// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

Last Updated: 01/21/11 | © TriRand Ltd., 2011


 Cell editing
Cell editing
Cell Editing is another editing mode of jqGrid for PHP. It is quite easy to add the feature. In this case we just need to set the cellEdit option to true.

Sample code:

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain and edit data
$grid->setUrl('grid.php');

//disable the editing of the first column
$grid->setColProperty('OrderID', array("editable"=>false));
// Set some grid options
$grid->setGridOptions(array(
   "rowNum"=>10,
   "rowList"=>array(10,20,30),
   "sortname"=>"OrderID",
   "cellEdit"=> true
));
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

As can be seen you will just need to set cellEdit option to true.

Last Updated: 03/08/10 | © TriRand Ltd., 2011


 Validating Data on the Client Side
Validating Data on the Client Side
jqGrid supports varios rules for client-side validation. They are available through the editrules option for each column. Since this is a collection, you can stack several validation rules at the same time - they will all apply to the respective edit field.

For this particular example we will check if the entered Freight value is a number and additionally to this we will validate the number if it is little than zero.
For this purpose we will use the example 1 from here

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';

//set a table to be manipulated
$grid->table = 'orders';

// set the primary key - it is serial
$grid->setPrimaryKeyId('OrderID');

// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain and edit the data
$grid->setUrl('grid.php');

//do not allow this field to be editable
$grid->setColProperty('OrderID',array("editable"=>false));

//set validation rules for Freight
grid->setColProperty('Freight'=>array("editrules"=>array("number"=>true,"minValue"=>0)));

// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID"
));

// enable form editing
$grid->navigator = true;

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
Last Updated: 05/02/10 | © TriRand Ltd., 2011


 Hierarchy
Hierarchy

Last Updated: 06/13/10 | © TriRand Ltd., 2011


 Subgrid 2 levels
Subgrid 2 levels
In this advanced tutorial we will use the code from our online example framework) "SubGrid (2 nested levels)" as a base and add other useful features often needed in real-world scenarios.

  1. We will enable editing in both parent and child grids.
  2. We will add an additional parameter to the subgrid (from parent) when a new record is inserted in order to sync both grids.
  3. When we delete a record in the parent grid, all associated records from the child grid will be deleted as well.
  4. We will use some of the additional functionality that the jqGrid database driver provides.

In order to achieve this we will create two PHP code files - one for the parent grid and another for the child grid.

grid.php code (parent grid)

// include the database connection settings
require_once 'jq-config.php';
// include the jqGrid class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// instruct the database that we will be using utf-8 encoding
$conn->query("SET NAMES utf8");

// create the jqGrid instance
$grid = new jqGridRender($conn);
// set the SQL select query
$grid->SelectCommand = 'SELECT CustomerID, CompanyName, ContactName, Phone, City FROM customers';
// instruct jqgrid to use the "customers" table and set primary keys needed for CRUD (create, read, update, delete) operations
$grid->table = 'customers';
$grid->setPrimaryKeyId('CustomerID');
$grid->serialKey = false;
// Set output format to json
$grid->dataType = 'json';
// let the grid automatically create the columns model based on the database table
$grid->setColModel();
// set the url to the location of the PHP code file for the respective grid
$grid->setUrl('grid.php');
// set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "height"=>250,
    "rowList"=>array(10,20,30),
    "sortname"=>"CustomerID"
));
$grid->setColProperty('CustomerID', array("label"=>"ID", "width"=>50));
// set the url to the location of the PHP code file for the respective grid
$grid->setSubGridGrid("subgrid.php");

// enable navigator
$grid->navigator = true;

// disable the delete operation programatically for that table
$grid->del = false;

// we need to write some custom code when we are in delete mode.
// get the grid operation parameter to see if we are in delete mode
// jqGrid sends the "oper" parameter to identify the needed action
$deloper = $_POST['oper'];
// det the customer id
$custid = $_POST['CustomerID'];

// if the operation is del and the customerid is set
if($deloper == 'del' && isset($custid)  )
{
   // the two tables are linked via CustomerID, so let try to delete the records in both tables
   try {
      jqGridDB::beginTransaction($conn);
      $cust = jqGridDB::prepare($conn, "DELETE FROM customers WHERE CustomerID= ?", array($custid));
      $order = jqGridDB::prepare($conn,"DELETE FROM orders WHERE CustomerID = ?", array($custid))

      jqGridDB::execute($cust);
      jqGridDB::execute($order);
      jqGridDB::commit($conn);
   } catch(Exception $e) {
      jqGridDB::rollBack($conn);
      echo $e->getMessage();
   }
}

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

With the command

$grid->setSubGridGrid("subgrid.php");

we set the main grid in subgrid mode expecting content from this url for the child grid.

Next we disable jqGrid's automatic deleting of records in the parent grid. By default, automatic deleting will delete the parent row only, whereas we also want to delete all related records in the child grid as well. This is done via

$grid->del = false;

In this case we should manually determine if we are in delete mode and manually delete the parent row and all related child rows. jqGrid does this by setting the "oper" post parameter. If the parameter "oper" equals "del", then we know we are in delete mode and can proceed with the logic needed. In addition to that, the grid sends the data for the row deleted, including the primary key (CustomerID in our case). For example:

// get the operation
$deloper = $_POST['oper'];
// det the customer id
$custid = $_POST['CustomerID'];
// if the operation is del and the customerid is set
if($deloper == 'del' && isset($custid)  )
{
...

At end we enclose the deletion in transaction deleting the desired records in both tables in order to make sure the tables are in sync.

Now, lets look at the subgrid PHP code file:

subgrid.php

<?php
// inclide the database connection settings
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// instruct the db that we use utf-8 encoding
$conn->query("SET NAMES utf8");
// Get the needed parameters passed from the main grid
// By default we add to postData subgrid and rowid parameters in the main grid
$subtable = jqGridUtils::Strip($_REQUEST["subgrid"]);
$rowid = jqGridUtils::Strip($_REQUEST["rowid"]);
// create the jqGrid instance
$grid = new jqGridRender($conn);
// set the SQL select query
$grid->SelectCommand = "SELECT OrderID, RequiredDate, ShipName, ShipCity, Freight FROM orders WHERE CustomerID = ?";
// set the ouput format to json
$grid->dataType = 'json';
// instruct the grid the we are using the "orders" datatable
$grid->table = "orders";
$grid->setPrimaryKeyId("OrderID");

// Let the grid create the column model automatically
$grid->setColModel(null,array(&$rowid));

// Set the url from where we obtain the data
$grid->setUrl('subgrid.php');

// Set some grid options
$grid->setGridOptions(array(
    "width"=>540,
    "rowNum"=>10,
    "sortname"=>"OrderID",
    "height"=>110,
    "postData"=>array("subgrid"=>$subtable,"rowid"=>$rowid))
);

// set a option when we add a record to insert a CustomerID too.
$grid->setNavOptions("add",array("editData"=>array("CustomerID"=>$rowid)));

// Change some property of the field(s)
$grid->setColProperty("RequiredDate", array(
    "formatter"=>"date",
    "formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y"),
    "search"=>false
    )
);

// enable editing
$grid->navigator = true;

$subtable = $subtable."_t";
$pager = $subtable."_p";

$grid->renderGrid($subtable,$pager, true, null, array(&$rowid), true,true);
$conn = null;
?>

In the subgrid code there is nothing special except this line of code

$grid->setNavOptions("add",array("editData"=>array("CustomerID"=>$rowid)));

With this line we set additional parameter when we are in add mode and this is the id of the Customer. The variable is posted and inserted succesfully.

Last Updated: 03/10/10 | © TriRand Ltd., 2011


 Subgrid 3 nested levels
Subgrid 3 nested levels
As shown in our Subgrid with 2 levels example, it is possible to add any number of nested (child) subgrids with jqGrid for PHP. For the purpose of this tutorial, let's consider a scenario where we want to construct a hierarchical jqGrid with 3 nested levels (for simplicity, we will just show how to create the hierarchy, without extra features like editing. There is no difference in how editing and extra features are handled in nested (child) subgrids - same principles apply).

In our sample Northwind database (available in the download bits of the products), we have three linked tables: "Customers" -> "Orders" -> "Order_Details". Each customer can have a number of orders, and each order can have a number of details related to it. This relation naturally fits in a 3-level jqGrid hierarchy.

grid.php (customers grid)

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT CustomerID, CompanyName, ContactName, Phone, City FROM customers';
// Set the table to where you update the data
$grid->table = 'customers';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "height"=>'auto',
    "gridview"=>false,
    "rowList"=>array(10,20,30),
    "sortname"=>"CustomerID"
));
$grid->setColProperty('CustomerID', array("label"=>"ID", "width"=>50));
$grid->setSubGridGrid("subgrid.php");
// Enable navigator
$grid->navigator = true;
// Enable only editing
$grid->setNavOptions('navigator', array("excel"=>false,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
// Enjoy
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

subgrid.php (orders grid)

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");
// Get the needed parameters passed from the main grid
$subtable = jqGridUtils::Strip($_REQUEST["subgrid"]);
$rowid = jqGridUtils::Strip($_REQUEST["rowid"]);
if(!$subtable && !$rowid) die("Missed parameters");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = "SELECT OrderID, RequiredDate, ShipName, ShipCity, Freight FROM orders WHERE CustomerID= ?";
// set the ouput format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel(null, array(&$rowid));
// Set the url from where we obtain the data
$grid->setUrl('subgrid.php');
// Set some grid options
$grid->setGridOptions(array(
    "width"=>540,
    "rowNum"=>10,
    "sortname"=>"OrderID",
    "height"=>'auto',
    "postData"=>array("subgrid"=>$subtable,"rowid"=>$rowid)));
// Change some property of the field(s)

$grid->setColProperty("RequiredDate", array(
    "formatter"=>"date",
    "formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y"),
    "search"=>false
    )
);
$grid->setSubGridGrid("subsubgrid.php");
$grid->navigator = true;
$grid->setNavOptions('navigator', array("excel"=>false,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
// Enjoy
$subtable = $subtable."_t";
$pager = $subtable."_p";
$grid->renderGrid($subtable,$pager, true, null, array(&$rowid), true,true);
$conn = null;
?>

subsubgrid.php (order_details grid)

<?php
require_once '../../../jq-config.php';
// include the jqGrid Class
require_once ABSPATH."php/jqGrid.php";
// include the driver class
require_once ABSPATH."php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");
// Get the needed parameters passed from the main grid
$subtable = jqGridUtils::Strip($_REQUEST["subgrid"]);
$rowid = jqGridUtils::Strip($_REQUEST["rowid"]);
if(!$subtable && !$rowid) die("Missed parameters");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = "SELECT OrderID, ProductID, Quantity, UnitPrice FROM order_details WHERE OrderID=?";
// set the ouput format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel(null, array(&$rowid));
// Set the url from where we obtain the data
$grid->setUrl('subsubgrid.php');
// Set some grid options
$grid->setGridOptions(array(
    "width"=>480,
    "rowNum"=>10,
    "sortname"=>"OrderID",
    "height"=>'auto',
    "postData"=>array("subgrid"=>$subtable,"rowid"=>$rowid)));
// Change some property of the field(s)
$grid->navigator = true;
$grid->setNavOptions('navigator', array("excel"=>false,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
// Enjoy
$subtable = $subtable."_t";
$pager = $subtable."_p";
$grid->renderGrid($subtable,$pager, true, null, array(&$rowid), true,true);
$conn = null;
?>

Last Updated: 02/22/10 | © TriRand Ltd., 2011


 Simple subgrid
Simple subgrid
You can esy integrate a simple subgrid using the previous "Hierarchy" samples (2 and 3-level hierarchy) in combination with this example.
Last Updated: 02/22/10 | © TriRand Ltd., 2011


 Master -> Detail with editing
Master -> Detail with editing
In this tutorial we will show how to link two jqGrid instances on the same page, so that selecting a row from master jqGrid shows details of the linked records in the second jqGrid instance. This is a classical master -> details example. We can achieve this easily with a few lines of javascript when the row in the master jqGrid is selected.

Additionally to this we will show how to set up detail so that we can add arecords to it setting the Master Key

Starting from this example, just add the following line:

<div>
    <?php include ("detail.php");?>
</div>

after this line:

<div>
    <?php include ("grid.php");?>
</div>

We will link the database table "Customers" to database table "Orders", so that when we select a customer from the master table, all orders for this customer will appear in the details table. In addition to that, we will summarize the totals of all orders of this customer in the footer row of the details jqGrid instance.

grid.php (customers grid)

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT CustomerID, CompanyName, ContactName, Phone, City FROM customers';
// Set the table to where you update the data
$grid->table = 'customers';
// Set output format to json
$grid->dataType = 'json';
// Set the primary key
$grid->setPrimarykeyId("CustomerID");
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"CustomerID"
));
$grid->setColProperty('CustomerID', array("label"=>"ID", "width"=>50));

// on select row we should post the customer id to second table and trigger it to reload the data
$selectorder = &lt;&lt;&lt;ORDER
function(rowid, selected)
{
    if(rowid != null) {
        jQuery("#detail").jqGrid('setGridParam',{postData:{CustomerID:rowid}});
        jQuery("#detail").trigger("reloadGrid");

        // Enable CRUD buttons in detail navigator when a row is selected

        jQuery("#add_detail").removeClass("ui-state-disabled");
        jQuery("#edit_detail").removeClass("ui-state-disabled");
        jQuery("#del_detail").removeClass("ui-state-disabled");
    }
}
ORDER;
$grid->setGridEvent('onSelectRow', $selectorder);

// We should clear the grid data on second grid on sorting, paging, etc.
$cleargrid = &lt;&lt;&lt;CLEAR
function(rowid, selected)
{
   // clear the grid data and footer data
   Query("#detail").jqGrid('clearGridData',true);

   // Disable CRUD buttons in detail navigator when a row is not selected

       jQuery("#add_detail").addClass("ui-state-disabled");
       jQuery("#edit_detail").addClass("ui-state-disabled");
       jQuery("#del_detail").addClass("ui-state-disabled");
}
CLEAR;

$grid->setGridEvent('onPaging', $cleargrid);
$grid->setGridEvent('onSortCol', $cleargrid);

// Enable navigator
$grid->navigator = true;

$grid->setNavOptions('navigator', array("excel"=>false,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
// Enjoy
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

detail.php (orders table)

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");
// Get the needed parameters passed from the main grid
if(isset ($_REQUEST["CustomerID"]))
    $rowid = jqGridUtils::Strip($_REQUEST["CustomerID"]);
else
    $rowid = "";
// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = "SELECT OrderID, RequiredDate, ShipName, ShipCity, Freight, CustomerID FROM orders WHERE CustomerID= ?";
// set the ouput format to json
$grid->dataType = 'json';
// Setup the table
$grid->table = 'orders';
// Setup primary key id
$grid->setPrimaryKeyId("OrderID");
// Let the grid create the model
$grid->setColModel(null, array(&$rowid));
// Set the url from where we obtain the data
$grid->setUrl('detail.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "footerrow"=>true,
    "userDataOnFooter"=>true,
    "sortname"=>"OrderID",
    "height"=>110
    ));
// Change some property of the field(s)
$grid->setColProperty("RequiredDate", array(
    "formatter"=>"date",
    "formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y"),
    "search"=>false
    )
);

//Set the CustomerID (master key)  hidden
$grid->setColProperty("CustomerID", array("hidden"=>true))l

$grid->navigator = true;
// Enable Editing
$grid->setNavOptions('navigator', array("excel"=>true,"add"=>true,"edit"=>true,"del"=>true,"view"=>false));

// Set the sumary of the orders
$summaryrow = array("Freight"=>array("Freight"=>"SUM"));

// disable the CRUD buttons when we initialy load the grid
$initgrid = <<INIT
jQuery("#add_detail").addClass("ui-state-disabled");
jQuery("#edit_detail").addClass("ui-state-disabled");
jQuery("#del_detail").addClass("ui-state-disabled");
INIT;

$grid->setJSCode($initgrid);

// on beforeshow form when add we get the customer id and set it for posting
$beforeshow = <<BEFORE
function(formid)
{
var srow = jQuery("#grid").jqGrid('getGridParam','selrow');
if(srow) {
    var gridrow = jQuery("#grid").jqGrid('getRowData',srow);
    $("#CustomerID",formid).val(gridrow.CustomerID);
}
}
BEFORE;

$grid->setNavEvent('add', 'beforeShowForm', $beforeshow);
$grid->renderGrid("#detail","#pgdetail", true, $summaryrow, array(&$rowid), true,true);
$conn = null;
?>

Last Updated: 01/07/11 | © TriRand Ltd., 2011


 Manipulate grid data (customFunc)
Manipulate grid data (customFunc)
There are situations where the data send to the grid should be obtained with a complex calculations and the query in this case can be quite tedious. In order to resolve such situations we have added a custom function (customFunc) where we can modifiy the data before it is send to the grid.

In order to ilustarate how this can be done we will use our example and demonstarte the two new options in the grid

  • customFunc
  • addUserData

With the help of these we can manipulate the final data send to the grid. customFunc is capable to modify the grid data and userdata , while addUserData can modify the userdata only (usually the summary column) send to the grid. The customFunc is called after the addUserData is set.

Now lets begin with our example.

Let suppose that our goal is to round the Fright field to 1 if it is little than 0 (zero). The summary row should be updated in the appropriate way and at end we want to add additional text field in the summary row to indicate that this is sum (intead that we can do this using callGridMethod with parameter footerData.

The customFunc accept two parameters the grid data object and the connection.
The function should return the new grid data object.

grid.php

<?php
// include the database connection settings/configuration
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// instruct the database that we use utf-8 encoding
$conn->query("SET NAMES utf8");
$grid = new jqGridRender($conn);
// set the SQL select query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid automatically create the model based on the SQL query
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID",
    "footerrow"=>true,
    "userDataOnFooter"=>true
));

// Let add the Label Total to the Shipname
$grid->addUserData(array("ShipName"=>"Total:"));

//Define the custom function
$grid->customFunc = "FrightUpdate";

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;

/// here is the function
function FrightUpdate($gdata, $conn)
{
$sumFreight = 0;
// gdata->rows contain the grid data rows
foreach($gdata->rows as $row )
{
       if($row->Freight < 1 ) {
             //NOTE THAT YOU CAN ADD A HTML content to the coulmns
             $row->Freight = 1;
       }
        $sumFreight += $row->Freight;
}
// set the sumary field
$gdata->userdata['Freight'] = $sumFreight;

// return the modified
return $gdata;

}
?>

Last Updated: 06/12/10 | © TriRand Ltd., 2011


 Attaching autocomplete in editing
Attaching autocomplete in editing
In this scenario we will demonstarte how to attach a autocomplete when we are in editng mode.
The whole script will be written in PHP, but it is possible that part of the javascript can be written in the index file.

In order to use this functionality we will use a jQuery UI autocomplete widget. The jQuery UI library can be downloaded form here:

http://jqueryui.com/download

When you download the library, please be a sure that you have marked the autocomplete checkbox.

The autocomplete widget is available from jQuery UI version 1.8 and up

Please refer to the coments at end of this page.

After the library is downloaded you should include it in the index file. This can look like this

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>jqGrid PHP Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.8.1.custom.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.multiselect.css" />
    <style type="text/css">
        html, body {
        margin: 0;         /* Remove body margin/padding */
        padding: 0;
        overflow: hidden;   /* Remove scroll bars on browser window */
        font-size: 75%;
        }
    </style>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
   <script type="text/javascript">
   $.jgrid.no_legacy_api = true;
   $.jgrid.useJSON = true;
   </script>
    <script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
    <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
  </head>
  <body>
      <div>
          <?php include ("grid.php");?>
      </div>
   </body>
</html>

Lets begin with our script.
We will first use our example and we will attach the autocomplete to the Customer name. In autocomplete we will display the name, but when we select a item we will post the id of the customer.

<?php
// include the database connection settings/configuration
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// instruct the database that we use utf-8 encoding
$conn->query("SET NAMES utf8");

$grid = new jqGridRender($conn);
// set the SQL select query
$grid->SelectCommand = 'SELECT a.OrderID, a.OrderDate, a.CustomerID, b.CompanyName, a.ShipName, a.Freight FROM orders a, customers b WHERE a.CustomerID = b.CustomerID';
// Set output format to json
$grid->dataType = 'json';
// Let the grid automatically create the model based on the SQL query
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
$grid->table = 'orders';

//lets hide the customerId
$grid->setColProperty('CustomerID',array('hidden'=>true));

// autocomplete javascript code
$company = <<CUSTOM
function (elem) {
setTimeout(function() {
        $(elem).autocomplete({
             source: 'company.php',
             select: function(event, ui) {
                $("#CustomerID").val(ui.item.id);
             }
        });
        jQuery('.ui-autocomplete').css({'font-size':'75%'});
},100);
}
CUSTOM;

// attaching the autocomplete function
$grid->setColProperty('CompanyName',array("editoptions"=>array("dataInit"=>"js:".$company)));

// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID",
    "footerrow"=>true,
    "userDataOnFooter"=>true
));

$grid->navigator=true;

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;

The PHP script for the company.php used in autocomplete has the following code:

<?php
// include the database connection settings/configuration
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// instruct the database that we use utf-8 encoding
$conn->query("SET NAMES utf8");
$term = jqGridUtils::GetParam("term");

$SQL = "SELECT CustomerID as id, CompanyName as name, CompanyName AS value FROM customers WHERE CompanyName LIKE ? or CustomerID LIKE ?";

$grid = new jqGridRender($conn);
$ret = $grid->SelectLimit($SQL , 10, 0, array($term."%",$term."%"));
echo json_encode($ret);

?>

Now what we do.
1. We have changed the sql query in Select Command so that we have joined the CompanyName to be displayed into the grid - see Select Command
2. We have included in the SelectCommand the CustomerID.
3. We set this field to be hidden so that it does not appear into the grid, but it is hidden into the editing form - see setColProperty for CustomerID
4. We have attached a dataInit event for the field CompanyName - see setColProperty for CompanyName
5. The dataInit event (javascript) just call the jQuery autocomplete widget - see $company variable. When the value is selected we change the CustomerID which is transported from company.php request.
6. The autocomplete obtain the data via ajax request privided from company.php file. To this request autocomplete widget send a term variable with the data typed from the user.
7. In company.php file we use again the power of jqGrid method selectLimit. This method return the obtained data in a way that is acceptable for the plugin.

Last Updated: 06/12/10 | © TriRand Ltd., 2011


 Formatting colums with PHP function
Formatting colums with PHP function
There are situations where using the build in formatters and custom java script, which are executed at client side, does not meet the requirments of the application.

For this purpose we have created a customFunc, where will be possible to use a PHP function to format certain column(s).

Based on this tutorial we will create a script to format the Freight value using number_format PHP function and put some additional HTML content inside this column when the value is less than 1.

The customFunc accept two parameters the grid data object and the connection.
The function should return the new grid data object.

grid.php

<?php
// include the database connection settings/configuration
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// instruct the database that we use utf-8 encoding
$conn->query("SET NAMES utf8");
$grid = new jqGridRender($conn);
// set the SQL select query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid automatically create the model based on the SQL query
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID",
    "footerrow"=>true,
    "userDataOnFooter"=>true
));

//Define the custom function
$grid->customFunc = "FrightUpdate";

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;

/// here is the function
function FrightUpdate($gdata, $conn)
{
// gdata->rows contain the grid data rows
   foreach($gdata->rows as $row )
   {
   // format using "," as decimal separator
      if($row->Freight < 1 ) {
      //color in red if the value is less than 1
         $row->Freight = "<font color='red'>".number_format($row->Freight, 2, ',', ' ')."</font>";
      } else {
         $row->Freight = number_format($row->Freight, 2, ',', ' ');
      }
   }
   // return the modified
   return $gdata;
}
?>

Last Updated: 06/13/10 | © TriRand Ltd., 2011


 Loading data at once and operate locally
Loading data at once and operate locally
Since version 3.7 we introduce a new very usefull feature of jqGrid - load all the needed data from server at once and then
operate on it locally - i.e - pagging, sorting, searching and etc.

For this purpose we introduce a new grid parameter - rowTotal. When set, this paramater (again with loadonce parameter set to true) instruct the server to load the total number of rows needed to work on.

Note that rowNum determines the total records displayed in the grid, while rowTotal the total rows on wich we operate.
When this parameter is set we send a aditional parameter to server named totalrows.

Setting rowTotal to rowTotal = -1 loads all the data from the query.
Setting rowTotal to any number greater than 0 (zero) (usually this should be greater than rowNum) loads only this number of rows.

Below is example, where we load all the data and then we operate on it locally.

grid.php

<?php
// include the database connection settings/configuration
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// instruct the database that we use utf-8 encoding
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// set the SQL select query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid automatically create the model based on the SQL query
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"OrderID",
//this instruct grid to load data only once and then go to local mode
    "loadonce"=>true,
//this instruct grid to load all the data from the query.
//If you want by example to load only 500 records, the set it to 500
    "rowTotal" => -1
));

//enable navigator, so that we can search
$grid->navigator = true;

$grid->setNavOptions('navigator', array("excel"=>false,"add"=>false,"edit"=>false,"del"=>false,"view"=>true, "search"=>true));

$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
Last Updated: 06/13/10 | © TriRand Ltd., 2011


 Grouping with summary
Grouping with summary
Since version 3.8 we introduce a great new feature - Grouping. Grouping allow us to group a data by different criteria. Currently we can group only at one level.

It is important to note that grouping and grouping operatins are performed at client side and not at server. The only thing that should be considered is that the data should be sorted in a appropriate way from server - i.e - first on field (column) on which we want to group and then to the desired column. This is done automatically in the PHP component with the option groupDataSorted (see below).

In this example we demonstrate this feature.

Our goal is to group the Orders by Customer and then show a subtotal Freight for each Customer.
This can be done just with few lines of code and adding a summaryType to the Freight column.

Below is the code where every operation related to the grouping is explained.

<?php
require_once 'jq-config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
// set the ouput format to json
$grid->dataType = 'json';
// Let the grid create the model from SQL query
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set alternate background using altRows property
$grid->setGridOptions(array(
    "rowNum"=>10,
    "sortname"=>"OrderID",
    "rowList"=>array(10,20,50),
    "height"=>'auto',
// Enable grouping
    "grouping"=>true,
// grouping options
    "groupingView"=>array(
// group by CustomerID
       "groupField" => array('CustomerID'),
// show the grouped column
       "groupColumnShow" => array(true),
// Bold the text at header
       "groupText" =>array('<b>{0}</b>'),
// Tell the grid that it should sort the data on server in the appropriatre way
       "groupDataSorted" => true,
// Allow summary footer to place a varios summary info
       "groupSummary" => array(true)
    )
    ));
// Change some property of the field(s)
$grid->setColProperty("OrderID", array("label"=>"ID", "width"=>60));
$grid->setColProperty("OrderDate", array(
    "formatter"=>"date",
    "formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y")
    )
);
// Add a summary property to the Freight Column
$grid->setColProperty("Freight", array("summaryType"=>"sum", summaryTpl=>"Sum: {0}", "formatter"=>"number"));
// Enjoy
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
Last Updated: 01/09/11 | © TriRand Ltd., 2011


 Run sql commands after CRUD
Run sql commands after CRUD
Before version 3.8.2 performing CRUD operations into the grid was limited to only single table only.
In most applications this cause a limitation and writting a lot of manual code to do the requiered task.

In order to make development easy and without writing a lot of manual code we have created a method
setAfterCrudAction( string $oper, string $sql, array $param ) method.

With a help of this method we should set only the SQL command and parameters for it.
Note that this command or set of commands are executed after the CRUD operation.
Moreover the operation will be executed only when the CRUD for the main table was succesfull.
We can set a unlimited commands to be executed.

Below is a example which update the name after from the edit after it was succesfull.

<?php
require_once '../../../jq-config.php';
// include the jqGrid Class
require_once ABSPATH."php/jqGrid.php";
// include the driver class
require_once ABSPATH."php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT CustomerID, CompanyName, Phone, PostalCode, City FROM customers';
// Set the table to where you update the data
$grid->table = 'customers';
// Set output format to json
$grid->dataType = 'json';
$grid->setPrimaryKeyId('CustomerID');
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grid.php');
// Set some grid options
$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"CustomerID"
));
$grid->setColProperty('CustomerID', array("editoptions"=>array("readonly"=>true)));

// For demonstration purposes only we will update the Customer name adding at end of
// the field U after the data is updated from the user

// This command is executed after edit
$cid = jqGridUtils::GetParam('CustomerID');
// This command is executed immediatley after edit occur.
$grid->setAfterCrudAction('edit', "UPDATE customers SET CompanyName = CONCAT(CompanyName,' -U') WHERE CustomerID=?",array($cid));

// You can write a set of command which will be run after edit
// $grid->setAfterCrudAction('edit', "UPDATE table2 SET ... WHERE  ",array(..));
// $grid->setAfterCrudAction('edit', "UPDATE tableN SET ... WHERE  ",array(..));

// Also you can do the same for add and del
// $grid->setAfterCrudAction('add', "UPDATE table1 SET ... WHERE  ",array(..));
// $grid->setAfterCrudAction('add', "UPDATE tableN SET ... WHERE  ",array(..));

// Enable navigator
$grid->navigator = true;
// Enable only editing
$grid->setNavOptions('navigator', array("excel"=>false,"add"=>false,"edit"=>true,"del"=>false,"view"=>true, "search"=>false));
// Close the dialog after editing
$grid->setNavOptions('edit',array("closeAfterEdit"=>true,"editCaption"=>"Update Customer","bSubmit"=>"Update"));
// Enjoy
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
Last Updated: 01/10/11 | © TriRand Ltd., 2011


 Using array data like SQL
Using array data like SQL
This example demonstrate that jqGrid can work with array data like it is SQL one.
For this purpose we have created a special jqGrid Array driver called jqGridArray.
The only what is needed in case of working with PHP array data is to include the driver,
create the array connection and from this point you can work with array with SQL commands:

Available SQL command: SELECT, DISTINCT, FROM, WHERE, ORDER BY, LIMIT, OFFSET
Operators available : * =, <, >, <=, >=, <>, !=, IS, IS IN, IS NOT, IS NOT IN, LIKE, ILIKE, NOT LIKE, NOT ILIKE
Functions available in WHERE parameters : LOWER(var), UPPER(var), TRIM(var)

Limitation: Currently CRUD operations are not available:

Below is a simple example which demonstrates this:

<?php
require_once '../../../jq-config.php';
// include the jqGrid Class
require_once ABSPATH."php/jqGrid.php";
// include the driver class
require_once ABSPATH."php/jqGridArray.php";

// create the array connection
$conn = new jqGridArray();
// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Create a random array data
for ($i = 0; $i < 1000; $i++)
{
    $data1[$i]['id']    = $i+1;
    $data1[$i]['foo']    = md5(rand(0, 10000));
    $data1[$i]['bar']    = 'bar'.($i+1);
}

// Always you can use SELECT * FROM data1
$grid->SelectCommand = "SELECT id, foo, bar FROM data1";

$grid->dataType = 'json';
$grid->setPrimaryKeyId('id');

$grid->setColModel();
// Enable navigator

$grid->setUrl('grid.php');

$grid->setGridOptions(array(
    "rowNum"=>10,
    "rowList"=>array(10,20,30),
    "sortname"=>"id"
));

$grid->navigator = true;
// Enable search
$grid->setNavOptions('navigator', array("excel"=>false,"add"=>false,"edit"=>false,"del"=>false,"view"=>false,"csv"=>true, "pdf"=>true));
// Activate single search
$grid->setNavOptions('search',array("multipleSearch"=>false));
// Enjoy

$grid->renderGrid('#grid','#pager',true, null, null, true,true);

?>
Last Updated: 01/10/11 | © TriRand Ltd., 2011


 Trouble-Shooting
Trouble-Shooting

Last Updated: 06/12/10 | © TriRand Ltd., 2011


 The grid is displayed in the page, but no data on it?
The grid is displayed in the page, but no data on it?
This problem is typically caused by invalid settings of the grid url inPHP code.

Resolution:
The path to the file from which you include the grid php file should be the same in setUrl method. For example, if the grid PHP file is included in a page like this:

...
<div>
   <?php include ("path_to_grid/grid.php");?>
</div>
...

Then in the grid PHP file you should use setUrl like this:

<?php
...

// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, ShipName, Freight FROM orders';
// Set output format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data

$grid->setUrl('path_to_grid/grid.php');
...
?>

Where path_to_grid is the path to the grid.php file

Last Updated: 06/12/10 | © TriRand Ltd., 2011


 jqAutocomplete PHP
jqAutocomplete PHP

Welcome to the technical documentation of jqAutocomplete for PHP. If you have questions and comments, please use the following channels to get back to us:

Public forums:
http://www.trirand.net/forum/

Email:
support@trirand.net

Last Updated: 10/24/11 | © TriRand Ltd., 2011


 Introduction
Introduction

jqAutocomplete for PHP is a server-side component built on top of open and widely used standards - jQuery, jQuery UI, ThemeRoller.

Autocomplete, when added to an input field, enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

This can be used to enter previous selected values, for example you could use Autocomplete for entering tags, to complete an address, you could enter a city name and get the zip code, or maybe enter email addresses from an address book.

You can pull data in from a local and/or a remote source: Local is good for small data sets (like an address book with 50 entries), remote is necessary for big data sets, like a database with hundreds or millions of entries to select from.

Some of the major features include:

  • Blazing speed - only the minimal data required is sent from server to client using JSON.
  • Supports the most popular SQL Databases like PostgreSQL, MySQL, Microsoft SQL Server.
  • Supports array data.
  • jQuery based client-side - familiar and powerful client-side API based on jQuery and jQuery UI.
  • Feature complete - every feature you might need, including caching,loading data at once and etc
  • ThemeRoller support - theming is based on ThemeRoller. A set of 25 themes by professional designers is available, including great free theme authoring tool.
  • many more.

Last Updated: 10/15/11 | © TriRand Ltd., 2011


 Installation & System Requierments
Installation & System Requierments

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Requirements
Requirements

Browser Support

jqAutocomplete for PHP supports all major browsers:

  • Internet Explorer 6.x+
  • FireFox 3.x+
  • Safari 2.x+
  • Google Chrome 2.x+
  • Opera 9.5+

PHP

jqAutocomplete is designed to work with PHP versions 5.1+.

Databases (optional)

Currently jqAutocomplete for PHP supports the following databases:

  • MySQL 5.x+ (PDO)
  • PostgreSQL versions 7.x+ (PDO)
  • SQLite versions 3.x+ (PDO)
  • Microsoft SQL Server 2005+
  • Oracle 8+
  • MySQL (through Mysqli)
  • DB2 (IBM DB2 functions)
  • Array
  • MongoDB

MySQL, PostgreSQL and SQLite databases are supported through PHP PDO (PHP Data Objects), so depending on your PHP setup you may need to install it before using jqAutocomplete for PHP. PDO is by default installed in PHP 5.1+ distributions. PDO is a core PHP technology, created and supported by the core PHP team.

To ensure that PDO is installed in your production enviornment, please run the following PHP script on your development/production machine:

<?php
phpinfo();
?>

Save the file and run it on your web server. The following should appear if you want to use MySQL and have PDO installed:

The following should appear if you want to use PostgreSQL and have PDO installed:

The following should appear if you want to use SQLite and have PDO installed:

Microsoft SQL Server is supported through the PHP driver provided by Microsoft. Please follow the installation instructions provided by Microsoft in the PHP driver documentation. After the driver is installed, the following should appear if you run the "phpinfo()" function:

Oracle is supported through the PHP OCI8 driver. Please follow the installation instructions provided in the same link. After the driver is installed, the following should appear if you run the "phpinfo()" function:

Additinally MqSQL database is supported through Mysqli driver. Follow the installation instuction provided from the same link. After the installation is done the following should appear if you run the "phpinfo()" function:

Additinally DB2 database is supported through DB2 driver. Follow the installation instuction provided from the same link. After the installation is done the following should appear if you run the "phpinfo()" function:

Last Updated: 10/15/11 | © TriRand Ltd., 2011


 Quick Install
Quick Install
Download and unzip the contents of the archive to any convenient location. The package contains the following folders:

- [php] - Contains the jqAutocomplete PHP class and the optional driver files for the appropriate database.
- [themes] - Contains the themes shipped with the product. Since jqAutocomplete supports jQuery UI Themeroller, any theme compatible with jQuery UI ThemeRoller will work for jqAutocomplete as well. Therefore, the package contains just one theme ("Redmond"). You can download any additional themes directly from jQuery UI's ThemeRoller site available here:

http://jqueryui.com/themeroller/

Just add "Redmond" theme in your PHP/HTML file.

<link rel="stylesheet" type="text/css" href="themes/redmond/jquery-ui.custom.css" />

- [js] - The javascript files of jqAutocomplete (and the needed libraries). You need to include them in your PHP page.

The first file is "jquery.js" - this is the official jQuery library.
The second file is "jquery-ui.custom.min.js" - this is the jQuery UI library.
The final result you will have in an PHP page containing jqAutocomplete would be something similar to that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqAutocomplete </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui.custom.css" />

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>

</head>
<body>
......

<div class="ui-widget">
   <label for="company">Company: </label>
   <input id="company" />
</div>

<?php include "firstautocomplete.php";?>
.......
</body>
</html>

Save the file as autocomplete.php or any desired name in the root directory.

In the root directory you will find a file named jq-config.php. Open the file and enter the appropriate information for the connection to the database. Save the file and then create a file firstautocomplete.php with the following content.

<?php
// include the Database driver class (we will use PDO).
require_once 'jq-config.php';
require_once "php/jqGridPdo.php";

// include the jqUtils Class. The class is needed in all jqSuite components.
require_once "php/jqUtils.php";

// include the jqAutocomplete Class
require_once "php/jqAutocomplete.php";

// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

$ac = new jqAutocomplete($conn);
// We use the northwind database
// Set the SQL command
$ac->SelectCommand = "SELECT CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName";
// Set from where to get the dat. In this case from the same file
$ac->setSource("firstautocomplete.php");
// Enjoy
$ac->renderAutocomplete("#company");

?>

Run the file autocomplete.php from your web browser. All subsequent requests the autocomplete needs will be forwarded back to the "firstautocomplete.php" file and the component will automatically handle the requests and provide the needed response - no need for custom coding.

Remarks

If the autocomplete is used with jqGrid PHP component there is no need to load the to load the jqUtils PHP file.
Last Updated: 10/15/11 | © TriRand Ltd., 2011


 Database Connections and drivers
Related Topics
See also
Quick Install
jqSuite PHP Documentation
Database Connections and drivers
If you take a look at our Quick Install topic, you will see that jqAutocomplete for PHP does not create its own connection to the database, but uses a connection that already exists. This is a very flexible approach in complex applications where the connection to the database had already been created. Typically in our examples we will create the connection using PDO rules, but this is not neccessary and you can reuse your own connection.

PDO Driver

When a PDO driver is used (for MySQL or PostgreSQL) a file named jqGridPdo.php can be included in addition to the main jqAutocomplete.php file. The file is available in the [php] folder of the jqSuite for PHP download package. Please note, that in this case you do not need to specify explicitly which database should be used - MySQL or PostgreSQL. The script will detect this automatically from the connection. Here is an example:

<?php
// include the jqAutocomplete Class
require_once "php/jqAutocomplete.php";
// include the PDO driver class - needed for MySQL and Postgre SQL
require_once "php/jqGridPdo.php";
...
?>

Microsoft SQL Driver

When Microsoft SQL Server is used, a file named jqGridSqlsrv.php should be included in addition to the main jqGrid.php file. The file is available in the [php] folder of the jqSuit for PHP download package.

Note: In order to work properly with fields of type "Date", when the connection is created you should also set a property - "ReturnDatesAsStrings"=>true in the connection string. The reason for this is that the driver by default handles dates as PHP date object.

Here is an example:

<?php
// Example connection
$connectionInfo = array("UID" => 'user', "PWD" => 'password',"Database"=>"test", "ReturnDatesAsStrings" => true);
$serverName = "localhost\SQLEXPRESS";
$conn = sqlsrv_connect( $serverName, $connectionInfo);
...
// include the jqAutocomplete Class
require_once "php/jqAutocomplete.php";
// include the SQL Server driver class
require_once "php/jqGridSqlsrv.php";
...
?>

See also

Quick Install
Last Updated: 09/13/10 | © TriRand Ltd., 2011


 Theming
Theming

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Basics and installation
Basics and installation
Theming is based on the highly popular ThemeRoller, which is the standard for developing jQuery UI widgets. This means that you have access to 25 ready-to-use themes created by professional designers, plus a unique free web-based tool allowing you to create your own theme. You can also customize a theme starting from an existing one.

The list of currently available themes is:

  • base
  • black-tie
  • blitzer
  • cupertino (Apple-like UI)
  • dark-hive
  • dot-luv
  • eggplantz
  • flick
  • hot-sneks
  • humanity
  • le-frog
  • mint-choc
  • overcast
  • pepper-grinder
  • redmond (Windows-like UI)
  • smoothness
  • south-street
  • start
  • sunny
  • swanky-purse
  • trontastic
  • ui-darkness
  • ui-lightness
  • vader

The install package of jqSuite for PHP comes with just the default Redmond theme. It is available in the [themes] folder of the install package. You can download any additional themes directly from jQuery UI's ThemeRoller site available here:

http://jqueryui.com/themeroller/

You can also create a new theme (either from scratch or based on another theme).

Just add reference to the ThemeRoller theme in your PHP file.

Example:

<head>
<link rel="stylesheet" type="text/css" href="themes/redmond/jquery-ui.custom.css" />
...
</head>

If you wish to use one of the other 25 themes ThemeRoller offers or your own theme, just replace the Redmond css file with the CSS file of the respective theme.

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Overview
Overview
The PHP jqAutocomplete class uses the jQuery UI CSS Framework to style look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.autocomplete.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<input class="ui-autocomplete-input"/>
<ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all">
  <li class="ui-menu-item">
    <a class="ui-corner-all">item 1</a>
  </li>
  <li class="ui-menu-item">
    <a class="ui-corner-all">item 2</a>
  </li>
  <li class="ui-menu-item">
    <a class="ui-corner-all">item 3</a>
  </li>
</ul>

Note: This is a sample of markup generated by the autocomplete plugin, not markup you should use to create a autocomplete. The only markup needed for that is <input/>.

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Autocomplete class guide
Autocomplete class guide

Last Updated: 10/24/11 | © TriRand Ltd., 2011


 Varaibles
Varaibles
List of public variables that can be used with this class.

Type | Names | Description | Default | Access
string | ajaxtype | Determines the ajax type made to the server. Defaut is GET. Can be a POST | GET | public
boolean | cache | When set to true enables client side caching of the results. This prevent multiple queries to the database. Please use with care. | false | public
string | height | Determines the height of the autocomplete elemnt. Work only if $scroll option is set to true. | 110px | public
boolean | loadAll | Determines if the data should be loaded at once from the SQL siurce. Also when set to true only one requrest is done and the data then is stored at client side. No more requests to the server | false | public
booean | scroll | Determines if the content in autocomplete should have a scroll. Use this option with the height option. If this option is not set the content will have height equal of the responce rows. | true | public
string | searchType | Set the search type for the LIKE SQL operator. The possible values are: startWith - set LIKE value%; contain - set LIKE %value%; endWith - set LIKE %value. If the value does not match any of the above setting the SQL command is interpreted as it is without adding any additional strings. API Tags: | startWith | public
string | fontsize | Set the font size of the widget when it is created. Can be set in any valid measure | 11px | public
boolean | strictcheck | Valid only if target is set in renderAutocomplete. If set to false the input is not cleared when the value is not found in the autcomplete list | true | public
string | SelectCommand | Defines the select command for obtaining the data from the database. Usually this type of command contain the SQL LIKE operator. If the command contain where clause we suppose that this command contain LIKE operator. The serched fields should comtain ? plece holder in order to search om the term element send from the autocompleter. Example: SELECT field1, field2 FROM table WHERE field1 LIKE ? OR field2 LIKE ? As seen you should place a placeholder on the serched fields. The class add the term element automatically to the query. For additional information see the documantation | empty string | public

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Methods
Methods
getOption( string $option )

Return the the requested option of the autocomplete
Parameters:

  • string $option: - the requested option or event.

API Tags:
Access: public

queryAutocomplete( )

Return the result for the autocomplete as PHP object. Determines automatically the placeholders (?) used into the SQL command

API Tags:
Access: public

renderAutocomplete( string $element, [ $target = false], [boolean $script = true], [boolean $echo = true], [boolean $runme = true] )

Main method which do everthing for the autocomplete. Should be called after all settings are done. Note that in one file we can have more than one autocomplete definitions. Construct the autocomplete and perform Query operations.
Parameters:

  • string $element: The DOM element on which audocomplete should be applied
  • $target: - if set the value selection from autocomplete will be set to this element
  • boolean $script: - if set to false the script tag: <script type='text/javascript'> will not be included.
  • boolean $echo: if set to false the result is not echoed but returned
  • boolean $runme: - internal variable used into the jqGrid class

API Tags:
Access: public

setEvent( string $event, string $code )

Set a JavaScript event for the autocomplete. For all the possible events refer the documentation
Parameters:

  • string $event the event name see events:
  • string $code Javascript code:

API Tags:
Access: public

setLength( mixed $num )

Set the limit of the requested data in case of SQL command
Parameters:

  • mixed $num: - if set as number determines the number of the requestd itemd from the query. If set to false loads all the data from the query.

API Tags:
Access: public

setOption( string $option, [mixed $value = null] )

Set the desired option for autocomplete. For a full list of the option refer the documentation
Parameters:
string $option option name see options:
mixed $value:

API Tags:
Access: public

setSource( mixed $source )

Set the source need for autocomlete to send a data. Can be a string or array. If the option is string then this is the url from where to obtain the data.
Parameters:
mixed $source string or array to be set:

API Tags:
Access: public

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Autocomplete options
Autocomplete options
For the Autocomplete options a two methods can be used

getOption($key) to obtain the desired option
where $key is a name listed in the table below
and
setOption(string $option, [mixed $value = null] ) to set a new option.

The method can be called several times in order to set or overwrite existing option.

Example: If we want to change the minial characters before autocomplete lunches, the we can do this:

<?php
...
$ac = new jqAutocomplete($conn);
// We use the northwind database
// Set the SQL command
$ac->SelectCommand = "SELECT CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName";
// Set from where to get the dat. In this case from the same file
$ac->setSource("firstautocomplete.php");
// set the minLength option
$ac->setOption('minLength', 3);
// Enjoy
$ac->renderAutocomplete("#company");

?>

Bellow is a list of all available grid options

Type | Name | Description | Default
string | appendTo | You can now define which element the menu is appended to. The default is to append to the body, which is the previous behavior. The appendTo option take any valid selector. If the selector matches multiple elements, the menu will be appended to the first matched item. | false
boolean | disabled | Disables (true) or enables (false) the autocomplete. Can be set when initialising (first creating) the autocomplete. | false
integer | delay | The delay in milliseconds the Autocomplete waits after a keystroke to activate itself. A zero-delay makes sense for local data (more responsive), but can produce a lot of load for remote data, while being less responsive. | 300
integer | minLength | The minimum number of characters a user has to type before the Autocomplete activates. Zero is useful for local data with just a few items. Should be increased when there are a lot of items, where a single character would match a few thousand items. | 1
array | position | You can now define where the menu will be displayed. The default is to display the menu below the text field, with the left edges aligned. More on this can be found here | false

Other options can be set using the properties of the class. Refer to Autocomplete Variables

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Autocomplete events
Autocomplete events
The event is action that is rasied on the client side when something is hapen in the input where autocomplete is bound. Since this is a client side job in order to use the autocomplete events you will need to write a java script code. Bellow is example in which we prevent inserting value on focus.
The PHP method that initializes the event is setEvent.

<?php
...
$ac = new jqAutocomplete($conn);
// We use the northwind database
// Set the SQL command
$ac->SelectCommand = "SELECT CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName";
// Set from where to get the dat. In this case from the same file
$ac->setSource("firstautocomplete.php");
// set the minLength option

$onfocus = << FOCUS;
function (event, ui)
{
// prevent value inserted on focus
return false;
}
FOCUS;
//Set focus event
$as->setEvent('focus', $onfocus);

// Enjoy
$ac->renderAutocomplete("#company");

?>

As can be seen from this example the first parameter of the method is the name of the event and the second is the code associated with that event. Note how $onfocus is written - function(event, ui) - This will produce in the cleint

focus:function(event, ui) {....}

Below is the list of events that can be used:

Event | Parameters | Description
search | event ui | Before a request (source-option) is started, after minLength and delay are met. Can be canceled (return false), then no request will be started and no items suggested.
open | event ui | Triggered when the suggestion menu is opened.
focus | event ui | Before focus is moved to an item (not selecting), ui.item refers to the focused item. The default action of focus is to replace the text field's value with the value of the focused item, though only if the focus event was triggered by a keyboard interaction. Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused.
select | event ui | Triggered when an item is selected from the menu; ui.item refers to the selected item. The default action of select is to replace the text field's value with the value of the selected item. Canceling this event prevents the value from being updated, but does not prevent the menu from closing.
close | event ui | When the list is hidden - doesn't have to occur together with a change.
change | event ui | After an item was selected; ui.item refers to the selected item. Always triggered after the close event.

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Autocomplete tutorials
Autocomplete tutorials

Last Updated: 10/24/11 | © TriRand Ltd., 2011


 Simple Autocomplete
Simple Autocomplete
In this tutorial we will create a simple autocomplete and will explain every line of the code.
The exmple provided here will act as basic for all other examples.

In order examples to work we suppose that the northwind database (which is bound in the jqSuite package) is installed on your machine.
All exmplaes are included into the packege in examples/autocomplete directory

Let suppose that we have a form element which contain a company field wich should be filled with the autocomplete.
Lets create our index page which contain the form.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqAutocomplete </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui.custom.css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>

</head>
<body>

<form action="#">
   <label for="company">Company: </label>
   <input id="company" />
   <input type="submit" name="submit" value="Submit" />
</form>

<?php include "autocomplete.php";?>
</body>
</html>

Omitting the meta and title tag in the HTML document we contiue with these lines of code

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui.custom.css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery-ui.custom.min.js" type="text/javascript"></script>

Generally, you'll need to include these 3 files on any page to use jQuery UI widgets and interactions:

jquery-ui.custom.css refer to jQuery UI Cascading Style Sheet File
jquery.js refers to jQuery library
jquery-ui.custom.min.js refer to jQuery UI

The autocomplete.php file has the following code:

<?php
// include the Database driver class (we will use PDO).
require_once 'jq-config.php';
require_once "php/jqGridPdo.php";

// include the jqUtils Class. The class is needed in all jqSuite components.
require_once "php/jqUtils.php";

// include the jqAutocomplete Class
require_once "php/jqAutocomplete.php";

// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// create autocomplete instance
$ac = new jqAutocomplete($conn);
//write the select command
$ac->SelectCommand = "SELECT CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName";
// set the source from where to get data. In this case it is the same file.
$ac->setSource("autocomplete.php");
// Enjoy
$ac->renderAutocomplete("#company");

?>

As canb be seen the autocomplete can be set only 4 lines of code.

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Multiple Autocomplete
Multiple Autocomplete
In this scenario we will show how we can set easy two autocomplete fields in the same file.

For this purpose let suppose that the another input field is the product. The index file will look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqAutocomplete </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui.custom.css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>

</head>
<body>

<form action="#">
   <label for="company">Company: </label>
   <input id="company" /> <br/>
   <label for="product">Product: </label>
   <input id="product" /> <br/>
   <input type="submit" name="submit" value="Submit" />
</form>

<?php include "autocomplete.php";?>
</body>
</html>

And the autocomplete.php file

<?php
require_once '../../../jq-config.php';
require_once ABSPATH."php/jqGridPdo.php";
require_once ABSPATH."php/jqUtils.php";
require_once ABSPATH."php/jqAutocomplete.php";

// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// create autocomplete instance
$ac = new jqAutocomplete($conn);
//write the select command
$ac->SelectCommand = "SELECT CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName";
// set the source from where to get data. In this case it is the same file.
$ac->setSource("autocomplete.php");
$ac->renderAutocomplete("#company");

// Create the second instance
$ac2 = new jqAutocomplete($conn);
//write the select command for the products
$ac2->SelectCommand = "SELECT ProductName FROM products WHERE ProductName LIKE ? ORDER BY ProductName";
// set the source from where to get data. In this case it is the same file.
$ac2->setSource("autocomplete.php");
// Enjoy
$ac2->renderAutocomplete("#product");
?>
Last Updated: 10/14/11 | © TriRand Ltd., 2011


 Caching data at client
Caching data at client
In some cases due to trafic to the server it is needed to cache the data at client in order to save requests to the server.
In this scenario we will cache the data at client. The cached data then will be used again to select a item. If the data is not found in the cache then we made request to the server. The returned data is cached again and so on.

We will use the index.php from the Simple Autocomplete

The autocomplete.php code is:

<?php
// include the Database driver class (we will use PDO).
require_once 'jq-config.php';
require_once "php/jqGridPdo.php";

// include the jqUtils Class. The class is needed in all jqSuite components.
require_once "php/jqUtils.php";

// include the jqAutocomplete Class
require_once "php/jqAutocomplete.php";

// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// create autocomplete instance
$ac = new jqAutocomplete($conn);
//write the select command
$ac->SelectCommand = "SELECT CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName";
// set the source from where to get data. In this case it is the same file.
$ac->setSource("autocomplete.php");

// Set the cache option
$ac->cache =  true;

// Enjoy
$ac->renderAutocomplete("#company");
?>
Last Updated: 10/14/11 | © TriRand Ltd., 2011


 Load all data at once
Load all data at once
If the data that will be used for autocomplete is relative not big, then we can use the option to load it at once to the client and to to make requests to the server every time the user type in the autocomplete field.

Below is the example which demostartes this. We will use the index.php from the Simple Autocomplete

One option will be added loadAll.
Note how the SelectCommand is written. In this case we do not need to have a where clause.

The autocomplete.php file is:

<?php
// include the Database driver class (we will use PDO).
require_once 'jq-config.php';
require_once "php/jqGridPdo.php";

// include the jqUtils Class. The class is needed in all jqSuite components.
require_once "php/jqUtils.php";

// include the jqAutocomplete Class
require_once "php/jqAutocomplete.php";

// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// create autocomplete instance
$ac = new jqAutocomplete($conn);
//write the select command
$ac->SelectCommand = "SELECT CompanyName FROM customers ORDER BY CompanyName";
// set the source from where to get data. In this case it is the same file.
$ac->setSource("autocomplete.php");

// Tell the component to load all the data at once
$ac->loadAll = true;
// Enjoy
$ac->renderAutocomplete("#company");
?>

Last Updated: 10/14/11 | © TriRand Ltd., 2011


 Set the value on different input
Set the value on different input
In most cases in real world scenarios the autocomplete is used to show one value, but to set another one in another input element. Usually the second element is hidden from the user.

In this case we will search on one value, but set another value in another field. For demostration purposes we will make this field readonly.
We will use the product table and will set two fields - one for the product name and another for the product id.

In order to demostrate the feature - type some word let say "a", after selecting the value type tab or just leave the field. You will see that the product_id is filled with another value.
Note that if you clear the value of the name the value of the product_id will be cleared too.

The file index.php is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqAutocomplete </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui.custom.css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>

</head>
<body>

<form action="#">
   <label for="product_name">Product: </label>
   <input id="product_name"  />
    <input id="product_id" readonly=readonly name="product_id"/
   <input type="submit" name="submit" value="Submit" />
</form>

<?php include "autocomplete.php";?>
</body>
</html>

The autocomplete.php file:

The difference here is in the SelectCommend. We have select three fields.
The first field is used to set the value of the product_name, the second field is used for display the value and the
third field is used to set the value of the product_id field.

<?php
require_once '../../../jq-config.php';
require_once ABSPATH."php/jqGridPdo.php";
require_once ABSPATH."php/jqUtils.php";
require_once ABSPATH."php/jqAutocomplete.php";

// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");

// create autocomplete instance
$ac = new jqAutocomplete($conn);
//write the select command
$ac->SelectCommand = "SELECT ProductName, ProductName, ProductID FROM products WHERE ProductName LIKE ? ORDER BY ProductName";
// set the source from where to get data. In this case it is the same file.
$ac->setSource("autocomplete.php");
// Set a second parameter, which tell the autocomplete to set a value in the
// product_id field.
// Enjoy
$ac->renderAutocomplete("#product_name", "#product_id");
?>
Last Updated: 10/14/11 | © TriRand Ltd., 2011


 jqDatepicker PHP
jqDatepicker PHP

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Introduction
Introduction

jqDatepicker for PHP is a server-side component built on top of open and widely used standards - jQuery, jQuery UI, ThemeRoller.

The Datepicker is a highly configurable plugin that adds datepicker functionality to your pages. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily.

By default, the datepicker calendar opens in a small overlay onFocus and closes automatically onBlur or when a date is selected. For an inline calendar, simply attach the datepicker to a div or span.

You can use keyboard shortcuts to drive the datepicker:

  • page up/down - previous/next month
  • ctrl+page up/down - previous/next year
  • ctrl+home - current month or open when closed
  • ctrl+left/right - previous/next day
  • ctrl+up/down - previous/next week
  • enter - accept the selected date
  • ctrl+end - close and erase the date
  • escape - close the datepicker without selection

Last Updated: 01/07/11 | © TriRand Ltd., 2011


 Installations and System Requierments
Installations and System Requierments

Last Updated: 01/07/11 | © TriRand Ltd., 2011


 Requierments
Requierments

Browser Support

jqDatepicker for PHP supports all major browsers:

  • Internet Explorer 6.x+
  • FireFox 3.x+
  • Safari 2.x+
  • Google Chrome 2.x+
  • Opera 9.5+

PHP

jqDatePicker is designed to work with PHP versions 5.1+.
Last Updated: 01/07/11 | © TriRand Ltd., 2011


 Quick Install
Quick Install
Download and unzip the contents of the archive to any convenient location. The package contains the following folders:

- [php] - Contains the jqDatepicker PHP class .
- [themes] - Contains the themes shipped with the product. Since jqDatepicker supports jQuery UI Themeroller, any theme compatible with jQuery UI ThemeRoller will work for jqDatepicker as well. Therefore, the package contains just one theme ("Redmond"). You can download any additional themes directly from jQuery UI's ThemeRoller site available here:

http://jqueryui.com/themeroller/

Just add "Redmond" theme in your PHP/HTML file.

<link rel="stylesheet" type="text/css" href="themes/redmond/jquery-ui.custom.css" />

- [js] - The javascript files of jqDatepicker (and the needed libraries). You need to include them in your PHP page.

The first file is "jquery.js" - this is the official jQuery library.
The second file is "jquery-ui.custom.min.js" - this is the jQuery UI library.

The final result you will have in an PHP page containing jqDatepicker would be something similar to that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqAutocomplete </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui.custom.css" />

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>

</head>
<body>
......

<div class="ui-widget">
   <label for="mydate">Date: </label>
   <input id="mydate" />
</div>

<?php include "datepicker.php";?>
.......
</body>
</html>

Save the file as datepicker.php or any desired name in the root directory.

<?php

// include the jqUtils Class. The class is needed in all jqSuite components.
require_once "php/jqUtils.php";

// include the datepicker Class
require_once "php/jqCalendar.php";

$dp = new jqCalendar();
// Set it to mydate element
$dp->renderCalendar("#mydate");

?>

Run the file index.php from your web browser.

Last Updated: 01/07/11 | © TriRand Ltd., 2011


 Theming
Theming

Last Updated: 01/07/11 | © TriRand Ltd., 2011


 Basics and installation
Basics and installation
Please refer to Basics and installation in autocomplete
Last Updated: 09/15/10 | © TriRand Ltd., 2011


 Overview
Overview
The jQuery UI Datepicker plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.datepicker.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible">
   <div class="ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-all">
      <a class="ui-datepicker-prev ui-corner-all">title="Prev"><span class="ui-icon ui-icon-circle-triangle-w">Prev</span></a>
      <a class="ui-datepicker-next ui-corner-all" title="Next"><span class="ui-icon ui-icon-circle-triangle-e">Next</span></a>
      <div class="ui-datepicker-title">
         <span class="ui-datepicker-month">January</span><span class="ui-datepicker-year">2009</span>
      </div>
   </div>
   <table class="ui-datepicker-calendar">
      <thead>
      <tr>
         <th class="ui-datepicker-week-end"><span title="Sunday">Su</span></th>
         ...
      </tr>
      </thead>
      <tbody><tr>
         <td class="ui-datepicker-week-end ui-datepicker-other-month "> 1 </td>
         ...
      </tr>
      </tbody>
   </table>
   <div class="ui-datepicker-buttonpane ui-widget-content">
      <button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all">Today</button>
      <button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all">Done</button>
   </div>
</div>

Note: This is a sample of markup generated by the datepicker plugin, not markup you should use to create a datepicker. The only markup needed for that is <input type="text" /> or <div></div>.

Last Updated: 09/15/10 | © TriRand Ltd., 2011


 Datepicker class guide
Datepicker class guide

Last Updated: 04/09/11 | © TriRand Ltd., 2011


 Variables
Variables
List of public variables that can be used with this class.

Type | Names | Description | Default | Access
boolean | buttonIcon | If this option is set to true it places a buton near the input field, allowing to lunch the datepicker either on focus and when the button is clicked. | false | public
string | fontsize | Set the font size of the widget when it is created. Can be set in any valid measure | 11px | public
boolean | buttonOnly | If this option is set to true it places a buton near the input field, disallowing to lunch the datepicker when we focus the input, but allow lunch them only when the button is clicked | false | public
Last Updated: 04/09/11 | © TriRand Ltd., 2011


 Methods
Methods
getOption( string $option )

Return the the requested option of the datepicker
Parameters:

  • string $option: - the requested option or event.

API Tags:
Access: public

renderCalendar( string $element, [boolean $script = true], [boolean $echo = true] )

Main method which do everthing for the datepicker. Should be called after all settings are done.

Parameters:

  • string $element: The DOM element on which datepicker should be applied
  • boolean $script: - if set to false the script tag: <script type='text/javascript'> will not be included.
  • boolean $echo: if set to false the result is not echoed but returned

API Tags:
Access: public

setEvent( string $event, string $code )

Set a JavaScript event for the datepicker
Parameters:

  • string $event the event name
  • string $code Javascript code:

API Tags:
Access: public

setOption( string $option, [mixed $value = null] )

Set the desired option for datepicker.
Parameters:
string $option option name
mixed $value:

API Tags:
Access: public

Last Updated: 09/15/10 | © TriRand Ltd., 2011


 Options
Options
To be written.
Last Updated: 09/15/10 | © TriRand Ltd., 2011


 Events
Events
To be written.
Last Updated: 09/15/10 | © TriRand Ltd., 2011


 Datepicker tutorials
Datepicker tutorials

Last Updated: 09/15/10 | © TriRand Ltd., 2011


 Attaching datepicker
Attaching datepicker
Attaching datepicker is just easy.
1. You will need to include in the index.php the needed CSS and Java Script files
2. You will need yust to create the instance and attach it to the desired element.

index.php file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqAutocomplete </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui.custom.css" />

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery-ui.custom.min.js" type="text/javascript"></script>

</head>
<body>

<form action="#">
   <label for="mydate">Date: </label>
   <input id="mydate" />
</form>

<?php include "datepicker.php";?>
</body>
</html>

datepicker.php file:

<?php

// include the jqUtils Class. The class is needed in all jqSuite components.
require_once "php/jqUtils.php";
// include the datepicker Class
require_once "php/jqCalendar.php";

$dp = new jqCalendar();
// set to have button icon
$dp->buttonIcon = true;
// Set it to mydate element
$dp->renderCalendar("#mydate");

?>

Last Updated: 09/16/10 | © TriRand Ltd., 2011


 jqChart PHP
jqChart PHP

Welcome to the technical documentation of jqChart for PHP. If you have questions and comments, please use the following channels to get back to us:

Public forums:
http://www.trirand.net/forum/

Email:
support@trirand.net

Last Updated: 06/07/11 | © TriRand Ltd., 2011


 Introduction
Introduction

jqChart PHP is a server side component built on top of open and widely used standard - jQuery.

jqChart is a charting library written in PHP and JavaScript, offering an easy way of adding interactive charts to your web site or web application.

jqChart works in all modern browsers including the iPhone/iPad and Internet Explorer from version 6. Standard browsers use SVG for the graphics rendering. In Internet Explorer graphics are drawn using VML.

jqChart is based on native browser technologies and doesn't require client side plugins like Flash or Java.

jqChart supports line, spline, area, areaspline, column, bar, pie and scatter chart types. Any of these can be combined in one chart.

With the exporting module enabled, your users can export the chart to PNG, JPG, PDF or SVG format at the click of a button, or print the chart directly from the web page.

jqChart uses licensed client-side technology from Highcharts

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Installation & System Requirments
Installation & System Requirments

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Requirments
Requirments

Browser Support

jqChart for PHP supports all major browsers:

  • Internet Explorer 6.x+
  • FireFox 3.x+
  • Safari 2.x+
  • Google Chrome 2.x+
  • Opera 9.5+

PHP

jqChart is designed to work with PHP versions 5.1+.

Databases (optional)

Currently jqChart for PHP supports the following databases:

  • MySQL 5.x+ (PDO)
  • PostgreSQL versions 7.x+ (PDO)
  • SQLite versions 3.x+ (PDO)
  • Microsoft SQL Server 2005+
  • Oracle 8+
  • MySQL (through Mysqli)
  • DB2 (IBM DB2 functions)
  • Array
  • MongoDB

Last Updated: 01/07/11 | © TriRand Ltd., 2011


 Quick Install
Quick Install
Download and unzip the contents of the archive to any convenient location. The package contains the following folders:

- [php] - Contains the jqChart PHP class (jqChart.php) and the optional driver files for the appropriate database. The driver files begin with jqGridxxx.php where xxx is the database name. Also additional file is needed to use the chat separatley - jqUtils.php.
- [themes] - Contains the themes shipped with the product. The theme files are Javascript files and not CSS files. The theme file (if used) should be loaded after the jqChart lib is loaded.
- [js] - The javascript files of jqChart - jquery.jqChart.js. You need to include them in your PHP page.

There are a diffrent scenarious on how to use the component. Below we will consider the two most used.

1. Load the javascript fules in separate page (mostley main page or index.php) and write a chart in another file.

The first file is "jquery.js" - this is the official jQuery library.
The second file is "jquery.jqChart.js" - this is the javascript chart files
The third (optional) file is the teheme file

The final result you will have in an PHP page containing jqChart would be something similar to that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqChart </title>

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.jqChart.js" type="text/javascript"></script>

<!-- this is optional theme file -->>

<script src="themes/dark-blue.js" type="text/javascript"></script>

</head>
<body>
......

<!-- the chart will be created in this place -->>
<?php include "chart.php";?>
.......
</body>
</html>

Save the file as index.php or any desired name in the root directory.

Create a file chart.php with the following content.

<?php
// include the jqUtils Class. The class is needed in all jqSuite components.
require_once "php/jqUtils.php";

// include the jqChart Class
require_once "php/jqChart.php";

$chart = new jqChart();

$chart->setChartOptions(array("defaultSeriesType"=>"line","marginRight"=>130,"marginBottom"=>25))
->setTitle(array('text'=>'Monthly Average Temperature',"x"=>-20))
->setSubtitle(array("text"=>"Source: WorldClimate.com","x"=>-20))
->setxAxis(array("categories"=>array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')))
->setyAxis(array("title"=>array("text"=>"Temperature (°C)")))
->setTooltip(array("formatter"=>"function(){return '<b>'+ this.series.name +'</b><br/>'+this.x +': '+ this.y +' (°C)';}"))
->setLegend(array( "layout"=>"vertical","align"=>"right","verticalAlign"=>'top',"x"=>-10,"y"=>100,"borderWidth"=>0))
->addSeries('Tokyo', array(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6))
->addSeries('New York', array(-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5))
->addSeries('Berlin', array(-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0))
->addSeries('London', array(3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8));

// output the chart
echo $chart->renderChart('',true,'1000');
?>

Run the file index.php from your web browser.

2. All in one file

Optionally you can write all the code in one file. Below we provide a example supposing that a jQuery library should be loaded too.

The file chart.php in this case can look like this:

<?php
// include the jqUtils Class. The class is needed in all jqSuite components.
require_once "php/jqUtils.php";

// include the jqChart Class
require_once "php/jqChart.php";

$chart = new jqChart();

$chart->setChartOptions(array("defaultSeriesType"=>"line","marginRight"=>130,"marginBottom"=>25))
->setTitle(array('text'=>'Monthly Average Temperature',"x"=>-20))
->setSubtitle(array("text"=>"Source: WorldClimate.com","x"=>-20))
->setxAxis(array("categories"=>array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')))
->setyAxis(array("title"=>array("text"=>"Temperature (°C)")))
->setTooltip(array("formatter"=>"function(){return '<b>'+ this.series.name +'</b><br/>'+this.x +': '+ this.y +' (°C)';}"))
->setLegend(array( "layout"=>"vertical","align"=>"right","verticalAlign"=>'top',"x"=>-10,"y"=>100,"borderWidth"=>0))
->addSeries('Tokyo', array(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6))
->addSeries('New York', array(-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5))
->addSeries('Berlin', array(-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0))
->addSeries('London', array(3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8));

$script = '<script src="js/jquery.js" type="text/javascript"></script>';
$script .= '<script src="js/jquery.jqChart.js" type="text/javascript"></script>';

// echo the JS files
echo $script;

// output the chart
echo $chart->renderChart('',true,'1000');
?>

Last Updated: 01/07/11 | © TriRand Ltd., 2011


 Theming
Theming

Last Updated: 05/31/11 | © TriRand Ltd., 2011


 Basics & installation
Basics & installation
Theming in jqChart as opposite to the most jqSuite components is supported with javascript files and not CSS one. This means that you should load a javascript file and not CSS.

Currently the theme switching is done with including a Java Script file. In the future releases this will be a part of php options settings

Currently there are a four themes plus the standart one.

The list of currently available themes is:

  • dark-blue
  • dark-green
  • blue
  • grid

All themes are available in the [themes] folder of the install package.

As of version 4.0 it is possible to set the theme dynamically within PHP script. See setTheme method

It is important to note that the themes file should be loaded after the jqChart file as is shown in the Quick Install

Below is exmple how to do this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqChart </title>

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.jqChart.js" type="text/javascript"></script>
<script src="themes/dark-blue.js" type="text/javascript"></script>
...
</body>
</html>

You to create your own theme starting from an existing one.

Last Updated: 03/13/11 | © TriRand Ltd., 2011


 Chart class guide
Chart class guide

Last Updated: 06/07/11 | © TriRand Ltd., 2011


 Methods
Methods
All methods in this package with exception of renderChart method set a various options for the chart.
Below we will list all the methods with its parameter.

Detailed description of the options is in Options chapter.

jqChart addSeries( string $name, mixed $value, [array $params = null], [mixed $limit = false], [integer $offset = 0] )

Add a data to the series with a given name. If the name exists the data will be overwritten. Data can be added via array, sql query or javascript function

Parameters:

  • string $name: the name of the chart. This will be displayed in the chart
  • mixed $value: can be array, sql query and java script function.
  • array $params: parameters passed to the query in case of SQL data
  • mixed $limit: if set to number the number of records to retrieve
  • integer $offset: how many records to skip in case of sql.

API Tags:
Return: instanceAccess: public

array getChartOptions( )

Return all the option for the Chart

API Tags:
Access: public

string renderChart( [string $div_id = ''], [boolean $createlem = true], [mixed $width = '800'], [ $height = '400'], [string $chart = 'chart'] )

Main method which construct the chart based on the optins set with the previous methods
Parameters:
  • string $div_id: the id of the chart element in the DOM. If empty the default name 'jqchart' is used.
  • boolean $createlem: if set to true a div element is created. If the option is set to false the previous option should be set in order to render the chart to a existing element.
  • mixed $width: set the width of the chart. If a number is used the width is created in pixels. Have sense only if $createlem is true
  • $height: set the height of the chart. If a number is used the height is created in pixels. Have sense only if $createlem is true
  • string $chart: the name which is used when a javascript chart object is created. Can be used later to refer to the chart. The default name is 'chart'

API Tags:
Access: public

jqChart setChartEvent( string $name, string $jscode )

Set event listeners for the chart.
Parameters:
  • string $name: The name of the event, Can be click, load, redraw, selection See documentation for more details
  • string $jscode: The javascript code associated with this event

API Tags:
Return: instance
Access: public

jqChart setChartOptions( mixed $name, [mixed $mixvalue = ''] )

Options regarding the chart area and plot area as well as general chart options.
Parameters:

  • mixed $name: the option name for the chart. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: is the value option in case the name is string

API Tags:
Return: instance
Access: public

jqChart setColors( array $avalue )

Set array containing the default colors for the chart's series.

When all colors are used, new colors are pulled from the start again. Defaults to: array('#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92')
Parameters:

  • array $avalue: values to be set for the colors

API Tags:
Return: instance
Access: public

jqChart setExporting( mixed $name, [mixed $mixvalue = ''] )

Set options for the Exporting module
Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

jqChart setJSCode( string $code )

Put a javascript code after all things are created. The method is executed only once when the chart is created.
Parameters:

  • string $code: - javascript to be executed

API Tags:
Return: instance
Access: public

jqChart setLabels( mixed $name, [mixed $mixvalue = ''] )

Set HTML labels that can be positioined anywhere in the chart area.
Parameters:

  • mixed $name: the option name for the label. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value in case the name is a string

API Tags:
Return: instance
Access: public

jqChart setLanguage( mixed $name, [mixed $mixvalue = ''] )

Set a language object. The default language is English. For detailed info on the object rehfer to the documentation
Parameters:

  • mixed $name: the option name for the language. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value in case the name is a string

API Tags:
Return: instance
Access: public

setLegend [line 225]

jqChart setLegend( mixed $name, [mixed $mixvalue = ''] )

Set the legend. The legend is a box containing a symbol and name for each series item or point item in the chart.
Parameters:

  • mixed $name: the option name for the legend. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

jqChart setLoading( mixed $name, [mixed $mixvalue = ''] )

Set the loading options which control the appearance of the loading screen that covers the plot area on chart operations
Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

jqChart setNavigation( mixed $name, [mixed $mixvalue = ''] )

Set collection of options for buttons and menus appearing in the exporting module.
Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

jqChart setPlotOptions( mixed $name, [array $avalue = ''] )

Set the plot options for the chart.

The plotOptions is a wrapper object for config objects for each series type. The config objects for each series can also be overridden for each series item as given in the series array
Parameters:

  • mixed $name: the name of tyhe option as per documentation
  • array $avalue: array of options = key value pair

API Tags:
Return: instance
Access: public

jqChart setSeriesOption( [string $name = ''], [mixed $option = ''], [mixed $value = ''] )

Set a various options for a serie.
Parameters:

  • string $name: the name for the serie
  • mixed $option: can be a array or string. If array a key value pair should be used, where key is the properti value is the optinvalue
  • mixed $value: the value of the option value in case the option is a string

API Tags:
Return: instance
Access: public

jqChart setSubtitle( mixed $name, [mixed $mixvalue = ''] )

Set the subtitle of the chart
Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

jqChart setTheme( string $name )

Set the theme of the chart - currently we have the following themes - grid, blue, dark-green, dark-blue. The theme is searched in the current directory, so be a carfully when set the name of the theme. The theme can be set via url something like
$chart->setTheme("http://example.com/grid.js");
Parameters:

  • string $name: the name or the url to the theme

API Tags:
Return: instance
Access: public

jqChart setTitle( mixed $name, [mixed $mixvalue = ''] )

Set the main title of the chart
Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

jqChart setTooltip( mixed $name, [mixed $mixvalue = ''] )

Set options for the tooltip that appears when the user hovers over a series or point
Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

jqChart setxAxis( mixed $name, [mixed $mixvalue = ''] )

Set the X axis or category axis. Normally this is the horizontal axis, though if the chart is inverted this is the vertical axis.

In case of multiple axes, the xAxis node is an array of configuration objects.
Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

jqChart setyAxis( mixed $name, [mixed $mixvalue = ''] )

Set the Y axis or value axis. Normally this is the vertical axis, though if the chart is inverted this is the horiontal axis. In case of multiple axes, the yAxis node is an array of configuration objects.
Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

Last Updated: 03/13/11 | © TriRand Ltd., 2011


 jqChart options
jqChart options

Last Updated: 03/13/11 | © TriRand Ltd., 2011


 Chart options
Chart options
Options regarding the chart area and plot area as well as general chart options.

These options should be set with

jqChart setChartOptions( mixed $name, [mixed $mixvalue = ''] )

Parameters:
  • mixed $name: the option name for the chart. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: is the value option in case the name is string

API Tags:
Return: instance
Access: public

Examples:
1. Using array:

$chart = new jqChart();
$chart->setChartOptions(array("defaultSeriesType"=>"line","marginRight"=>130));
...

2.The same using name value

$chart = new jqChart();
$chart->setChartOptions("defaultSeriesType","line")
->setChartOptions("marginRight",130);
...

Option name | Type | Default
alignTicks | Boolean | true
When using multiple axis, the ticks of two or more opposite axes will automatically be aligned by adding ticks to the axis or axes with the least ticks. This can be prevented by setting alignTicks to false. If the grid lines look messy, it's a good idea to hide them for the secondary axis by setting gridLineWidth to 0. Defaults to true.
animation | Boolean|Array | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation. The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported: duration The duration of the animation in milliseconds. easing The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
backgroundColor | Color | "#FFFFFF"
The background color or gradient for the outer chart area. Defaults to "#FFFFFF". Defaults to "#FFFFFF".
borderColor | Color | "#4572A7"
The color of the outer chart border. The border is painted using vector graphic techniques to allow rounded corners. Defaults to "#4572A7". Defaults to "#4572A7".
borderRadius | Number | 5
The corner radius of the outer chart border.
borderWidth | Number | 0
The pixel width of the outer chart border. The border is painted using vector graphic techniques to allow rounded corners.
className | String | ""
A CSS class name to apply to the charts container div, allowing unique CSS styling for each chart. Defaults to "".
defaultSeriesType | String |
Alias of type. See below
height | Number | null
An explicit height for the chart. By default the height is calculated from the offset height of the containing element.
ignoreHiddenSeries | Boolean | true
If true, the axes will scale to the remaining visible series once one series is hidden. If false, hiding and showing a series will not affect the axes or the other series. For stacks, once one series within the stack is hidden, the rest of the stack will close in around it even if the axis is not affected. Defaults to true.
inverted | Boolean | false
Whether to invert the axes so that the x axis is horizontal and y axis is vertical. When true, the x axis is reversed by default. If a bar plot is present in the chart, it will be inverted automatically. Defaults to false.
margin | Array | null
The margin between the outer edge of the chart and the plot area. The numbers in the array designate top, right, bottom and left respectively. Use the options marginTop, marginRight, marginBottom and marginLeft for shorthand setting of one option. The margin is 0 by default. The actual space is dynamically calculated from the offset of axis labels, axis title, title, subtitle and legend in addition to the spacingTop, spacingRight, spacingBottom and spacingLeft options.
marginTop | Number | null
The margin between the top outer edge of the chart and the plot area. Use this to set a fixed pixel value for the margin as opposed to the default dynamic margin. See also spacingTop. Defaults to null.
marginRight | Number | 50
The margin between the right outer edge of the chart and the plot area. Use this to set a fixed pixel value for the margin as opposed to the default dynamic margin. See also spacingRight.
marginBottom | Number | 70
The margin between the bottom outer edge of the chart and the plot area. Use this to set a fixed pixel value for the margin as opposed to the default dynamic margin. See also spacingBottom.
marginLeft | Number | 80
The margin between the left outer edge of the chart and the plot area. Use this to set a fixed pixel value for the margin as opposed to the default dynamic margin. See also spacingLeft.
plotBackgroundColor | Color | null
The background color or gradient for the plot area.
plotBackgroundImage | String | null
The URL for an image to use as the plot background. To set an image as the background for the entire chart, set a CSS background image to the container element.
plotBorderColor | Color | "#C0C0C0"
The color of the inner chart or plot area border.
plotBorderWidth | Number | 0
The pixel width of the plot area border.
plotShadow | Boolean | false
Whether to apply a drop shadow to the plot area. Requires that plotBackgroundColor be set.
reflow | Boolean | true
Whether to reflow the chart to fit the width of the container div on resizing the window.
shadow | Boolean | False
Whether to apply a drop shadow to the outer chart area. Requires that backgroundColor be set.
showAxes | Boolean | false
Whether to show the axes initially. This only applies to empty charts where series are added dynamically, as axes are automatically added to cartesian series.
spacingTop | Number | 10
The space between the top edge of the chart and the content (plot area, axis title and labels, title, subtitle or legend in top position).
spacingRight | Number | 10
The space between the right edge of the chart and the content (plot area, axis title and labels, title, subtitle or legend in top position).
spacingBottom | Number | 15
The space between the bottom edge of the chart and the content (plot area, axis title and labels, title, subtitle or legend in top position).
spacingLeft | Number | 10
The space between the left edge of the chart and the content (plot area, axis title and labels, title, subtitle or legend in top position).
style | Array |
Additional CSS styles to apply inline to the container div. Defaults to: array( "fontFamily"=> '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font "fontSize=> '12px' )
type | String | "line"
The default series type for the chart. Can be one of line, spline, area, areaspline, column, bar, pie and scatter. Defaults to "line".
width | Number | null
An explicit width for the chart. By default the width is calculated from the offset width of the containing element.
zoomType | String | ""
Decides in what dimentions the user can zoom by dragging the mouse. Can be one of x, y or xy. Defaults to "".

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Chart events
Chart events
Event listeners for the chart.

These options should be set with set setChartEvent method

jqChart setChartEvent( string $name, string $jscode )

Parameters:
  • string $name: The name of the event, Can be click, load, redraw, selection See documentation for more details
  • string $jscode: The javascript code associated with this event

API Tags:
Return: instance
Access: public

Example. Alert coordinates onclick

$chart = new jqChart();

$onclick = "function(event) {
    alert ('x: '+ event.xAxis[0].value +', y: '+ event.yAxis[0].value);
}";

$chart->setChartEvent("click", $onclick);
...

Option name | Type | Default
addSeries | JS Function | null
Fires when a series is added to the chart after load time, using the addSeries method. The this keyword refers to the chart object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery. Through event.options you can access the series options that was passed to the addSeries method. Returning false prevents the series from being added.
click | JS Function | null
Fires when clicking on the plot background. The this keyword refers to the chart object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts.
Information on the clicked spot can be found through event.xAxis and event.yAxis, which are arrays containing the axes of each dimension and each axis' value at the clicked spot. The primary axes are event.xAxis[0] and event.yAxis[0]. Remember the unit of a datetime axis is milliseconds since 1970-01-01 00:00:00.
click: function(e) {
console.log(
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', e.xAxis[0].value),
e.yAxis[0].value
)
}
load | JS Function | null
Fires when the chart is finished loading. The this keyword refers to the chart object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery.
redraw | JS Function | null
Fires when the chart is redrawn, either after a call to chart.redraw() or after an axis, series or point is modified with the redraw option set to true. The this keyword refers to the chart object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery
selection | JS Function
Fires when an area of the chart has been selected. Selection is enabled by setting the chart's zoomType. The this keyword refers to the chart object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery. The default action for the selection event is to zoom the chart to the selected area. It can be prevented by calling event.preventDefault().
Information on the selected area can be found through event.xAxis and event.yAxis, which are arrays containing the axes of each dimension and each axis' min and max values. The primary axes are event.xAxis[0] and event.yAxis[0]. Remember the unit of a datetime axis is milliseconds since 1970-01-01 00:00:00.
selection: function(event) {
// log the min and max of the primary, datetime x-axis
console.log(
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', event.xAxis[0].min),
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', event.xAxis[0].max)
);
// log the min and max of the y axis
console.log(event.yAxis[0].min, event.yAxis[0].max);
}

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Colors
Colors
An array containing the default colors for the chart's series. When all colors are used, new colors are pulled from the start again.
Defaults to: array('#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92')

The method used:

jqChart setColors( array $avalue )

Parameters:

  • array $avalue: values to be set for the colors

API Tags:
Return: instance
Access: public

$chart = new jqChart();

$onclick = "function(event) {
    alert ('x: '+ event.xAxis[0].value +', y: '+ event.yAxis[0].value);
}";

$chart->setColors(array('#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'));
...
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Labels
Labels
Set HTML labels that can be positioined anywhere in the chart area.

The method used:

jqChart setLabels( mixed $name, [mixed $mixvalue = ''] )

Parameters:

  • mixed $name: the option name for the label. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value in case the name is a string

API Tags:
Return: instance
Access: public

Example:

...

$chart = new jqChart();
$chart->setTitle(array('text'=>'Combination chart'))
->setxAxis(array(
    "categories"=>array('Apples', 'Oranges', 'Pears', 'Bananas', 'Plums')
))
->setTooltip(array("formatter"=>$tooltip))
->setLabels(array(
    "items"=>array(array(
        "html"=> 'Total fruit consumption',
        "style"=>array("left"=>"40px","top"=>"8px","color"=>"black")
    ))
)) ;
...

Option name | Type | Default
items | Array (See below) | null
An array containing configuration for each label.
style | Array | null
Shared CSS styles for all labels Defaults to array( "color"=>'#3E576F' }

items Array

Option name | Type | Default
html/td> | String | null
Inner HTML or text for the label. Defaults to "".
style | Array | null
CSS styles for each label. To position the label, use left and top like this:
array(
"left" => '100px',
"top" => '100px'
}

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Language
Language
Set a language object. The default language is English.

Method used

jqChart setLanguage( mixed $name, [mixed $mixvalue = ''] )

Parameters:

  • mixed $name: the option name for the language. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value in case the name is a string

Example:

...

$chart = new jqChart();
->setLanguage(array(
"weekdays"=> array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi')
)) ;
...

Option name | Type | Default
decimalPoint | String | "."
The default decimal point used in the Highcharts.numberFormat method unless otherwise specified in the function arguments.
downloadPNG | String | "Download PNG image"
Exporting module only. The text for the PNG download menu item.
downloadJPEG | String | "Download JPEG image"
Exporting module only. The text for the JPEG download menu item.
downloadPDF | String | "Download PDF document"
Exporting module only. The text for the PDF download menu item.
downloadSVG | String | "Download SVG vector image"
Exporting module only. The text for the SVG download menu item.
exportButtonTitle | String | "Export to raster or vector image"
Exporting module only. The tooltip text for the export button.
loading | String | Loading...
The loading text that appears when the chart is set into the loading state following a call to chart.showLoading.
months | Array | See description
An array containing the months names. Defaults to array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December').
printButtonTitle | String | "Print the chart"
Exporting module only. The tooltip text for the print button.
resetZoom | String | Reset Zoom
The text for the label appearing when a chart is zoomed.
resetZoomTitle | String | Reset zoom level
The tooltip title for the label appearing when a chart is zoomed.
thousandsSep | String | ","
The default thousands separator used in the Highcharts.numberFormat method unless otherwise specified in the function arguments.
weekdays | Array | see Description
An array containing the weekday names. Defaults to array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Legend
Legend
Set the legend. The legend is a box containing a symbol and name for each series item or point item in the chart.

Method used

jqChart setLegend( mixed $name, [mixed $mixvalue = ''] )

Parameters:

  • mixed $name: the option name for the legend. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

Example:

...
$chart = new jqChart();
$chart->setChartOptions(array(
    "defaultSeriesType"=>"bar"
))
->setLegend(array(
    "layout"=> 'vertical',
    "align"=> 'right',
    "verticalAlign"=> 'top',
    "x"=> -100,
    "y"=> 100,
    "floating"=> true,
    "borderWidth"=> 1,
    "backgroundColor"=> '#FFFFFF',
    "shadow"=>true
))
...

Option name | Type | Default
align | String | center
The horizontal alignment of the legend box within the chart area. Defaults to "center".
backgroundColor | Color | null
The background color of the legend, filling the rounded corner border. Defaults to null.
borderColor | Color | #909090
The color of the drawn border around the legend. Defaults to #909090.
borderRadius | Number | 5
The border corner radius of the legend. Defaults to 5.
borderWidth | Number | 1
The width of the drawn border around the legend
enabled | Boolean | true
Enable or disable the legend. Defaults to true.
floating | Boolean | false
When the legend is floating, the plot area ignores it and is allowed to be placed below it.
itemHiddenStyle | Array | array("color" =>'#CCC')
CSS styles for each legend item when the corresponding series or point is hidden. Properties are inherited from style unless overridden here.
itemHoverStyle | Array | array("color"=>'#000')
CSS styles for each legend item in hover mode. Properties are inherited from style unless overridden here.
itemStyle | Array | array("cursor"=>'pointer',"color"=>'#3E576F')
CSS styles for each legend item.
itemWidth | Number | null
The width for each legend item. This is useful in a horizontal layout with many items when you want the items to align verticall.
labelFormatter | JS Function | See below
Callback function to format each of the series' labels. The this keyword refers to the series object, or the point object in case of pie charts. Defaults to: labelFormatter: function() { return this.name } When set a "js:" should be set before the string.
lineHeight | Number | 15
f the plot area sized is calculated automatically and the legend is not floating, the legend margin is the space between the legend and the axis labels or plot area.
reversed | Boolean | false
Whether to reverse the order of the legend items compared to the order of the series or points as defined in the configuration object
shadow | Boolean | false
Whether to apply a drop shadow to the legend. A backgroundColor also needs to be applied for this to take effect.
style | Array |
CSS styles for the legend area.
symbolPadding | Number | 5
The pixel padding between the legend item symbol and the legend item text
symbolWidth | Number | 30
The pixel width of the legend item symbol
verticalAlign | String | "bottom"
The vertical alignment of the legend box. Can be one of "top", "middle" or "bottom". Vertical position can be further determined by the "y" option.
width | Number | null
The width of the legend box, not including style.padding
x | Number | 15
The x offset of the legend relative to it's horizontal alignment align within chart.spacingLeft and chart.spacingRight. Negative x moves it to the left, positive x moves it to the right. The default value of 15 together with align: "center" puts it in the center of the plot area.
y | Number | 0
The vertical offset of the legend relative to it's vertical alignment verticalAlign within chart.spacingTop and chart.spacingBottom. Negative y moves it up, positive y moves it down.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Loading
Loading
The loading options control the appearance of the loading screen that covers the plot area on chart operations. This screen only appears after an explicit call to Java Script chart.showLoading() method. It is a utility for developers to communicate to the end user that something is going on, for example while retrieving new data via an XHR connection. The "Loading..." text itself is not part of this configuration object, but part of the Language object.

Method used

jqChart setLoading( mixed $name, [mixed $mixvalue = ''] )

Parameters:

  • mixed $name: the option name for the legend. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

Option name | Type | Default
hideDuration | Number | 100
The duration in milliseconds of the fade out effect
labelStyle | Array |
CSS styles for the loading label span.
showDuration | Number | 100
The duration in milliseconds of the fade in effect.
style | Array |
CSS styles for the loading screen that covers the plot area.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 PlotOptions
PlotOptions
The plotOptions is a wrapper object for config objects for each series type. The config objects for each series can also be overridden for each series item as given in the series array.

Configuration options for the series are given in three levels. Options for all series in a chart are given in the plotOptions.series object. Then options for all series of a specific type are given in the plotOptions of that type, for example plotOptions.line. Next, options for one single series are given in the series array.

Method used:

jqChart setPlotOptions( mixed $name, [array $avalue = ''] )

Set the plot options for the chart.

The plotOptions is a wrapper object for config objects for each series type. The config objects for each series can also be overridden for each series item as given in the series array
Parameters:

  • mixed $name: the name of the option
  • array $avalue: array of options = key value pair

API Tags:
Return: instance
Access: public

Example:

...
$chart = new jqChart();
$chart->setChartOptions(array("defaultSeriesType"=>"line"))
->setPlotOptions(
   array(
      "line"=>array(
         "dataLabels"=>array("enabled"=>true),"enableMouseTracking"=> false
      )
   )
)
...

Option name | Type | Default
area | Array |
Area plot options.
areaspline | Array |
Areaspline plot options.
bar | Array |
Bar plot options.
column | Array |
Column plot options.
line | Array |
Line plot options.
pie | Array |
Pie plot options.
series | Array |
General options for all series regardless of type.
scatter | Array |
Scatter plot options.
spline | Array |
Spline plot options.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 area
area
Area plot options

Option name | Type | Default
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null
Define the z index of the series.
fillColor | Color | null
Fill color or gradient for the area. When null, the series' color is used with the series' fillOpacity.
fillOpacity | Number | 0.75
Fill opacity for the area.
lineColor | Color | null
A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting allows setting a separate color for the line without altering the fillColor.
threshold | Number | 0
The Y axis value to serve as the base for the area, for distinguishing between values above and below a threshold.

Last Updated: 03/13/11 | © TriRand Ltd., 2011


 dataLabels
dataLabels
dataLabels array

Option name | Type | Default
align | String | "center"
The alignment of the data label compared to the point. Can be one of "left", "center" or "right".
enabled | Boolean | false
Enable or disable the data labels.
formatter | JS Function | See
Callback JavaScript function to format the data label. Available data are:
  • this.percentage Stacked series and pies only. The point's percentage of the total.
  • this.point The point object. The point name, if defined, is available through this.point.name.
  • this.series: The series object. The series name is available through this.series.name.
  • this.total Stacked series only. The total value at this point's x value.
  • this.x: The y value.
  • this.y: The y value.
Default to "formatter"=>"js:function() {
return this.y;
}"
Note that if it is defined a "js:" should be put before the string.
rotation | Number | 0
Text rotation in degrees.
staggerLines
step
style | array
Styles for the label
x | Number | 0
The x position offset of the label relative to the point.
y | Number | -6
-6 The y position offset of the label relative to the point.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 events
events
Events for the area. All events are a javascript functions.

Event | Description
click | Fires when the series is clicked. The this keyword refers to the series object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. Additionally, event.point holds a pointer to the nearest point on the graph.
checkboxClick | Fires when the checkbox next to the series' name in the legend is clicked.. The this keyword refers to the series object itself. One parameter, event, is passed to the function. The state of the checkbox is found by event.checked. Return false to prevent the default action which is to toggle the select state of the series.
hide | Fires when the series is hidden after chart generation time, either by clicking the legend item or by calling .hide().
legendItemClick | Fires when the legend item belonging to the series is clicked. The this keyword refers to the series object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. The default action is to toggle the visibility of the series. This can be prevented by returning false or calling event.preventDefault().
mouseOver | Fires when the mouse enters the graph. The this keyword refers to the series object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts.
mouseOut | Fires when the mouse leaves the graph. The this keyword refers to the series object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. If the stickyTracking option is true, mouseOut doesn't happen before the mouse enters another graph or leaves the plot area.
show | Fires when the series is shown after chart generation time, either by clicking the legend item or by calling .show().
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 marker
marker
Marker options

Option name | Type | Default
enabled | Boolean | true
Enable or disable the point marker.
fillColor | Color | null
The fill color of the point marker. When null, the series' or point's color is used.
lineColor | Color | null
The color of the point marker's outline. When null, the series' or point's color is used.
lineWidth | Number | 0
The width of the point marker's outline.
radius | Number | 0
The radius of the point marker.
states | Array |
Interaction states for the point marker.
symbol | String | null
A predefined shape or symbol for the marker. When null, the symbol is pulled from options.symbols. Other possible values are "circle", "square", "diamond", "triangle" and "triangle-down". Additionally, the URL to a graphic can be given on this form: "url(graphic.png)".
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 point
point
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 states
states
States options

Option name | Type | Default
hover | array |
Configuration options for the hovered line. Members are inherited from the default line configuration, but single members can be overridden.
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 areaspline
areaspline
Areaspline plot options

Option name | Type | Default
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null
Define the z index of the series.
fillColor | Color | null
Fill color or gradient for the area. When null, the series' color is used with the series' fillOpacity.
fillOpacity | Number | 0.75
Fill opacity for the area.
lineColor | Color | null
A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting allows setting a separate color for the line without altering the fillColor.
threshold | Number | 0
The Y axis value to serve as the base for the area, for distinguishing between values above and below a threshold.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 dataLabels
dataLabels
Area plot options

Option name | Type | Default
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null
Define the z index of the series.
fillColor | Color | null
Fill color or gradient for the area. When null, the series' color is used with the series' fillOpacity.
fillOpacity | Number | 0.75
Fill opacity for the area.
lineColor | Color | null
A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting allows setting a separate color for the line without altering the fillColor.
threshold | Number | 0
The Y axis value to serve as the base for the area, for distinguishing between values above and below a threshold.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 events
events
Events for the areaspline. All events are a javascript functions.

Event | Description
click | Fires when the series is clicked. The this keyword refers to the series object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. Additionally, event.point holds a pointer to the nearest point on the graph.
checkboxClick | Fires when the checkbox next to the series' name in the legend is clicked.. The this keyword refers to the series object itself. One parameter, event, is passed to the function. The state of the checkbox is found by event.checked. Return false to prevent the default action which is to toggle the select state of the series.
hide | Fires when the series is hidden after chart generation time, either by clicking the legend item or by calling .hide().
legendItemClick | Fires when the legend item belonging to the series is clicked. The this keyword refers to the series object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. The default action is to toggle the visibility of the series. This can be prevented by returning false or calling event.preventDefault().
mouseOver | Fires when the mouse enters the graph. The this keyword refers to the series object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts.
mouseOut | Fires when the mouse leaves the graph. The this keyword refers to the series object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. If the stickyTracking option is true, mouseOut doesn't happen before the mouse enters another graph or leaves the plot area.
show | Fires when the series is shown after chart generation time, either by clicking the legend item or by calling .show().
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 bar
bar
Bar plot options

Option name | Type | Default
borderColor | Color | "#FFFFFF"
The color of the border surronding each column or bar.
borderRadius | Number | 0
The corner radius of the border surronding each column or bar.
borderWidth | Number | 1
The width of the border surronding each column or bar.
colorByPoint | Boolean | false
When using automatic point colors pulled from the options.colors collection, this option determines whether the chart should receive one color per series or one color per point.
groupPadding | Number | 0.2
Padding between each value groups, in x axis units.
minPointLength | Number | 0
The minimal height for a column or width for a bar. By default, 0 values are not shown. To visualize a 0 (or close to zero) point, set the minimal point length to a pixel value like 3. In stacked column charts, minPointLength might not be respected for tightly packed values.
pointPadding | Number | 0.1
Padding between each column or bar, in x axis units.
pointWidth | Number | null
A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from the pointPadding and groupPadding.
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null
Define the z index of the series.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 column
column
Column plot options

Option name | Type | Default
borderColor | Color | "#FFFFFF"
The color of the border surronding each column or bar.
borderRadius | Number | 0
The corner radius of the border surronding each column or bar.
borderWidth | Number | 1
The width of the border surronding each column or bar.
colorByPoint | Boolean | false
When using automatic point colors pulled from the options.colors collection, this option determines whether the chart should receive one color per series or one color per point.
groupPadding | Number | 0.2
Padding between each value groups, in x axis units.
minPointLength | Number | 0
The minimal height for a column or width for a bar. By default, 0 values are not shown. To visualize a 0 (or close to zero) point, set the minimal point length to a pixel value like 3. In stacked column charts, minPointLength might not be respected for tightly packed values.
pointPadding | Number | 0.1
Padding between each column or bar, in x axis units.
pointWidth | Number | null
A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from the pointPadding and groupPadding.
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null
Define the z index of the series.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 line
line
Line plot options

Option name | Type | Default
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null
Define the z index of the series.
step | Boolean | false
Whether to apply steps to the line.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 pie
pie
Pie plot options

Option name | Type | Default
borderColor | Color | "#FFFFFF"
The color of the border surronding each slice.
borderWidth | Number | 1
The width of the border surronding each slice.
center | Array | array("50%","50%")
The center of the pie chart relative to the plot area. Can be percentages or pixel values.
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null
Define the z index of the series.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 series
series
Series plot options

Option name | Type | Default
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 scatter
scatter
Scatter plot options

Option name | Type | Default
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 spline
spline
Spline plot options

Option name | Type | Default
allowPointSelect | Boolean | false
Allow this series' points to be selected by clicking on the markers, bars or pie slices.
animation | Boolean | true
Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to false here. It can be overridden for each individual API method as a function parameter. The only animation not affected by this option is the initial series animation, see plotOptions.series => animation.
The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery easing and a duration of 500 ms. If used as a configuration object, the following properties are supported:
duration
The duration of the animation in milliseconds.
easing
The easing can be set to linear or swing. More easing functions are available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the jQuery docs.
color | String
The main color for the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
cursor String ""
You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user that the points and lines can be clicked.
dashStyle | String | null
A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle include:
  • Solid
  • ShortDash
  • ShortDot
  • ShortDashDot
  • ShortDashDotDot
  • Dot
  • Dash
  • LongDash
  • DashDot
  • LongDashDot
  • LongDashDotDot
dataLabels | array
Defines the appearance of the data labels, static labels for each point.
enableMouseTracking | Boolean | true
Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on graphs and points. For large datasets it improves performance.
events | Array | See here
Event listeners for the series.
id | String | null
An id for the series. This can be used after render time to get a pointer to the series object
lineWidth | Number | 2
Pixel with of the graph line.
marker | Array | See here
Defines the appearance of the point markers.
point | Array | See here
See here
pointStart | Number | 0
If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a series contains one yearly value starting from 1945, set pointStart to 1945.
pointInterval | Number | 1
If no x values are given for the points in a series, pointInterval defines the interval of the x values. For example, if a series contains one value every decade starting from year 0, set pointInterval to 10.
selected | Boolean | false
Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be checked for a selected series.
shadow | Boolean | true
Whether to apply a drop shadow to the graph line.
showCheckbox | Boolean | false
If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox is determined by the selected option.
showInLegend | Boolean | true
Whether to display this particular series or series type in the legend.
stacking | String | null
Whether to stack the values of each series on top of each other. Possible values are null to disable, "normal" to stack by value or "percent".
states | Array | See here
A wrapper array for all the series options in specific states.
stickyTracking | Boolean | true
Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is false, the tooltip will be hidden when moving the mouse between series.
visible | Boolean | true
Set the initial visibility of the series.
zIndex | Number | null

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Series
Series
The actual series to append to the chart. In addition to the members listed below, any member of the plotOptions for that specific type of plot can be added to a series individually. For example, even though a general lineWidth is specified in plotOptions.series, an individual lineWidth can be specified for each series.

The methods used:

jqChart addSeries( string $name, mixed $value, [array $params = null], [mixed $limit = false], [integer $offset = 0] )

Add a data to the series with a given name. If the name exists the data will be overwritten. Data can be added via array, sql query or javascript function

Parameters:

  • string $name: the name of the chart. This will be displayed in the chart
  • mixed $value: can be array, sql query and java script function.
  • array $params: parameters passed to the query in case of SQL data
  • mixed $limit: if set to number the number of records to retrieve
  • integer $offset: how many records to skip in case of sql.

API Tags:
Return: instance
Access: public

jqChart setSeriesOption( [string $name = ''], [mixed $option = ''], [mixed $value = ''] )

Set a various options for a serie.
Parameters:

  • string $name: the name for the serie
  • mixed $option: can be a array or string. If array a key value pair should be used, where key is the properti value is the optinvalue
  • mixed $value: the value of the option value in case the option is a string

API Tags:
Return: instance
Access: public

The data is added with addSeries method.
Array Data
1. A list of numerical values. In this case, the numberical values will be interpreted and y values, and x values will be automatically calculated, either starting at 0 and incrementing by 1, or from pointStart and pointInterval given in the plotOptions. If the axis is has categories, these will be used. Example:

...
$chart = new jqChart();
$chart->addSeries('Tokyo', array(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6))
...

2. A list of arrays with two values. In this case, the first value is the x value and the second is the y value. If the first value is a string, it is applied as the name of the point, and the x value is incremented following the above rules. Example:

...
$chart = new jqChart();
->addSeries('data', array(
arraY(20, 20), array(80, 80)
));
...

3. A list of object with named values. In this case the objects are point configuration objects as seen under options.point. Example:

...
$chart = new jqChart();
->addSeries('data', array(
array(
   "name" =>'Point 1',
   "color"=> '#00FF00',
   "y"=> 0
),
array(
   "name" =>'Point 2',
   "color"=> '#FF00FF',
   "y"=> 5
)
));
...

Data can be added via Javascript function
Example:

...
$randdata = << RNDATA
(function() {
// generate an array of random data
    var data = [],
    time = (new Date()).getTime(),
    i;
    for (i = -19; i <= 0; i++) {
        data.push({
            x: time + i * 1000,
            y: Math.random()
        });
    }
    return data;
})()
RNDATA;
...
$chart = new jqChart();
$chart->addSeries('Random data', 'js:'.$randdata );
...

Data can be added direct via SQL query.
Example

...

require_once ABSPATH."php/jqUtils.php";
require_once ABSPATH."php/jqGridPdo.php";
require_once ABSPATH."php/jqChart.php";

$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Tell the db that we use utf-8
jqGridDB::query($conn,"SET NAMES utf8");

$chart = new jqChart($conn);
$chart->addSeries("MyOrders","SELECT SUM(ordersum) FROM orders GROUP BY order_date");
...
Last Updated: 03/13/11 | © TriRand Ltd., 2011


 Options
Options
Series options.
Use setSeriesOptions method to set a values

Option name | Type | Default
stack | Mixed | null
This option allows grouping series in a stacked chart. The stack option can be a string or a number or anything else, as long as the grouped series' stack options match each other.
type | String | "line"
"line" The type of series. Can be one of area, areaspline, bar, column, line, pie, scatter or spline.
xAxis | Number | 0
When using dual or multiple x axes, this number defines which xAxis the particular series is connected to. It refers to the index of the axis in the xAxis array, with 0 being the first.
yAxis | Number | 0
When using dual or multiple y axes, this number defines which yAxis the particular series is connected to. It refers to the index of the axis in the yAxis array, with 0 being the first.
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Subtitle
Subtitle
The chart's subtitle

Method used

jqChart setSubtitle( mixed $name, [mixed $mixvalue = ''] )

Parameters:
  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

Example:

...

$chart = new jqChart();
$chart->setChartOptions(array("defaultSeriesType"=>"line","marginRight"=>130,"marginBottom"=>25))
->setTitle(array('text'=>'Monthly Average Temperature',"x"=>-20))
->setSubtitle(array("text"=>"Source: WorldClimate.com","x"=>-20))
...

Option name | Type | Default
align | String | "center"
The horizontal alignment of the subtitle. Can be one of "left", "center" and "right".
floating | Boolean | false
When the subtitle is floating, the plot area will not move to make space for it.
text | String | ""
The subtitle of the chart.
style | Arrray |
CSS styles for the title. Exact positioning of the title can be achieved by changing the margin property, or by adding position: "absolute" and left and top properties.
verticalAlign | String | "top"
The vertical alignment of the title. Can be one of "top", "middle" and "bottom".
x | Number | 0
The x position of the subtitle relative to the alignment within chart.spacingLeft and chart.spacingRight.
y | Number | 40
The y position of the subtitle relative to the alignment within chart.spacingTop and chart.spacingBottom.
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Title
Title
The chart's subtitle

Method used

jqChart setTitle( mixed $name, [mixed $mixvalue = ''] )

Parameters:
  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

Example:

...

$chart = new jqChart();
$chart->setChartOptions(array("defaultSeriesType"=>"line","marginRight"=>130,"marginBottom"=>25))
->setTitle(array('text'=>'Monthly Average Temperature',"x"=>-20))
->setSubtitle(array("text"=>"Source: WorldClimate.com","x"=>-20))
...

Option name | Type | Default
align | String | "center"
The horizontal alignment of the title. Can be one of "left", "center" and "right".
floating | Boolean | false
When the title is floating, the plot area will not move to make space for it.
text | String | ""
The title of the chart.
margin | Number | 15
The margin between the title and the plot area, or if a subtitle is present, the margin between the subtitle and the plot area.
style | Arrray |
CSS styles for the title. Exact positioning of the title can be achieved by changing the margin property, or by adding position: "absolute" and left and top properties.
verticalAlign | String | "top"
The vertical alignment of the title. Can be one of "top", "middle" and "bottom".
x | Number | 0
The x position of the title relative to the alignment within chart.spacingLeft and chart.spacingRight.
y | Number | 25
The y position of the title relative to the alignment within chart.spacingTop and chart.spacingBottom.
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Tooltip
Tooltip
Options for the tooltip that appears when the user hovers over a series or point.

Method Used

jqChart setTooltip( mixed $name, [mixed $mixvalue = ''] )

Parameters:
  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

Example:

...
$chart = new jqChart();
$chart->setChartOptions(array("defaultSeriesType"=>"line","marginRight"=>130,"marginBottom"=>25))
->setTooltip(array("formatter"=>"function(){return '<b>'+ this.series.name +'</b><br/>'+this.x +': '+ this.y +'
(°C)';}"
))
...

Option name | Type | Default
backgroundColor | Color | "rgba(255, 255, 255, .85)"
The background color or gradient for the tooltip.
borderColor | Color | "auto"
The color of the tooltip border. When null, the border takes the color of the corresponding series or point.
borderRadius | Number | 5
The radius of the rounded border corners.
borderWidth | number | 2
The pixel width of the tooltip border.
crosshairs | Mixed | null
Display crosshairs to connect the points with their corresponding axis values. The crosshairs can be defined as a boolean, an array of booleans or an object.
Boolean
If the crosshairs option is true, a single crosshair relating to the x axis will be shown.
Array of booleans
In an array of booleans, the first value turns on the x axis crosshair and the second value to the y axis crosshair. Use [true, true] to show complete crosshairs.
Array of objects
In an array of objects, the first value applies to the x axis crosshair and the second value to the y axis crosshair. For each dimension, a width, color and dashStyle can be given. can be given.
enabled | Boolean | true
Enable or disable the tooltip.
formatter | Function
Callback function to format the text of the tooltip. Return false to disable tooltip for a specific point on series.
A subset of HTML is supported. The HTML of the tooltip is parsed and converted to SVG, therefore this isn't a complete HTML renderer. The following tabs are supported: b, strong, i, em, br, span tags . Spans can be styled with a style attribute, but only text-related CSS that is shared with SVG is handled.
The tooltip can be shared between multiple series through the shared option. The available data in the formatter differ a bit depending on whether the tooltip is shared or not. In a shared tooltip, all properties except x, which is common for all points, are kept in an array, this.points.
Available data are:

this.percentage (not shared) / this.points[i].percentage (shared)
Stacked series and pies only. The point's percentage of the total.
this.point (not shared) / this.points[i].point (shared)
The point object. The point name, if defined, is available through this.point.name.
this.points
In a shared tooltip, this is an array containing all other properties for each point. this.series (not shared) / this.points[i].series (shared) The series object. The series name is available through this.series.name.
this.total (not shared) / this.points[i].total (shared)
Stacked series only. The total value at this point's x value.
this.x
this.y (not shared) / this.points[i].y (shared) The y value.
shadow | Boolean | true
Whether to apply a drop shadow to the tooltip.
shared | Boolean | false
When the tooltip is shared, the entire plot area will capture mouse movement, and tooltip texts for all series will be shown in a single bubble. This is recommended for single series charts and for iPad optimized sites.
snap | Number | 10/25
Proximity snap for graphs or single points. Does not apply to bars, columns and pie slices. It defaults to 10 for mouse-powered devices and 25 for touch devices.
style | Array
CSS styles for the tooltip. The tooltip can also be styled through the CSS class .highcharts-tooltip.
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 xAxis
xAxis
The X axis or category axis. Normally this is the horizontal axis, though if the chart is inverted this is the vertical axis. In case of multiple axes, the xAxis node is an array of configuration objects.

Method used:

jqChart setxAxis( mixed $name, [mixed $mixvalue = ''] )

In case of multiple axes, the xAxis node is an array of configuration objects.
Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

Example:

...
$chart = new jqChart();
$chart->setChartOptions(array("defaultSeriesType"=>"line","marginRight"=>130,"marginBottom"=>25))
->setTitle(array('text'=>'Monthly Average Temperature',"x"=>-20))
->setSubtitle(array("text"=>"Source: WorldClimate.com","x"=>-20))
->setxAxis(array("categories"=>array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))) ...

Option name | Type | Default
allowDecimals | Boolean | true
Whether to allow decimals in this axis' ticks. When counting integers, like persons or hits on a web page, decimals must be avoided in the axis tick labels.
alternateGridColor | Color | null
When using an alternate grid color, a band is painted across the plot area between every other grid line.
categories Array ()
If categories are present for the xAxis, names are used instead of numbers for that axis. Example:
"categories"=> array('Apples', 'Bananas', 'Oranges')
dateTimeLabelFormats | Array
For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default string representations used for each unit. For an overview of the replacement codes, see dateFormat. Default
array(
"second"=> '%H:%M:%S',
"minute"=> '%H:%M',
"hour"=> '%H:%M',
"day"=> '%e. %b',
"week"=> '%e. %b',
"month"=> '%b '%y',
"year"=> '%Y'
)
endOnTick | Boolean | false
Whether to force the axis to end on a tick. Use this option with the maxPadding option to control the axis end.
events | Array
A collection of event handlers.
gridLineColor | Color | "#C0C0C0"
Color of the grid lines extending the ticks across the plot area.
gridLineDashStyle | String | ShortDot
The dash or dot style of the grid lines.
gridLineWidth | Number | 0
The width of the grid lines extending the ticks across the plot area.
id | String | null
An id for the axis. This can be used after render time to get a pointer to the axis object
labels | Array
Configuration object for the axis labels, usually displaying the number for each tick.
lineColor | Color | "#C0D0E0".
The color of the line marking the axis itself.
lineWidth | Number | 1
The width of the line marking the axis itself
linkedTo | Number | null
Index of another axis that this axis is linked to. When an axis is linked to a master axis, it will take the same extremes as the master, but as assigned by min or max or by setExtremes. It can be used to show additional info, or to ease reading the chart by duplicating the scales.
max | Number | null
The maximum value of the axis. If null, the max value is automatically calculated. If the endOnTick option is true, the max value might be rounded up. The actual maximum value is also influenced by chart.alignTicks.
maxPadding | Number | 0.01
Padding of the max value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the highest data value to appear on the edge of the plot area. When the axis' max option is set or a max extreme is set using axis.setExtremes(), the maxPadding will be ignored.
maxZoom | Number
The maximum amount of zoom on this axis. The entire axis will not be allowed to span over a smaller interval than this. For example, for a datetime axis the main unit is milliseconds. If maxZoom is set to 3600000, you can't zoom in more than to one hour.
The default maxZoom for the x axis is five times the smallest interval between any of the data points.
min | Number | null
The minimum value of the axis. If null the min value is automatically calculated. If the startOnTick option is true, the min value might be rounded down.
minorGridLineColor | Color | #E0E0E0
Color of the minor, secondary grid lines.
minorGridLineDashStyle | String | Solid
The dash or dot style of the minor grid lines.
minorTickColor | Color | #A0A0A0.
Color for the minor tick marks.
minorTickInterval | Number | null
Tick interval in scale units for the minor ticks. If "auto", the minor tick interval is calculated as a fifth of the tickInterval. If null, minor ticks are not shown.
minorTickLength | Number | 2
The pixel length of the minor tick marks.
minorTickPosition | String | outside
The position of the minor tick marks relative to the axis line. Can be one of inside and outside.
minorTickWidth | Number | 0
The pixel width of the minor tick mark.
minPadding | Number | 0.01
Padding of the min value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the lowest data value to appear on the edge of the plot area. When the axis' min option is set or a min extreme is set using axis.setExtremes(), the minPadding will be ignored.
offset | Number | 0
The distance in pixels from the plot area to the axis line. A positive offset moves the axis with it's line, labels and ticks away from the plot area. This is typically used when two or more axes are displayed on the same side of the plot.
opposite | Boolean | false
Whether to display the axis on the opposite side of the normal. The normal is on the left side for vertical axes and bottom for horizontal, so the opposite sides will be right and top respectively. This is typically used with dual or multiple axes.
plotBands | Array | null
An array of configuration objects for plot bands colouring parts of the plot area background.
plotLines | Array | null
An array of configuration objects for plot lines marking specific values in the plot area.
reversed | Boolen | false
Whether to reverse the axis so that the highest number is closest to origo. If the chart is inverted, the x axis is reversed by default.
showFirstLabel | Boolean | true
Whether to show the first tick label.
showLastLabel | Boolean | false
Whether to show the last tick label.
startOfWeek | Number | 1
For datetime axes, this decides where to put the tick between weeks. 0 = Sunday, 1 = Monday.
startOnTick | Boolean | false
Whether to force the axis to start on a tick. Use this option with the maxPadding option to control the axis start.
tickColor | Color | #C0D0E0
Color for the main tick marks.
tickInterval | Mixed | null
tickInterval : Mixed null The interval of the tick marks in axis units. When null, the tick interval is computed to approximately follow the tickPixelInterval on linear and datetime axes. On categorized axes, a null tickInterval will default to 1, one category. Note that datetime axes are based on milliseconds, so for example an interval of one day is expressed as 24 * 3600 * 1000.
tickLength | Number | 5
The pixel length of the main tick marks.
tickmarkPlacement | String | between
For categorized axes only. If "on" the tick mark is placed in the center of the category, if "between" the tick mark is placed between categories.
tickPixelInterval | Number
If tickInterval is null this option sets the approximate pixel interval of the tick marks. Not applicable to categorized axis. Defaults to 72 for the Y axis and 100 for the X axis.
tickPosition | String | "outside"
The position of the major tick marks relative to the axis line. Can be one of inside and outside.
tickWidth | Number | 1
The pixel width of the major tick marks.
title | Array
Configuration array for the axis title.
type | String | linear
The type of axis. Can be one of "linear" or "datetime". In a datetime axis, the numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days.
Last Updated: 03/13/11 | © TriRand Ltd., 2011


 events
events
xAxis.events
Event handlers for the axis.

setExtremes : Function

Fires when the minimum and maximum is set for the axis, either by calling the .setExtremes() method or by selecting an area in the chart. The this keyword refers to the axis object itself. One parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. The new user set minimum and maximum values can be found by event.min and event.max.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 labels
labels
The axis labels show the number or category for each tick.

Option name | Type | Default
align | String | "center"
What part of the string the given position is anchored to. Can be one of "left", "center" or "right". In inverted charts, x axis label alignment and y axis alignment are swapped.
enabled | Boolean | true
Enable or disable the axis labels.
formatter | Function
Callback JavaScript function to format the label. The value is given by this.value. Defaults to:
function() {
return this.value;
}
rotation | Number | 0
Rotation of the labels in degrees.
staggerLines | Number | null
Horizontal axes only. The number of lines to spread the labels over to make room or tighter labels.
step | Number | null
To show only every n'th label on the axis, set the step to n. Setting the step to 2 shows every other label.
style | Array
CSS styles for the label.
x | Number | 0
The x position offset of the label relative to the tick position on the axis.
y | Number | 0
The y position offset of the label relative to the tick position on the axis.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 plotBands
plotBands
plotBands options
A colored band stretching across the plot area marking an interval on the axis.

Option name | Type | Default
color | Color/td> | null
The color of the plot band.
events | array |
An object defining mouse events for the plot band. Supported properties are click, mouseover, mouseout, mousemove.
from | Number | null
The start position of the plot band in axis units.
id | String | null
An id used for identifying the plot band in Axis.removePlotBand.
label | Array |
Text labels for the plot bands.
to | Number | null
The end position of the plot band in axis units.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 plotLines
plotLines
A line streching across the plot area, marking a specific value on one of the axes.

Option name | Type | Default
color | Color | null
The color of the plot band.
dashStyle | string | Solid
The dashing or dot style for the plot line
events | array |
An object defining mouse events for the plot band. Supported properties are click, mouseover, mouseout, mousemove.
value | Number | null
The position of the line in axis units
id | String | null
An id used for identifying the plot band in Axis.removePlotBand.
label | Array |
Text labels for the plot bands.
width | Number | null
The width or thickness of the plot line.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 title
title
The axis title, showing next to the axis line.

Option name | Type | Default
align | String | "middle"
Alignment of the title relative to the axis values. Possible values are "low", "middle" or "high".
margin | Number |
The pixel distance between the axis labels or line and the title. Defaults to 0 for horizontal axes, 10 for vertical
rotation | Number |
The rotation of the text in degrees. 0 is horizontal, 270 is vertical reading from bottom to top. Defaults to 0.
style | Array |
CSS styles for the title. When titles are rotated they are rendered using vector graphic techniques and not all styles are applicable. Most noteworthy, a bug in IE8 renders all rotated strings bold and italic.
text | String | null
The actual text of the axis title. It can contain basic HTML text markup like b, i and spans with style.

Last Updated: 01/08/11 | © TriRand Ltd., 2011


 yAxis
yAxis
yAxis

The Y axis or value axis. Normally this is the vertical axis, though if the chart is inverted this is the horiontal axis. In case of multiple axes, the yAxis node is an array of configuration objects.

Method used:

jqChart setyAxis( mixed $name, [mixed $mixvalue = ''] )

Parameters:

  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

Example:

...
$chart = new jqChart();
$chart->setChartOptions(array("defaultSeriesType"=>"line","marginRight"=>130,"marginBottom"=>25))
->setTitle(array('text'=>'Monthly Average Temperature',"x"=>-20))
->setSubtitle(array("text"=>"Source: WorldClimate.com","x"=>-20))
->setxAxis(array("categories"=>array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))) ->setyAxis(array("title"=>array("text"=>"Temperature (°C)")))
...

Option name | Type | Default
allowDecimals | Boolean | true
Whether to allow decimals in this axis' ticks. When counting integers, like persons or hits on a web page, decimals must be avoided in the axis tick labels.
alternateGridColor | Color | null
When using an alternate grid color, a band is painted across the plot area between every other grid line.
categories Array ()
If categories are present for the xAxis, names are used instead of numbers for that axis. Example:
"categories"=> array('Apples', 'Bananas', 'Oranges')
dateTimeLabelFormats | Array
For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default string representations used for each unit. For an overview of the replacement codes, see dateFormat. Default
array(
"second"=> '%H:%M:%S',
"minute"=> '%H:%M',
"hour"=> '%H:%M',
"day"=> '%e. %b',
"week"=> '%e. %b',
"month"=> '%b '%y',
"year"=> '%Y'
)
endOnTick | Boolean | false
Whether to force the axis to end on a tick. Use this option with the maxPadding option to control the axis end.
events | Array
A collection of event handlers.
gridLineColor | Color | "#C0C0C0"
Color of the grid lines extending the ticks across the plot area.
gridLineDashStyle | String | ShortDot
The dash or dot style of the grid lines.
gridLineWidth | Number | 0
The width of the grid lines extending the ticks across the plot area.
id | String | null
An id for the axis. This can be used after render time to get a pointer to the axis object
labels | Array
Configuration object for the axis labels, usually displaying the number for each tick.
lineColor | Color | "#C0D0E0".
The color of the line marking the axis itself.
lineWidth | Number | 1
The width of the line marking the axis itself
linkedTo | Number | null
Index of another axis that this axis is linked to. When an axis is linked to a master axis, it will take the same extremes as the master, but as assigned by min or max or by setExtremes. It can be used to show additional info, or to ease reading the chart by duplicating the scales.
max | Number | null
The maximum value of the axis. If null, the max value is automatically calculated. If the endOnTick option is true, the max value might be rounded up. The actual maximum value is also influenced by chart.alignTicks.
maxPadding | Number | 0.01
Padding of the max value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the highest data value to appear on the edge of the plot area. When the axis' max option is set or a max extreme is set using axis.setExtremes(), the maxPadding will be ignored.
maxZoom | Number
The maximum amount of zoom on this axis. The entire axis will not be allowed to span over a smaller interval than this. For example, for a datetime axis the main unit is milliseconds. If maxZoom is set to 3600000, you can't zoom in more than to one hour.
The default maxZoom for the x axis is five times the smallest interval between any of the data points.
min | Number | null
The minimum value of the axis. If null the min value is automatically calculated. If the startOnTick option is true, the min value might be rounded down.
minorGridLineColor | Color | #E0E0E0
Color of the minor, secondary grid lines.
minorGridLineDashStyle | String | Solid
The dash or dot style of the minor grid lines.
minorTickColor | Color | #A0A0A0.
Color for the minor tick marks.
minorTickInterval | Number | null
Tick interval in scale units for the minor ticks. If "auto", the minor tick interval is calculated as a fifth of the tickInterval. If null, minor ticks are not shown.
minorTickLength | Number | 2
The pixel length of the minor tick marks.
minorTickPosition | String | outside
The position of the minor tick marks relative to the axis line. Can be one of inside and outside.
minorTickWidth | Number | 0
The pixel width of the minor tick mark.
minPadding | Number | 0.01
Padding of the min value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the lowest data value to appear on the edge of the plot area. When the axis' min option is set or a min extreme is set using axis.setExtremes(), the minPadding will be ignored.
offset | Number | 0
The distance in pixels from the plot area to the axis line. A positive offset moves the axis with it's line, labels and ticks away from the plot area. This is typically used when two or more axes are displayed on the same side of the plot.
opposite | Boolean | false
Whether to display the axis on the opposite side of the normal. The normal is on the left side for vertical axes and bottom for horizontal, so the opposite sides will be right and top respectively. This is typically used with dual or multiple axes.
plotBands | Array | null
An array of configuration objects for plot bands colouring parts of the plot area background.
plotLines | Array | null
An array of configuration objects for plot lines marking specific values in the plot area.
reversed | Boolen | false
Whether to reverse the axis so that the highest number is closest to origo. If the chart is inverted, the x axis is reversed by default.
showFirstLabel | Boolean | true
Whether to show the first tick label.
showLastLabel | Boolean | false
Whether to show the last tick label.
startOfWeek | Number | 1
For datetime axes, this decides where to put the tick between weeks. 0 = Sunday, 1 = Monday.
startOnTick | Boolean | false
Whether to force the axis to start on a tick. Use this option with the maxPadding option to control the axis start.
tickColor | Color | #C0D0E0
Color for the main tick marks.
tickInterval | Mixed | null
tickInterval : Mixed null The interval of the tick marks in axis units. When null, the tick interval is computed to approximately follow the tickPixelInterval on linear and datetime axes. On categorized axes, a null tickInterval will default to 1, one category. Note that datetime axes are based on milliseconds, so for example an interval of one day is expressed as 24 * 3600 * 1000.
tickLength | Number | 5
The pixel length of the main tick marks.
tickmarkPlacement | String | between
For categorized axes only. If "on" the tick mark is placed in the center of the category, if "between" the tick mark is placed between categories.
tickPixelInterval | Number
If tickInterval is null this option sets the approximate pixel interval of the tick marks. Not applicable to categorized axis. Defaults to 72 for the Y axis and 100 for the X axis.
tickPosition | String | "outside"
The position of the major tick marks relative to the axis line. Can be one of inside and outside.
tickWidth | Number | 1
The pixel width of the major tick marks.
title | Array
Configuration array for the axis title.
type | String | linear
The type of axis. Can be one of "linear" or "datetime". In a datetime axis, the numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days.
Last Updated: 01/08/11 | © TriRand Ltd., 2011


 Exporting
Exporting

Trirand Inc offers the exporting web service free of charge. If you include the exporting module in your charts, two buttons will appear in the upper right. One button prints the chart, which is done on the client side only. The other button handles exporting. By default, an SVG representation of the chart is sent by POST to http://trirand.com/jqcharts/, where it is converted using Apache'sBatik converter to PDF, PNG or JPEG. SERVER
Last Updated: 03/13/11 | © TriRand Ltd., 2011


 Installing own export server
Installing own export server
Server Setup

If you want to set up this web service on your own server, the index.php file that handles the POST is supplied in the download package inside the php/jqchart-export directory.

  1. Make sure that PHP and Java is installed on your server.
  2. Upload the index.php file from the php/jqchart-export directory in the download package to your server.
  3. In your FTP program, create directory called temp in the same directory as index.php and chmod this new directory to 777 (Linux/Unix servers only).
  4. Download Batik from http://xmlgraphics.apache.org/batik/#download. Find the binary distribution for your version of JRE
  5. Upload batik-rasterizer.jar and the entire lib directory to a location where the index.php is (or some other).
  6. In the options in the top of the index.php file, set the path to batik-rasterier.jar (in case the jar files are copied in another dir).
  7. In your chart options using setExporting method, set the url option to match your PHP file location.
Last Updated: 03/13/11 | © TriRand Ltd., 2011


 Export options
Export options
Options for exporting

Method Used

jqChart setExporting( mixed $name, [mixed $mixvalue = ''] )

Parameters:
  • mixed $name: the option name for the loading. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $mixvalue: a value option in case the name is a string

API Tags:
Return: instance
Access: public

Example:

...
$chart = new jqChart();
$chart->setChartOptions(array("defaultSeriesType"=>"line","marginRight"=>130,"marginBottom"=>25))
// disable exporting
->setExporting(array("enabled"=>false))
...

Option name | Type | Default
buttons | exporting.buttons - object | See below
Configuration options for the buttons associated with the exporting module. See detail
enabled | boolean | true
Whether to enable the exporting module.
filename | string | chart
The filename, without extension, to use for the exported chart.
type | string | image/png
Default MIME type for exporting if chart.exportChart() is called without specifying a type option. Possible values are image/png, image/jpeg, application/pdf and image/svg+xml.
url | string | http://trirand.com/jqcharts/
The URL for the server module converting the SVG string to an image format. By default this points to Trirand Inc free web service.
width | number | 800
The pixel width of charts exported to PNG or JPG.
Last Updated: 03/13/11 | © TriRand Ltd., 2011


 buttons
buttons
Options for the export related buttons, print and export.

Option name | Type | Default
exportButton | object | See link
Options for the export button
printButton | object | See link
Options for the print button
Last Updated: 03/13/11 | © TriRand Ltd., 2011


 exportButton
exportButton
Options for the export button.

Option name | Type | Default
align | string | right
Aligment for the buttons
backgroundColor | color/td> | See below
Background color or gradient for the buttons backgroundColor=>array( linearGradient => array(0, 0, 0, 20), stops=>array( array(0.4, '#F7F7F7'), array(0.6, '#E3E3E3') ) )
borderColor | color | #B0B0B0
The border color of the buttons.
borderRadius | number | 3
The border corner radius of the buttons
borderWidth | number | 1
The border width of the buttons
enabled | boolean | true
Whether to enable buttons
height | number | 20
Pixel height of the buttons
hoverBorderColor | string | #909090
Color of the button border on hover.
hoverSymbolFill | string | #768F3E.
See navigation.buttonOptions => hoverSymbolFill.
hoverSymbolStroke | string | #4572A5.
Stroke (line) color for the symbol within the button on hover
onclick | function (javascript) |
A click handler callback to use on the button directly instead of the popup men
menuItems | array |
A collection of config options for the menu items. Each options object consists of a text option which is a string to show in the menu item, as well as an onclick parameter which is a callback function to run on click. By default, there is one menu item for each of the available export types. Menu items can be customized by defining a new array of items and assigning null to unwanted positions (see override example below).
symbol | string | exportIcon
The symbol for the button. Points to a definition function in the Highcharts.Renderer.symbols collection. The default exportIcon function is part of the exporting module
symbolFill | string | #A8BF77.
See navigation.buttonOptions => symbolFill.
symbolSize | number | 12
The pixel size of the symbol on the button
symbolStroke | string | #A0A0A0
The color of the symbol's stroke or line
symbolStrokeWidth | number | 1
The pixel stroke width of the symbol on the button
symbolX | number | 11.5
The x position of the center of the symbol inside the button.
symbolY | number | 10.5
The y position of the center of the symbol inside the button.
verticalAlign | string | top
The vertical alignment of the buttons. Can be one of "top", "middle" or "bottom".
width | number | 24
The pixel width of the button
y | number | 10
The vertical offset of the button's position relative to its verticalAlign.
x | number | 10
The horizontal positioin of the button relative to the align option.
Last Updated: 03/13/11 | © TriRand Ltd., 2011


 printButton
printButton
Options for the print button.

Option name | Type | Default
align | string | right
Aligment for the buttons
backgroundColor | color/td> | See below
Background color or gradient for the buttons backgroundColor=>array( linearGradient => array(0, 0, 0, 20), stops=>array( array(0.4, '#F7F7F7'), array(0.6, '#E3E3E3') ) )
borderColor | color | #B0B0B0
The border color of the buttons.
borderRadius | number | 3
The border corner radius of the buttons
borderWidth | number | 1
The border width of the buttons
enabled | boolean | true
Whether to enable buttons
height | number | 20
Pixel height of the buttons
hoverBorderColor | string | #909090
Color of the button border on hover.
hoverSymbolFill | string | #768F3E.
See navigation.buttonOptions => hoverSymbolFill.
hoverSymbolStroke | string | #4572A5.
Stroke (line) color for the symbol within the button on hover
onclick | function (javascript) |
A click handler callback to use on the button directly. By default this onclick calls chart.print(), but it can be overridden to do other actions.
symbol | string | printIcon
The symbol for the button. Points to a definition function in the Highcharts.Renderer.symbols collection. The default print function is part of the exporting module.
symbolFill | string | #A8BF77.
See navigation.buttonOptions => symbolFill.
symbolSize | number | 12
The pixel size of the symbol on the button
symbolStroke | string | #A0A0A0
The color of the symbol's stroke or line
symbolStrokeWidth | number | 1
The pixel stroke width of the symbol on the button
symbolX | number | 11.5
The x position of the center of the symbol inside the button.
symbolY | number | 10.5
The y position of the center of the symbol inside the button.
verticalAlign | string | top
The vertical alignment of the buttons. Can be one of "top", "middle" or "bottom".
width | number | 24
The pixel width of the button
y | number | 10
The vertical offset of the button's position relative to its verticalAlign.
x | number | 10
The horizontal positioin of the button relative to the align option.
Last Updated: 03/13/11 | © TriRand Ltd., 2011


 Java Script Reference
Java Script Reference
The Chart object

The chart object is the JavaScript object representing a single chart in the web page. The pointer to your chart object is returned when a chart is created using the Highcharts.Chart() constructor:

var chart = new Highcharts.Chart(options);

The reference to the variable can be set in PHP renderChart method - see parameter $chart

Methods

addSeries (Object options, [Boolean redraw], [Mixed animation]) : Series

Add a series to the chart after render time. Note that this method should never be used when adding data synchronously at chart render time, as it adds expense to the calculations and rendering. When adding data at the same time as the chart is initiated, add the series as a configuration option instead.

Parameters

  • options: Object
    The series options, as documented under plotOptions.series and under the plotOptions for each series type.
  • redraw: Boolean
    Defaults to true. Whether to redraw the chart after the series is added. See the redraw() method below.
  • animation: Mixed
    Defaults to true. When true, the series' updating will be animated with default animation options. The animation can also be a configuration object with properties duration and easing.

Returns

The series added, if successful.

destroy ()

Removes the chart and purges memory. This method should be called before writing a new chart into the same container. It is called internally on window unload to prevent leaks.

exportChart (Object options, Object chartOptions) : null

Submit an SVG version of the chart to a server along with some parameters for conversion.

Parameters

  • options: Object
    Exporting options. Out of the exporting options, the following options can be given as parameters to the exportChart method. All options default to the values given in the exporting config optins. filename: the filename for the export without extension, url: the URL for the server module to do the conversion, width: the width of the PNG or JPEG image generated on the server, type: the MIME type of the converted image.
  • chartOptions: Object
    Additional chart options for the exported chart. For example a different background color can be added here.

get (String id) : Axis|Series|Point

Get an axis, series or point by its id as given in the configuration options.

Parameters

  • id: String
    The id of the axis, series or point to get.

Returns
The first Axis, Series or Point with a matching id if found, null if not.

getSelectedPoints () : Array<Point>

Returns an array of all currently selected points in the chart. Points can be selected either programmatically by the point.select() method or by clicking.

Returns

An array of the selected points.

getSelectedPoints () : Array<Point>

Returns an array of all currently selected points in the chart. Points can be selected either programmatically by the point.select() method or by clicking.

Returns

An array of the selected points.

getSVG (Object additionalOptions) :

Get an SVG string representing the chart.

Parameters

  • additionalOptions: Object
    Chart options to add to the exported chart in addition to the options given for the original chart. For example if series.lineWidth should be greater in the exported chart than in the original, or the chart should have a different background color, this is added here.

hideLoading () :

Hide the loading screen. Options for the loading screen are defined at options.loading.

print () : null

Exporting module required. Clears away other elements in the page and prints the chart as it is displayed. By default, when the exporting module is enabled, a button at the upper left calls this method.

redraw () : null

Redraw the chart after changes have been done to the data or axis extremes. All methods for updating axes, series or points have a parameter for redrawing the chart. This is true by default. But in many cases you want to do more than one operation on the chart before redrawing, for example add a number of points. In those cases it is a waste of resources to redraw the chart for each new point added. So you add the points and call chart.redraw() after.

The chart.redraw() method only redraws those parts of the chart that are actually changed. If the data of a series is changed and it doesn't affect the axes, only the series itself is redrawn. If the new data requires the axis extremes to be altered, the axis and all other series depending on it are redrawn.

setSize (Number width, Number height, [Mixed animation]) :

Resize the chart to a given width and height.

Parameters

  • width: Number
    The new pixel width of the chart.
  • height: Number
    The new pixel height of the chart.
  • animation: Mixed
    Defaults to true. When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing.

setTitle (Object title, object subtitle) :

Set a new title or subtitle for the chart

Parameters

  • title: Object
    A configuration object for the new title as defined at #title.
  • subtitle: Object
    A configuration object for the new subtitle as defined at #subtitle.

showLoading (String str) : null

Dim the chart's plot area and show a loading label text. Options for the loading screen are defined at options.loading. A custom text can be given as a parameter for loadind
Last Updated: 03/13/11 | © TriRand Ltd., 2011


 jqTreeGrid PHP
jqTreeGrid PHP

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Introduction
Introduction

jqTreeGrid for PHP is a server-side component built on top of open and widely used standards such as jQuery, jQuery UI, ThemeRoller, etc..

Some of the major features include:

  • Suport of the both most used tree models - adjacency and nested
  • Blazing speed - only the minimal data required is sent from server to client using JSON or XML
  • Supports the most popular SQL Databases like PostgreSQL, MySQL, Microsoft SQL Server.
  • Minimal HTML size - jqTreeGrid uses client-side rendering, meaning no hundreds of KBs of nested <tables> in HTML.
  • jQuery based client-side - familiar and powerful client-side API based on jQuery.
  • Feature complete - every feature you might need, including adding/editing of records, sorting seraching etc
  • ThemeRoller support - theming is based on ThemeRoller. A set of 25 themes by professional designers is available, including great free theme authoring tool.
  • many more.
Last Updated: 03/19/11 | © TriRand Ltd., 2011


 Installation and System Requierements
Installation and System Requierements

Last Updated: 03/22/11 | © TriRand Ltd., 2011


 System requirements
System requirements

Please refer to this topic
Last Updated: 03/19/11 | © TriRand Ltd., 2011


 Quick Installation
Quick Installation
Download and unzip the contents of the archive to any convenient location. The package contains the following folders:

- [php] - Contains the jqTreeGrid and jqGrid PHP classes and the driver files for the appropriate database.
- [themes] - Contains the themes shipped with the product. Since jqTreeGrid supports jQuery UI Themeroller, any theme compatible with jQuery UI ThemeRoller will work for jqTreeGrid as well. Therefore, the package contains just one theme ("Redmond"). You can download any additional themes directly from jQuery UI's ThemeRoller site available here:

http://jqueryui.com/themeroller/

In addition to the "Redmond" theme, there is one more file in the [themes] folder - ui.jqgrid.css. This is the one and only Css file jqGrid needs. Just add it after you add the reference to the "Redmond" theme in your PHP/HTML file containing jqGrid for PHP.

<link rel="stylesheet" type="text/css" href="themes/redmond/jquery-ui-1.7.2.custom.css" />
<link rel="stylesheet" type="text/css" href="themes/ui.jqtreegrid.css" />

- [js] - The javascript files of jqTreeGrid (and the needed libraries). You need to include them in your PHP page.

The first file is "jquery.js" - this is the official jQuery library on which jqGrid is built upon.
The second file you need is the i18n (localization) javascript file. Depending on the language you need, just pick one from the "js/i18n" folder.
The last one is the jqTreeGrid javascript code itself, located in "jquery.jqTreeGrid.min.js"

The final result you will have in an PHP page containing jqGrid would be something similar to that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqGrid </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqtreegrid.css" />

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqTreeGrid.min.js" type="text/javascript"></script>

</head>
<body>
......
<?php include "myfirsttreegrid.php";?>
.......
</body>
</html>

Save the file as treegrid.php or any desired name in the root directory.

In the root directory you will find a file named jq-config.php. Open the file and enter the appropriate information for the connection to the database. Save the file and then create a file myfirsttreegrid.php with the following conten. Note that this example will use the database and tables provided with the demo.

<?php
require_once 'jq-config.php';
// include the driver class
require_once ABSPATH."php/jqGridPdo.php";
// include the jqTreeGrid Class
// NOTE that jqGrid.php file should be available in same directory

require_once ABSPATH."php/jqTreeGrid.php";

// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");
// Create the jqTreeGrid instance
$tree = new jqTreeGrid($conn);

$tree->SelectCommand = "SELECT * FROM adj_table";

// set the table and primary key
$tree->table = 'adj_table';
$tree->setPrimaryKeyId('emp_id');
// set tree model and table configuration
$tree->setTreeModel('adjacency');
$tree->setTableConfig(array('id'=>'emp_id', 'parent'=>'boss_id'));

// autoloading is disabled
$tree->autoLoadNodes = false;
// collapse all nodes (default)
$tree->expandAll = true;
// show any error (if any ) from server
$tree->showError = true;

$tree->setColModel();

$tree->setUrl('treegrid.php');
$tree->dataType = 'json';
// Some nice setting
$tree->setColProperty('name',array("label"=>"Employee", "width"=>170));
$tree->setColProperty('salary',array("label"=>"Salary", "align"=>"right","width"=>90));

// hide the not needed fields
$tree->setColProperty('emp_id',array("hidden"=>true));
$tree->setColProperty('boss_id',array("hidden"=>true));

// and finaly set the expand column and height to auto
$tree->setGridOptions(array(
// set which column should act as expanded one
   "ExpandColumn"=>"name",
   "height"=>'auto',
   "sortname"=>"emp_id",
   // allow automatic scrolling of the rows
   "scrollrows"=>true
   ));
// enable key navigation
$tree->callGridMethod('#tree', 'bindKeys');

$tree->navigator = true;
$tree->setNavOptions('navigator', array("add"=>true,"edit"=>true, "del"=>true, "search"=>false, "excel"=>false));
$tree->renderTree('#tree', '#pager', true,null, null, true, true);
?>

Run the file tree.php from your web browser. All subsequent requests the grid needs will be forwarded back to the "myfirsttreegrid.php" file (using the $grid->setUrl(...) method) and the grid will automatically handle the requests and provide the needed response - no need for custom coding.

Last Updated: 03/22/11 | © TriRand Ltd., 2011


 Connection and database drivers
Connection and database drivers
If you take a look at our "Quick installation" topic, you will see that jqTreeGrid for PHP does not create its own connection to the database, but uses a connection that already exists. This is a very flexible approach in complex applications where the connection to the database had already been created. Typically in our examples we will create the connection using PDO rules, but this is not neccessary and you can reuse your own connection.

PDO Driver

When a PDO driver is used (for MySQL or PostgreSQL) a file named jqGridPdo.php should be included in addition to the main jqTreeGrid.php file. The file is available in the [php] folder of the jqSuite for PHP download package. Please note, that in this case you do not need to specify explicitly which database should be used - MySQL or PostgreSQL. The script will detect this automatically from the connection. Here is an example:

<?php
require_once "php/jqTreeGrid.php";
// include the PDO driver class - needed for MySQL and Postgre SQL
require_once "php/jqGridPdo.php";
...
?>

Microsoft SQL Driver

When Microsoft SQL Server is used, a file named jqGridSqlsrv.php should be included in addition to the main jqTreeGrid.php file. The file is available in the [php] folder of the jqSuite for PHP download package.

Note: In order to work properly with fields of type "Date", when the connection is created you should also set a property - "ReturnDatesAsStrings"=>true in the connection string. The reason for this is that the driver by default handles dates as PHP date object.

Here is an example:

<?php
// Example connection
$connectionInfo = array("UID" => 'user', "PWD" => 'password',"Database"=>"test", "ReturnDatesAsStrings" => true);
$serverName = "localhost\SQLEXPRESS";
$conn = sqlsrv_connect( $serverName, $connectionInfo);
...
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the SQL Server driver class
require_once "php/jqGridSqlsrv.php";
...
?>

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Localization
Localization

Localization in jqTreeGrid is the same as in jqGrid. For this purpose please look here:

List of available language packs
Using predefined language packs
Modifying/Creating a new language pack
Programmatically overriding language defaults
Right-To-Left languages

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Theming
Theming

Theming in jqTreeGrid is exactley as in jqGrid. For this purpose please look at the following topics
Last Updated: 03/20/11 | © TriRand Ltd., 2011


 TreeGrid class guide
TreeGrid class guide

jqTreeGrid and jqGrid for PHP are designed in a way that allows it to be integrated in any framework or architecture, without compromising any of its features. In order to achieve this, we have separated the component into four classes - each of them provides functionality that is convenient in different contexts.

In addition to that, each class inherits the properties of its base class, so that the base features will be available to you at any time.

Below is the list of classes:

jqGrid Class
jqGridEdit Class
jqGridRender Class

Here is the hierarchy of the classes

jqGrid
   |
   --jqGridEdit
      |
      --jqGridRender
         |
          --jqTreeGrid

jqGrid is the base class and provides some of the functionality, jqGridEdit extends on that and provides editing capabilities, jqGridRender extends jqGridEdit and provides all grid features plus automatic generation of Javascript and HTML placeholders required by the grid. jqTreeGrid extends the jqGridRender so that it allow to build edit and query different tree models. In this respect, jqTreeGrid is the most advanced class and requires the minimal amount of coding, however in certain situations you may find jqGrid more convenient to use based on the context.

Last Updated: 03/21/11 | © TriRand Ltd., 2011


 jqTreeGrid Class
jqTreeGrid Class

Last Updated: 03/21/11 | © TriRand Ltd., 2011


 Variables
Variables
All the variables that ara available at jqGrid, jqEdit and jqRender classes can be used within TreeGrid class

Type | Names | Description | Default | Access
boolean | $autoLoadNodes | If set to false all data is requested an is available at client side | true | public
boolean | $expandAll | If set to true all nodes are expanded when the data is loaded at client side. | false | public

Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Methods
Methods
All the methods that ara available at jqGrid, jqEdit and jqRender classes can be used within TreeGrid class

boolean deleteTreeNode( array $data )

Delete the data into the database according the table element and tree grid model. Use this method instead of delete method in edit class

A primaryKey should be set. If the key is not set It can be obtained from jqGridDB::getPrimaryKey Return true on success, false when the operation is not succefull
Parameters:

  • array $data: associative array which key values correspond to the names in the delete command

API Tags:
Access: public

editTree( [ $summary = null], [ $params = null], [string $oper = false], [ $echo = true] )

Perform the all CRUD operations depending on the oper param send from the grid, the table element and the treegrid model If the primaryKey is not set we try to obtain it using jqGridDB::getPrimaryKey If the primary key is not set or can not be obtained the operation is aborted.

Also the method call the queryTree to perform the tree ouput
Parameters:

  • array $summary: - set which columns should be sumarized in order to be displayed to the grid By default this parameter uses SQL SUM function: array("colmodelname"=>"sqlname"); It can be set to use the other one this way array("colmodelname"=>array("sqlname"=>"AVG")); By default the first field correspond to the name of colModel the second to the database name
  • array $params: additional parameters that can be passed to the query
  • string $oper: if set the requested oper operation is performed without to check the parameter sended from the grid.
  • boolean $echo: should the result be echoed or returned

API Tags:
Access: public

array getTableConfig( )

Return the curent configuration for the model used

API Tags:
Access: public

string getTreeModel( )

Returns the currently used tree model

API Tags:
Access: public

boolean insertTreeNode( array $data )

Insert the data array into the database according to the table element and tree model.

A primaryKey should be set. If the key is not set It can be obtained from jqGridDB::getPrimaryKey. The table config for the tree should be set.
Parameters:

  • array $data: associative array which key values correspond to the names in the table.

API Tags:
See: setTableConfig Return true on succes, false otherwiese.
Access: public

mixed queryTree( [ $summary = null], [ $params = null], [boolen $echo = true] )

Return the result of the query to jqTreeGrid. Currently does not support searching.
Parameters:

  • array $summary: - set which columns should be sumarized in order to be displayed to the grid By default this parameter uses SQL SUM function: array("colmodelname"=>"sqlname"); It can be set to use the other one this way array("colmodelname"=>array("sqlname"=>"AVG")); By default the first field correspond to the name of colModel the second to the database name
  • array $params: - parameter values passed to the sql
  • boolen $echo: if set to false return the records as object, otherwiese json encoded or xml string depending on the dataType variable

API Tags:
Access: public

mixed. renderTree( [string $tblelement = ''], [string $pager = ''], [boolean $script = true], [ $summary = null], [ $params = null], [boolean $createtbl = false], [boolean $createpg = false], [boolean $echo = true] )

Main method which do allmost everthing for the tree grid.

Construct the tree grid, perform CRUD operations, perform Query set a jqGrid method, and javascript code.
Parameters:

  • string $tblelement: the id of the table element to costrict the grid
  • string $pager: the id for the pager element
  • boolean $script: if set to true add a script tag before constructin the grid.
  • array $summary: - set which columns should be sumarized in order to be displayed to the grid By default this parameter uses SQL SUM function: array("colmodelname"=>"sqlname"); It can be set to use other one this way : array("colmodelname"=>array("sqlname"=>"AVG")); By default the first field correspond to the name of colModel the second to the database name
  • array $params: parameters passed to the query
  • boolean $createtbl: if set to true the table element is created automatically from this method. Default is false
  • boolean $createpg: if set to true the pager element is created automatically from this script. Default false.
  • boolean $echo: if set to false the function return the string representing the grid

API Tags:
Access: public

setTableConfig( array $aconfig )

Set the configuration fields for the model used. For the adjacency model a 'id' and 'parent' should be set For the nested model 'id', 'left', 'right' and 'level' should be set Optional fields for all models : expanded, icon, leaf, loaded
Parameters:

  • array $aconfig:

API Tags:
Access: public

setTreeModel( [string $model = 'nested'] )

Set the tree mode used. Can be adjacency or nested. Deafault is nested
Parameters:

  • string $model:

API Tags:
Access: public

boolean updateTreeNode( array $data )

Update the data into the database according the table element A primaryKey should be set. If the key is not set It can be obtained from jqGridDB::getPrimaryKey.Return true on success, false when the operation is not succefull

Parameters:

  • array $data: associative array which key values correspond to the names in the table

API Tags:
Access: public
Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Options
Options
For the TreeGrid options a two methods can be used. These methods are from the jqGridRender Class

getGridOption($key) to obtain the desired option
where $key is a name listed in the table below
and
setGridOption(array $aoptions) to set a new option(s)
where
$aoptions is array where multiple optins can be set.
The method can be called several times in order to set or overwrite existing option(s).

Example: If we want to change the width and the height of the grid we can write the code like this

<?php
...
// Create the jqTreeGrid instance
$tree = new jqTreeGrid($conn);
...
$tree->setGridOptions(array("width"=>500,"height"=>350));
...
$tree->renderTree(...);
?>

The same code is equivalent

<?php
...
// Create the jqTreeGrid instance
$tree = new jqTreeGrid($conn);
...
$tree->setGridOptions(array("width"=>500));
$tree->setGridOptions(array("height"=>350));
...
$tree->renderTree(...);
?>

Again with Grid Options available in the grid we can use the following one

Type | Name | Description | Default
boolean | ExpandColClick | boolean when true, the tree is expanded and/or collapsed when we click on the text of the expanded column, not only on the image |
string | ExpandColumn | Indicates which column (name from colModel) should be used to expand the tree grid. If not set the first one is used. | null
string | treedatatype | Determines the initial datatype (see datatype option). Usually this should not be changed. During the reading process this option is equal to the datatype option | null
bollean | treeGrid | Enables tree grid. Usualy this option shuld not be set. It is set automatically when the new instance of a class is created. | false
string | treeGridModel | Deteremines the method used for the treeGrid. Can be nested or adjacency. Change this option with setTreeModel method. | nested
string | treeGridModel | Deteremines the method used for the treeGrid. Can be nested or adjacency. Change this option with setTreeModel method. | nested
array | treeIcons | This array set the icons used in the tree. The icons should be a valid icons from UI theme roller images. The default values are: array("plus"=>'ui-icon-triangle-1-e',"minus"=>'ui-icon-triangle-1-s',"leaf"=>'ui-icon-radio-off'} | nested
array | treeReader | extends the colModel defined in the basic grid. The fields described here are added to end of the colModel array. This means that the data returned from the server should have values for these fields. Usually this option should not be set. It is set automatically from the class. |
integer | tree_root_level | Determines the level where the root element begins when treeGrid is enabled | 0

Last Updated: 03/21/11 | © TriRand Ltd., 2011


 Java Script Events
Java Script Events
Last Updated: 03/20/11 | © TriRand Ltd., 2011


 Java Script Methods
Java Script Methods
Below is the list of Java Script jqTreGrid methods. These methods can be either called with callGridMethod or setJSCode.
It is recommended to use these methods with setJSCode, since everey method requiere to have parameter record.

In the methods below, record means the current record, which can be obtained via the getLocalRow method like this:

var record = jQuery("#grid_id").jqGrid('getLocalRow',rowid);

where rowid is the id of the row andf grid_id is the id of the grid

Method | Parameters | Returns | Description
collapseNode | record | grid object | Collapse the node at specified record
collapseRow | record | grid object | Collapse the current row
delTreeNode | rowid | boolean | Where rowid is the id of the row. Deletes the specified node and all child nodes of that node. Does not delete the node in the server table
expandNode | record | grid object | Expand the node at specified record
expandRow | record | grid object | Expand the current row
getNodeAncestors | record | array | Returns array of the ancestors of the specified record
getNodeDepth | record | number | Returns the depth of the specified record
getNodeParent | record | array | Returns the parent node of the specified record
getNodeChildren | record | array | Returns array of child nodes of the specified record; returns empty array if none
getRootNodes |  | array | Returns an array of the current root nodes.
isNodeLoaded | record | boolean | Returns true if the node is already loaded
isVisibleNode | record | boolean | Returns true or false if the node is visible or not
setTreeRow | rowid, data | boolean | Set a data in specifird rowid. Does not set it at server
SortTree | name, direction | grid object | Direction is 'asc' (meaning ascending) or 'desc' (meaning descending); sorts the tree with the set name (sortname is from grid colModel option)
Last Updated: 03/21/11 | © TriRand Ltd., 2011


 TreeGrid models
TreeGrid models

As mentioted into the presentastion jqTreeGrid component can support two type of tree model - nested and adjacency.
By default the component uses a nested set model.

In order to work the component in a desired manner it is recommended that the tables that hold the tree data should contain certain fields.
All of these fields and the type of the model should be set with setTableConfig and and setTreeModel php methods.

By example if we use the nested set model and our system fields in the tree table are named lft, rgt and level then the appropriate setting can look like this

<?php
....
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);

// Create the jqTreeGrid instance
$tree = new jqTreeGrid($conn);
.....

// set the table and primary key
$tree->table = 'nested_category';
$tree->setPrimaryKeyId('category_id');
// set model
$tree->setTreeModel('nested');
//set the table configuration
$tree->setTableConfig(array('id'=>'category_id', 'left'=>'lft', 'right'=>'rgt'));

...

?>

Having this in mind bellow we will discuss the both models.

Last Updated: 03/21/11 | © TriRand Ltd., 2011


 Nested set model
Nested set model
Nested Set is a solution for storing hierarchical data that provides very fast read access. However, updating nested set trees is more costly. Therefore this solution is best suited for hierarchies that are much more frequently read than written to. And because of the nature of the web, this is the case for most web applications.
For more detailed information on the Nested Set, read here:
http://www.sitepoint.com/article/hierarchical-data-database/2
http://dev.mysql.com/tech-resources/articles/hierarchical-data.html

In order to work the nested set model in jqTreeGrid is requiered to have three field - left , right and level.

$tableconfigarray = array("left"=>"lft", "right"=>"rgt", "level"=>"level", "id"=>"id")

Another requirments is to have uniquie id in the table and in most cases this id is requiered to be serial (autoincremet) integer field.
For this purpose the id field should be set to. It is not neccesary to set this field if it is set as primary and serial in the tree grid definitions.

Two methods are connected with these settings

$tree->setTreeMode('nested') - sets the tree model

and

$tree->setTableConfig(array(....)); set the system fields for the tree.

By example if the table that holds the tree data is called nested_category and the id primary autoincremented field is called account_id and the other system fields have the default names, the following example prepares correct the tree grid:

<?php
...
// set the table and primary key
$tree->table = 'nested_category';
$tree->setPrimaryKeyId('category_id');
// set model
$tree->setTreeModel('nested');
//set the table configuration
$tree->setTableConfig(array('id'=>'category_id', 'left'=>'lft', 'right'=>'rgt', 'level'=>'level'));

...
?>

Last Updated: 03/21/11 | © TriRand Ltd., 2011


 Adjacency model
Adjacency model
This is a simple implementation of the traditional Adjacency List Model for storing trees in relational databases.

In the adjacency list model, every node will have a "parent" key, that will be NULL for root nodes.

The adjacency list model has the advantage of fast writes at the cost of slow reads. If you read more than you write, use nested set model instead

Like the nested set model the table should have a uniquie id which is serial (autoincremented)

if our tree salary table has the following structure

CREATE TABLE adj_table (
  emp_id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(30) NOT NULL,
  salary decimal(10,2) DEFAULT '0.00',
  boss_id int(11) DEFAULT NULL,
  PRIMARY KEY (emp_id)
);

then the appropriate settings should be:

<?php
...
// set the table and primary key
$tree->table = 'adj_table';
$tree->setPrimaryKeyId('emp_id');
// set tree model and table configuration
$tree->setTreeModel('adjacency');
$tree->setTableConfig(array('id'=>'emp_id', 'parent'=>'boss_id'));

...
?>
Last Updated: 03/21/11 | © TriRand Ltd., 2011


 jqScheduler PHP
jqScheduler PHP

Last Updated: 10/14/11 | © TriRand Ltd., 2011


 Introduction
Introduction

jqScheduler for PHP is a event calendar component built on top of open and widely used standards such as jQuery, jQuery UI, ThemeRoller, etc..
Some of the major features include:

  • Multiple Resources View to display several calendars for different resources
  • Blazing speed - only the minimal data required is sent from server to client
  • Template View for simple and effective visualization of events assigned to different resources
  • Data export to iCal format
  • Printing to PDF format.
  • Drag and drop events
  • jQuery based client-side - familiar and powerful client-side API based on jQuery.
  • Easy search interface in order to find the needed information immediatley
  • ThemeRoller support - theming is based on ThemeRoller. A set of 25 themes by professional designers is available, including great free theme authoring tool.
  • many more.
Last Updated: 10/14/11 | © TriRand Ltd., 2011


 Installation and system requierments
Installation and system requierments

Last Updated: 10/14/11 | © TriRand Ltd., 2011


 System requierments
System requierments

Browser Support

jqScheduler for PHP supports all major browsers:

  • Internet Explorer 6.x+
  • FireFox 3.x+
  • Safari 2.x+
  • Google Chrome 2.x+
  • Opera 9.5+

PHP

jqScheduler is designed to work with PHP versions 5.1+.
It can work as separate application and easy integration with any other application. Requiere a minimal setup. See Quick Install.

Databases

Currently jqScheduler for PHP supports the following databases:

  • MySQL 5.x+ (PDO)
  • PostgreSQL versions 7.x+ (PDO)
  • SQLite versions 3.x+ (PDO)
  • Microsoft SQL Server 2005+
  • Oracle 8+
  • MySQL (through Mysqli)
  • DB2 (IBM DB2 functions)

MySQL, PostgreSQL and SQLite databases are supported through PHP PDO (PHP Data Objects), so depending on your PHP setup you may need to install it before using jqScheduler for PHP. PDO is by default installed in PHP 5.1+ distributions. PDO is a core PHP technology, created and supported by the core PHP team.

To ensure that PDO is installed in your production enviornment, please run the following PHP script on your development/production machine:

<?php
phpinfo();
?>

Save the file and run it on your web server. The following should appear if you want to use MySQL and have PDO installed:

The following should appear if you want to use PostgreSQL and have PDO installed:

The following should appear if you want to use SQLite and have PDO installed:

Microsoft SQL Server is supported through the PHP driver provided by Microsoft. Please follow the installation instructions provided by Microsoft in the PHP driver documentation. After the driver is installed, the following should appear if you run the "phpinfo()" function:

Oracle is supported through the PHP OCI8 driver. Please follow the installation instructions provided in the same link. After the driver is installed, the following should appear if you run the "phpinfo()" function:

Additinally MySQL database is supported through Mysqli driver. Follow the installation instuction provided from the same link. After the installation is done the following should appear if you run the "phpinfo()" function:

Additinally DB2 database is supported through DB2 driver. Follow the installation instuction provided from the same link. After the installation is done the following should appear if you run the "phpinfo()" function:

Last Updated: 10/14/11 | © TriRand Ltd., 2011


 Quick Install
Quick Install
Download and unzip the contents of the archive to any convenient location. The package contains the following folders:

- [php] - Contains the jqScheduler and the driver files for the appropriate database.
- [themes] - Contains the themes shipped with the product. Since jqScheduler supports jQuery UI Themeroller, any theme compatible with jQuery UI ThemeRoller will work for jqScheduler as well. Therefore, the package contains just one theme ("Redmond"). You can download any additional themes directly from jQuery UI's ThemeRoller site available here:

http://jqueryui.com/themeroller/

In addition to the "Redmond" theme, there is one more file in the [themes] folder - ui.jqsheduler.css. This is the one and only Css file jqSceduler needs. Just add it after you add the reference to the "Redmond" theme in your PHP/HTML file containing jqGrid for PHP.

<link rel="stylesheet" type="text/css" href="themes/redmond/jquery-ui-custom.css" />
<link rel="stylesheet" type="text/css" href="themes/ui.jqsheduler.css" />

- [js] - The javascript files of jqScheduler (and the needed libraries). You need to include them in your PHP page.

The first file is "jquery.js" - this is the official jQuery library on which jqGrid is built upon.
The next one is the jqScheduler javascript code itself, located in "jquery.jqScheduler.min.js"

Before to create any files to run the jqScheduler, we need to create the database table that holds the information for the Scheduler.

The default table name is events and you should create it in your database where you plan to use the jqScheduler. The table definition for MqSql database is in directory php/backend/db_mysql.sql.
If the table can not be named events (or you have already such one) rename it in you way and then after creating the instance do .
$eventcal->table ="your_new_table_name";

See below

After this is done the final result you will have in an PHP page containing jqSceduler would be something similar to that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jqSheduler </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqscheduler.css" />

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.jqScheduler.min.js" type="text/javascript"></script>

</head>
<body>
......
<?php include "eventcal.php";?>
.......
</body>
</html>

Save the file as jqscheduler.php or any desired name in the root directory.

In the root directory you will find a file named jq-config.php. Open the file and enter the appropriate information for the connection to the database. Save the file and then create a file eventcal.php with the following content. Note that this example will use the database and tables provided with the demo.

<?php
require_once "php/jqUtils.php";
require_once "php/jqScheduler.php";
require_once "php/jqGridPdo.php";
require_once 'jq-config.php';
ini_set("display_errors",1);
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
$conn->query("SET NAMES utf8");
$eventcal = new jqScheduler($conn);
$eventcal->table ="events";
$eventcal->setLocale('en_GB');
$eventcal->setUrl('eventcal.php');
$eventcal->setUser(1);
$eventcal->setUserNames(array('1'=>"Calender User 1",'2'=>"Calendar user 2") );
$eventcal->render();
?>

Run the file jqscheduler.php from your web browser.

Last Updated: 05/31/11 | © TriRand Ltd., 2011


 List of available language packs
List of available language packs

List of predefined packs

A complete list of available predefined language packs is in the /php/localization folder with their filename and the language they represent.

File name | Language
bg_BG.inc | Bulgarian
en_EN.inc | English

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Using predefined laguage packs
Using predefined laguage packs

Basics

jqScheduler for PHP comes with a lot of predefined language packs. They are located in the installation package, in the /php/localization folder. Language packs are in the form of php files, containing definitions for all strings in the schedule that can be localized - this includes messages, captions, search/add/delete dialog labels, etc.

In order to use a particular language pack, you need to use the PHP method setLocale($lang_pack) wher the $lang_pack is 5 letter code where the first two letter represent the language and the lastr two letter represent the Country. The example below set the Bulgarian language pack.

...
...
$eventcal = new jqScheduler($conn);
$eventcal->setLocale('bg_BG');
...

By defaulr a English language pack is used. In this case it is not needed to use setLocale method.

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Modifying/Creating a new language pack
Modifying/Creating a new language pack

Structure of a language pack

A language pack is essentially a PHP file with constants for specific strings in the grid that can be localized. In addition to that, there are formats (date format, etc) that can be predefined to match the locale of the specific country. Every language file is defined as a class which contain arrays of the translated strings.

In order to modify a language pack, just open the respective php file and edit it with your favourite text editor. For example, let's say we want to modify the English language pack. Opening the /php/localization/en_EN.inc file in a text editor brings are something along the lines of (this is just a part of the file):

<?php
class jqEventLocalization {

//fullcalender translations
// these locale setting use javascript convensions for date forrmating
/* * !!!!!!!!! NOTE dateFormat in fullcalender differ from datepicker
* Configure both in appropriate way
*/
public $dateFormat = "dd/MM/yyyy";
public $fullcalendar = array(
   'isRTL'=> false,
   'firstDay' => 1,
   'monthNames'=>array('January','February','March','April','May','June','July','August','September','October','November','December'),
   'monthNamesShort'=>array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),
   'dayNames'=> array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'),
   'dayNamesShort'=>array('Sun','Mon','Tue','Wed','Thu','Fri','Sat'),
   'buttonText'=>array (
      'today' =>'today',
      'month' =>'month',
      'week' =>'week',
      'day'=> 'day',
      'search'=>'search'
   ),
   'allDayText'=> 'all-day',
   'axisFormat'=> 'h(:mm)tt',
   'timeFormat'=>array(
   'agenda'=> 'h:mm{ - h:mm}'
   ));

// Time picker
// slotMinutes: 30 - this is get from calender options
// the corresponding options is timeIntervalpublic
$timepicker = array(
   "minutes"=>"mins",
   "onehour"=>"1 hr",
   "hours"=>"hrs"
);
...
?>

Just modify any of the strings/rules you wish. The naming of the string is self-explanatory - for example in order to modify the all-day text, just modify the 'allDayText variable in the defaults array.

Just modify anything you wish. Finally, save the file with another name, for example, "en_EN_custom.inc" and set it in your page instead of the default English language, e.g.

...
$eventcal = new jqScheduler($conn);
$eventcal->setLocale('en_EN_custom');
...

  Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Dynamically overriding language defaults
Dynamically overriding language defaults
In some cases, you may want to keep the majority of the locale settings in your language packs, but still change some of them programmatically based on certain server-side conditions.

The way this works is the following - if a specific value for a property is not specified in PHP code, the default from the language pack will be used. If it is specified in code however, it will override the language pack default.

Not all texts can be set dynamically.

A example for this is customizing the 'all-day' text. Using setOptions method for the allDayText variable we can overwrite the text.

<?php
...
$eventcal = new jqScheduler($conn);
...
$eventcal->setOptions(array(
'allDayText'=>'All Day'
));
...
?>
Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Theming
Theming

Last Updated: 06/07/11 | © TriRand Ltd., 2011


 Basics
Basics
Theming is based on the highly popular and open ThemeRoller, which is the standard for developing jQuery UI widgets. This means that you have access to 25 ready-to-use themes created by professional designers, plus a unique free web-based tool allowing you to create your own theme. You can also customize a theme starting from an existing one.

The list of currently available themes is:

  • base
  • black-tie
  • blitzer
  • cupertino (Apple-like UI)
  • dark-hive
  • dot-luv
  • eggplant
  • excite-bike
  • flick
  • hot-sneks
  • humanity
  • le-frog
  • mint-choc
  • overcast
  • pepper-grinder
  • redmond (Windows-like UI)
  • smoothness
  • south-street
  • start
  • sunny
  • swanky-purse
  • trontastic
  • ui-darkness
  • ui-lightness
  • vader

Here is a preview of some of them

Redmond

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Setting theme for the scheduler
Setting theme for the scheduler
The install package of jqScheduler for PHP comes with just the default Redmond theme. It is available in the [themes] folder of the install package. You can download any additional themes directly from jQuery UI's ThemeRoller site available here:

http://jqueryui.com/themeroller/

There are currently 25 professional themes available. You can also create a new theme (either from scratch or based on another theme).

In addition to the "Redmond" theme, there is one more file in the [themes] folder - ui.jqscheduler.css. This is the one and only Css file jqScheduler for PHP needs for themeing in addition to the ThemeRoller theme. Just add it after you add the reference to the ThemeRoller theme in your PHP file.

Example:

<head>
<link rel="stylesheet" type="text/css" href="themes/redmond/jquery-ui-1.8.13.custom.css" />
<link rel="stylesheet" type="text/css" href="themes/ui.jqscheduler.css" />
...
</head>

If you wish to use one of the other 25 themes ThemeRoller offers or your own theme, just replace the Redmond css file with the CSS file of the respective theme.

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 Rolling your own theme
Rolling your own theme
In order to create your own theme, just use the superb ThemeRoller theme creator tool available here.

Last Updated: 06/06/11 | © TriRand Ltd., 2011


 jqScheduler class guide
jqScheduler class guide

Last Updated: 06/07/11 | © TriRand Ltd., 2011


 Variables
Variables
List of variables that can be used with this class.

Type | Name | Description | Default | Access
string | version | Get the current version of the chart | n/a | public
string | table | The name of the table which holds event data | events | public
string | calenderid | The id of the eventcalendar in the template | calendar | public
string | datepickerid | The id of the calendar in the template | datepicker | public
string | eventid | The id of the event form for entering data in the template | event | public
array | available_users | The available calendar for the particular user | empty array | public
string | backend_type | The default backend type. Can be database, demo, gcal, calDAV. Currently only database is available | database | public
string | printformat | The default printing format of the events when print button is clicked. Can be pdf or html | pdf | public

Last Updated: 06/07/11 | © TriRand Ltd., 2011


 Methods
Methods
Publick methods within jqScheduler

setUrl( $curl )

Set the url from where to get the data after the scdedule is created.

Parameters:

  • string $curl: the url

API Tags:
Access: public

setLocale( $lng )

Set the language used in the schedule. After this string we add a inc suffix and search for this file.

Parameters:

  • string $lng: The name of the language file. default is English

API Tags:
Access: public

setTemplate( $html, string [$css=''] )

Set the template and css files used for rendering and editing the events

Parameters:

  • string $html: The name of the html file. Deafult is calendar.html
  • string $css: The the name of the css file. Default is calendar.css

API Tags:
Access: public

getOption( $option )

Return the option of the event calendar

Parameters:

  • string $option: existing option

API Tags:
Access: public

setOption($option, $value=null)

Set options for the event calender. See options

Parameters:

  • mixed $option: the option name for the event calender. Can be a string or array. When used as array a key value pair should be defined, where the key is the name
  • mixed $value is the value option in case the $option is string

API Tags:
Access: public

setEvent( $event, $code )

Set a valid javascript calendar event

Parameters:

  • string $event: Valid event
  • string $code: Javascript code which will be executed when the event raises

API Tags:
Access: public

setUser( $user_id, $usesession=true )

Set the current user used in event calendar. The function uses sessions to store the current user. This is done if the second parameter is set to true.

Parameters:

  • integer $user_id: the user
  • boolean $usesession: is set to true a session is used, otherwiese a custom mechanism should be used

API Tags:
Access: public

setUserNames( $anames )

Set the pair value names of the currently used calendar (users). This represent different calendars for the curren user.

Parameters:

  • array $anames: associative array for the the calendars

API Tags:
Access: public

setUserDateFormat ($newformat)

Set the user date format for entering and displaying dates. A PHP convensions should be used. Default is d/m/Y

Parameters:

  • string $newformat: new date format

API Tags:
Access: public

setPdfOptions( $apdf )

Set options for PDF export.

Parameters:

  • array $apdf: pdf options

API Tags:
Access: public

exportEvents( )

Export events to iCal format. A start and end parameters should be send in

Parameters:

  • None

API Tags:
Access: public

printEvents( )

Print the result either as html or as pdf depending on the $printformat variable

Parameters:

  • None

API Tags:
Access: public

render( [$script], [$echo] )

Create the scheduler after all options and events are set and the do all the thing regarding adding, editing printing and etc things

Parameters:

  • boolean $script: if true a javascript tag is outputed
  • boolean $echo : if false a the string is returned (where possible)

API Tags:
Access: public

Last Updated: 06/07/11 | © TriRand Ltd., 2011


 Options
Options

For the Scheduler options a two methods can be used

getOption($key) to obtain the desired option
where $key is a name listed below
and
setOption(array $aoptions, $value) to set a new option(s)
where
$aoptions is array where multiple options can be set.
The method can be called several times in order to set or overwrite existing option(s).

Example: If we want to change the eventColor and evenBorderColor we can write the code like this

<?php
...
// Create the jqGridRender instance
$events = new jqScheduler($conn);
...
$events->setOption(array("eventColor"=>'#378006',"eventBorderColor"=>'#378006'));
...
$events->render();
?>

The same code is equivalent

<?php
...
// Create the jqGridRender instance
$events = new jqScheduler($conn);
...
$events->setOption("eventColor",'#378006');
$events->setOption("eventBorderColor",'#378006');
...
$events->render();
?>

Bellow is a list of all available options

Last Updated: 06/13/11 | © TriRand Ltd., 2011


 General Display/View
General Display/View
header
Defines the buttons and title at the top of the calendar.

Type: mixed - array/false, default:

array(
'left'=> 'prev, next today',
'center=> 'title',
'right'=> 'agendaDay, agendaWeek, month'
)

Setting the header options to false will display no header. An array can be supplied with properties left, center, and right. These properties contain strings with comma/space separated values. Values separated by a comma will be displayed adjacently. Values separated by a space will be displayed with a small gap in between. Strings can contain any of the following values:

title
text containing the current month/week/day
prev
button for moving the calendar back one month/week/day
next
button for moving the calendar forward one month/week/day
prevYear
button for moving the calendar back on year
nextYear
button for moving the calendar forward one year
today
button for moving the calendar to the current month/week/day
a view name
button that will switch the calendar to any of the Available Views

Example:

$eventcal->setOption("header"=>array('left'=> 'title','center'=> '', 'right'=> 'today prev,next'));

buttonIcons
Determines which theme icons appear on the header buttons.

Type: array. default:

array(
'prev'=> 'circle-triangle-w',
'next'=> 'circle-triangle-e'
)

A hash must be supplied that maps button names (from the header) to icon strings. The icon strings determine the CSS class that will be used on the button. For example, the string 'circle-triangle-w' will result in the class 'ui-icon-triangle-w'.

If a button does not have an entry, it falls back to using buttonText.

If you are using a jQuery UI theme and would prefer not to display any icons and would rather use buttonText instead, you can set the buttonIcons option to false.

Example:

$eventcal->setOption("buttonIcons"=>array( 'prev'=> 'circle-triangle-w', 'next'=> 'circle-triangle-e'));

firstDay
The day that each week begins.

Type: integer default: 0 (Sunday)

The value must be a number that represents the day of the week.

Sunday=0, Monday=1, Tuesday=2, etc.

This option is useful for UK users who need the week to start on Monday (1).

weekends
Whether to include Saturday/Sunday columns in any of the calendar views.

Type: Boolean, default: true

weekMode
Determines the number of weeks displayed in a month view. Also determines each week's height.

Type: String, default: 'fixed'

Available options:

'fixed'
The calendar will always be 6 weeks tall. The height will always be the same, as determined by height, contentHeight, or aspectRatio.
'liquid'
The calendar will have either 4, 5, or 6 weeks, depending on the month. The height of the weeks will stretch to fill the available height, as determined by height, contentHeight, or aspectRatio.
'variable'
The calendar will have either 4, 5, or 6 weeks, depending on the month. Each week will have the same constant height, meaning the calendar’s height will change month-to-month.

height
Will make the entire calendar (including header) a pixel height.

Type: Integer

By default, this option is unset and the calendar's height is calculated by aspectRatio.

Example usage of height:
Example:

$eventcal->setOption("height"=>650);

Setter
You can dynamically set a calendar's height after initialization with javaScript:

$('#calendar').fullCalendar('option', 'height', 700);

contentHeight
Will make the calendar's content area a pixel height.

Type: Integer

By default, this option is unset and the calendar's height is calculated by aspectRatio.

Example usage of contentHeight:
Example:

$eventcal->setOption("contentHeight"=>600);

Setter
You can dynamically set a calendar's content height after initialization with javaScript:

$('#calendar').fullCalendar('option', 'contentHeight', 700);

aspectRatio
Determines the width-to-height aspect ratio of the calendar.

Type: Float, default: 1.35

A calendar is a block-level element that fills its entire avaiable width. The calendar’s height, however, is determined by this ratio of width-to-height. (Hint: larger numbers make smaller heights).

The following example will initialize a calendar who's width is twice its height:

$eventcal->setOption("aspectRatio"=>2);

Setter
You can dynamically set a calendar's aspectRatio after initialization with JavaScript:

$('#calendar').fullCalendar('option', 'aspectRatio', 1.8);

defaultView
The initial view when the calendar loads.

Type:String, default: 'month'

Any of the Available Views (see below)

Available Views
jqScheduler has a number of different "views", or ways of displaying days and events. The following 5 views are available:

  • month
  • basicWeek
  • basicDay
  • agendaWeek
  • agendaDay

You can define header buttons to allow the user to switch between them. You can set the initial view of the calendar with the defaultView option (see above).

Last Updated: 06/08/11 | © TriRand Ltd., 2011


 Agenda Options
Agenda Options
allDaySlot
Determines if the "all-day" slot is displayed at the top of the calendar.

Type: Boolean, default: true

When hidden with false, all-day events will not be displayed in agenda views.

allDayText
The text titling the "all-day" slot at the top of the calendar.

Type: String, default: 'all-day'

axisFormat
Determines the time-text that will be displayed on the vertical axis of the agenda views.

Type: String, default: 'h(:mm)tt'

The value is a format-string that will be processed by formatDate.

The default value will produce times that look like "5pm" and "5:30pm".

slotMinutes
The frequency for displaying time slots, in minutes.

Type: Integer, default: 30

The default will make a slot every half hour.

defaultEventMinutes
Determines the length (in minutes) an event appears to be when it has an unspecified end date.

Type:Integer, default: 120

By default, if an Event Object as no end, it will appear to be 2 hours.

This option only affects events that appear in the agenda slots, meaning they have allDay set to true.

firstHour
Determines the first hour that will be visible in the scroll pane.

Type:Integer, default: 6

Values must be from 0-23, where 0=midnight, 1=1am, etc.

The user will be able to scroll upwards to see events before this time. If you want to prevent users from doing this, use the minTime option instead.

minTime
Determines the first hour/time that will be displayed, even when the scrollbars have been scrolled all the way up.

Type:Integer/String, default: 0

This can be a number like 5 (which means 5am), a string like '5:30' (which means 5:30am) or a string like '5:30am'

maxTime
Determines the last hour/time (exclusively) that will be displayed, even when the scrollbars have been scrolled all the way down.

Type:Integer/String, default: 24

This can be a number like 22 (which means 10pm), a string like '22:30' (which means 10:30pm) or a string like '10:30pm'.

Last Updated: 06/08/11 | © TriRand Ltd., 2011


 Current Date
Current Date
year
The initial year when the calendar loads.

Type: Integer

Must be a 4-digit year like 2009.

If year is unspecified, the calendar will begin at the current year.

month
The initial month when the calendar loads.

Type:Integer

IMPORTANT: The value is 0-based, meaning January=0, February=1, etc.

If month is unspecified and year is set to the current year, the calendar will start on the current month. If month is unspecified and year is not set to the current year, the calendar will start on January.

date
The initial date-of-month when the calendar loads.

Type:Integer

This option only matters for the week & day views. Month view does not need this option, because month view always displays the entire month from start to finish.

If date is unspecified, and year/month are set to the current year/month, then the calendar will start on the current date. If date is unspecified, and year/month are not set to the current year/month, then the calendar will start on the first of the month.

Last Updated: 06/08/11 | © TriRand Ltd., 2011


 Text/Time Options
Text/Time Options
timeFormat
Determines the time-text that will be displayed on each event.

Type: mixed - array/String default:

array(
// for agendaWeek and agendaDay
'agenda'=> 'h:mm{ - h:mm}', // 5:00 - 6:30

// for all other views
''=> 'h(:mm)t' // 7p
);

A single format string will change the time-text for events in all views. A View Option Hash may be provided to target specific views (this is what the default does).

Time-text will only be displayed for Event Objects that have allDay equal to false.

Here is an example of displaying all events in a 24-hour format:

$eventcal->setOption("timeFormat"=>"H(:mm)");

columnFormat
Determines the text that will be displayed on the calendar's column headings.

Type: mixed - array/String, default:

array(
'month'=> 'ddd', // Mon
'week'=> 'ddd M/d', // Mon 9/7
'day'=> 'dddd M/d' // Monday 9/7
)
A single string will set the title format for all views. A View Option Hash may be provided to target specific views (this is what the default does).

titleFormat
Determines the text that will be displayed in the header's title.

Type: mixed - array/String, default:

array(
'month'=> 'MMMM yyyy', // September 2009
'week'=> "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", // Sep 7 - 13 2009
'day'=> 'dddd, MMM d, yyyy' // Tuesday, Sep 8, 2009

)
A single string will set the title format for all views. A View Option Hash may be provided to target specific views (this is what the default does).

buttonText
Text that will be displayed on buttons of the header.

Type: array, default:

array(
'today'=> 'today',
'month'=> 'month',
'week'=> 'week',
'day'=> 'day'
);

monthNames
Full names of months.

Type: Array, default:

array('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December');

monthNamesShort
Abbreviated names of months.

Type: Array, default:

array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

dayNames
Full names of days-of-week.

Type:Array, default:

array('Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday');

dayNamesShort
Abbreviated names of days-of-week.

Type:Array, default:

array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');

Last Updated: 06/08/11 | © TriRand Ltd., 2011


 Event Data/Rendering
Event Data/Rendering
allDayDefault
Determines the default value for each Event Object's allDay property, when it is unspecified.

Type: boolean, default: true

ignoreTimezone
When parsing ISO8601 dates, whether UTC offsets should be ignored while processing event source data.

Type: boolean, default: true

The default is true, which means the UTC offset for all ISO8601 dates will be ignored. For example, the date "2008-11-05T08:15:30-05:00" will be processed as November 5th, 2008 at 8:15am in the local offset of the browser.

If you are using ISO8601 dates with UTC offsets, chances are you want them processed. You must set this option to false. In the future, the default for this option will probably be changed to false.

lazyFetching
Determines when event fetching should occur.

Type: boolean, default: true

When set to true (the default), the calendar will only fetch events when it absolutely needs to, minimizing AJAX calls. For example, say your calendar starts out in month view, in February. FullCalendar will fetch events for the entire month of February and store them in its internal cache. Then, say the user switches to week view and begins browsing the weeks in February. The calendar will avoid fetching events because it already has this information stored.

When set to false, the calendar will fetch events any time the view is switched, or any time the current date changes (for example, as a result of the user clicking prev/next).

eventColor
Sets the background and border colors for all events on the calendar.

Type: String

You can use any of the CSS color formats such #f00, #ff0000, rgb(255,0,0), or red

eventBackgroundColor
Sets the background color for all events on the calendar.

Type:String

You can use any of the CSS color formats such #f00, #ff0000, rgb(255,0,0), or red.

eventBorderColor
Sets the border color for all events on the calendar.

Type:String

You can use any of the CSS color formats such #f00, #ff0000, rgb(255,0,0), or red.

eventTextColor
Sets the text color for all events on the calendar.

Type:String

You can use any of the CSS color formats such #f00, #ff0000, rgb(255,0,0), or red.

Last Updated: 06/13/11 | © TriRand Ltd., 2011


 Dragging & Resizing
Dragging & Resizing
editable
Determines whether the events on the calendar can be modified.

Type: boolean, default: false

This determines if the events can be dragged and resized. Enables/disables both at the same time. If you don't want both, use editable in conjunction with disableDragging and disableResizing.

disableDragging
Disables all event dragging, even when events are editable.

Type: boolean, default: false

disableResizing
Disables all event resizing, even when events are editable.

Type: boolean, default

dragRevertDuration
Time it takes for an event to revert to its original position after an unsuccessful drag.

Type: integer, default: 500

Time is in milliseconds (1 second = 1000 milliseconds).

dragOpacity
The opacity of an event while it is being dragged.

Type: float/array, default:

array(
// for agendaWeek and agendaDay
"agenda"=> 0.5,

// for all other views
'' => 1.0
)
Float values range from 0.0 to 1.0.

Specify a single number to affect all views, or a View Option Hash to target specific views (which is what the default does).

Last Updated: 06/13/11 | © TriRand Ltd., 2011


 jqForm PHP
jqForm PHP

Welcome to the technical documentation of jqForm for PHP. If you have questions and comments, please use the following channels to get back to us:

Public forums:
http://www.trirand.net/forum/

Email:
support@trirand.net

Last Updated: 10/24/11 | © TriRand Ltd., 2011


 Introduction
Introduction

jqForm for PHP is a server-side component built on top of open and widely used standards - jQuery, jQuery UI, ThemeRoller.

Bellow is the list of the most common featutres (in general)

  • Ajax Submit (via jQuery Form plugin)
  • Multilingual (field captions, default values, error messages).
  • ClientSide validation(when used HTML5)
  • Serverside input validation (in development)
  • Access rights; the same form can be used for different users/groups.
  • Can deal with hitting enter in text fields .
  • Offers some nice domapi form element implementations and some more ready-to-use out-of-the-box special fields.
  • Can deal with include-once and onLoad javascript stuff.
  • Auto-persisting of submitted forms to database. This includes the auto-creation/update of the database table.
  • No limits: everything you can do with plain HTML can be done with this package.
Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Installation and System Requierments
Installation and System Requierments

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Requierments
Requierments

Browser Support

jqForm for PHP supports all major browsers:

  • Internet Explorer 6.x+
  • FireFox 3.x+
  • Safari 2.x+
  • Google Chrome 2.x+
  • Opera 9.5+

PHP

jqForm is designed to work with PHP versions 5.1+.

Databases (optional)

Currently jqForm for PHP supports the following databases:

  • MySQL 5.x+ (PDO)
  • PostgreSQL versions 7.x+ (PDO)
  • SQLite versions 3.x+ (PDO)
  • Microsoft SQL Server 2005+
  • Oracle 8+
  • MySQL (through Mysqli)
  • DB2 (IBM DB2 functions)

MySQL, PostgreSQL and SQLite databases are supported through PHP PDO (PHP Data Objects), so depending on your PHP setup you may need to install it before using jqAutocomplete for PHP. PDO is by default installed in PHP 5.1+ distributions. PDO is a core PHP technology, created and supported by the core PHP team.

To ensure that PDO is installed in your production enviornment, please run the following PHP script on your development/production machine:

<?php
phpinfo();
?>

Save the file and run it on your web server. The following should appear if you want to use MySQL and have PDO installed:

The following should appear if you want to use PostgreSQL and have PDO installed:

The following should appear if you want to use SQLite and have PDO installed:

Microsoft SQL Server is supported through the PHP driver provided by Microsoft. Please follow the installation instructions provided by Microsoft in the PHP driver documentation. After the driver is installed, the following should appear if you run the "phpinfo()" function:

Oracle is supported through the PHP OCI8 driver. Please follow the installation instructions provided in the same link. After the driver is installed, the following should appear if you run the "phpinfo()" function:

Additinally MySQL database is supported through Mysqli driver. Follow the installation instuction provided from the same link. After the installation is done the following should appear if you run the "phpinfo()" function:

Additinally DB2 database is supported through DB2 driver. Follow the installation instuction provided from the same link. After the installation is done the following should appear if you run the "phpinfo()" function:

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Quick Install
Quick Install
Download and unzip the contents of the archive to any convenient location. The package contains the following folders:

- [php] - Contains the jqForm PHP class and the optional driver files for the appropriate database.
- [themes] - Contains the themes shipped with the product. Since jqForm supports jQuery UI Themeroller, any theme compatible with jQuery UI ThemeRoller will work for jqForm as well. Therefore, the package contains just one theme ("Redmond"). You can download any additional themes directly from jQuery UI's ThemeRoller site available here:

http://jqueryui.com/themeroller/

Just add "Redmond" theme in your PHP/HTML file.

<link rel="stylesheet" type="text/css" href="themes/redmond/jquery-ui.custom.css" />

- [js] - The javascript files of jqForm (and the needed libraries). You need to include them in your PHP page.

The first file is "jquery.js" - this is the official jQuery library.
The second file is "jquery.jqForm.js" - this is the jqForm specific libraray.
The third file is "jquery.form.js" - this is the jqquery form plugin.
The final result you will have in an PHP page containing jqForm would be something similar to that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First PHP jqAutocomplete </title>

<link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui.custom.css" />

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.jqForm.js" type="text/javascript"></script>
<script src="js/jquery.form.js" type="text/javascript"></script>

</head>
<body>
......
<?php include "firstform.php";?>
.......
</body>
</html>

Save the file as myform.php or any desired name in the root directory and then create a file firstform.php with the following content.

<?php
// Include classes
include_once 'php/jqUtils.php';
include_once 'php/jqForm.php';
// Create instance
$myform = new jqForm();
// Set Form properties
$myform->setFormProperties('myform',array('method' => 'post', 'id' => 'myform'));
// Set url
$myform->setUrl('firstform.php');
// Set Form header
$myform->setFormHeader('Address Details','ui-icon-pencil');
// Set Form layout
$myform->setColumnLayout('twocolumn');
$myform->setTableStyles('','padding-top: 3px','padding-top: 3px');
// Add elements
$myform->addElement('name','text', array('label' => 'Name', 'size' => '40', 'id' => 'myform_name'));
$myform->addElement('email','email', array('label' => 'E-mail', 'size' => '40', 'id' => 'myform_email'));
$myform->addElement('address','text', array('label' => 'Address', 'size' => '40', 'id' => 'myform_address'));
$myform->addElement('tel','tel', array('label' => 'Telephone', 'required' => '1', 'id' => 'myform_tel'));
$elem_5[]=$myform->createElement('newSubmit','submit', array('value' => 'Submit', 'id' => 'newSubmit'));
$myform->addGroup("newGroup",$elem_5, array('style' => 'text-align:right;', 'id' => 'myform_newGroup'));
// Render the form
echo $myform->renderForm($jqformparams);
?>

Run the file myform.php from your web browser. All subsequent requests will be forwarded back to the "firstform.php" file and the component will automatically handle the requests and provide the needed operation - no need for custom coding.

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Overview
Overview
The jqForm PHP class uses the jQuery UI CSS Framework to style look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.autocomplete.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<form name="myform" method = "post" id = "myform" >
    <table style="">
       <thead>
          <tr>
             <th align='left' colspan="2">
                 <div class="ui-state-default ui-corner-all" style = "padding:6px;" >
                    <span class="ui-icon ui-icon-pencil" style="float:left; margin:-2px 5px 0 0;"></span>
                    Address Details
                 </div>
              </th>
           </tr>
         </thead>
         <tbody>
            <tr>
               <td style="padding-top: 3px">
                  <label for="myform_name">Name</label>
               </td>
               <td style="padding-top: 3px">
                  <input size = "40" id = "myform_name" name = "name" class = " ui-input ui-widget-content ui-corner-all" type = "text" />
               </td>
           </tr>
            ...
           <tr>
              <td colspan="2">
                  <div name='newGroup' style = "text-align:right;width:100%;" id = "myform_newGroup" name = "newGroup" >
                     <input value = "Submit" id = "newSubmit" class = "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" type = "submit" />
                  </div>
              </td>
           </tr>
        </tbody>
     </table>
</form>

Note: This is a sample of markup generated by the jqForm, not markup you should use to create a form.

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Form class guide
Form class guide

Last Updated: 10/24/11 | © TriRand Ltd., 2011


 Varaibles
Varaibles
List of public variables that can be used with this class.
Usual implementation can look like this
<?php
// Include classes
include_once 'php/jqUtils.php';
include_once 'php/jqForm.php';
// Create instance
$myform = new jqForm();
$myform->encoding = 'utf-8';
...
?>

Type | Names | Description | Default | Access
string | inputclass | Set a commom class to all input elements | ui-widget-content ui-corner-all | public
string | SelectCommand | Defines the select command for obtaining the data from the database. This command can contain any valid SQL syntax. With this command we fill the form is the record can be found. In the command is possible to use parameters which can be set later in the render method. Example: SELECT field1, field2 FROM table WHERE field1 = ? | empty string | public
string | table | The table where the data submitted from the form will be stored. The class autoamticaly detect if the record should be inserted or updated based on the primary key set | empty | public
string | oper | Determines the operation when ajax is in action and after the form is rendered into the DOM. Currently we have following operatin: no, get, save | empty | public
string | DbDate | The date format used in the database to store the date | Y-m-d | public
string | DbTime | The time format used in the database to store the time | H:i:s | public
string | DbDateTime | The datetime format used in the database to store the datetime | Y-m-d H:i:s | public
string | UserDate | The date format used in client side to show the date | Y-m-d | public
string | UserTime | The time format used in client side to show the time | H:i:s | public
string | UserDateTime | The datetime format used in client side to show the datetime | Y-m-d H:i:s | public
boolean | serialKey | Determines if the primary key is serial (autoincrement) | true | public
string | encoding | The encoding used in the database and response | utf-8 | public
boolean | trans | Determines if the operation add/update in the table after posting the data to the script should be enclosed in transaction | true | public
boolean | add | Detrmines if adding of data is enabled | true | public
boolean | edit | Detrmines if updating of data is enabled | true | public

Last Updated: 10/16/11 | © TriRand Ltd., 2011


 Methods
Methods
void addElement( string $name, string $type, [array $aproperties = array()] )

Add a input element in elements array with name = $name of type = $type and properties = $aproperties

Parameters:

  • string $name: the name of the input
  • string $type: the type of the input can be: select, textarea, submit, reset, button, input
  • array $aproperties: properties

API Tags:
Access: public

void addEvent( string $field, string $event, string $code )

Add a javascript event = $event with code = $code for field = $field

Parameters:

  • string $field: namre of the field
  • string $event: name of the event
  • string $code: java script code

API Tags:
Access: public

void addGroup( string $name, array $elemetnts, array $properties )

Add a group in the elements array with input elements and properties

Parameters:

  • string $name: group name
  • array $elemetnts: array of input elements
  • array $properties: of the group

API Tags:
Access: public

string createElement( string $name, string $type, array $prop )

Create a input element of type=$type name=$name and propertiies The method is used in renderForm to cretate the form elements based on the elemets optiins array

Parameters:

  • string $name: the name of the element
  • string $type: the type of the input element
  • array $prop: valid HTML properties of the element

API Tags:
Access: public

string createGroup( string $name, array $elements, [type $prop = null] )

Creates a group element with name = $name and properties = $properties, containing input elements (array)

Parameters:

  • string $name: - the name of the group element
  • array $elements: - array of the elemets in the group
  • type $prop: properties of the group element

API Tags:
Access: public

array getPrimaryKeyId( )

Return the primary key(s) of the table as array

API Tags:
Access: public

boolean insert( array $data )

Insert the data array into the database according to the table element.
Return true on succes, false otherwiese.

Parameters:

  • array $data: associative array which key values correspond to the names in the table.

API Tags:
Access: public

string renderForm( [ $params = null] )

The main method which should be called at end whenall other data for the form is prepared. The pethod perform constructiong of the form, obtaining data and save the data posted from the client.

Parameters:

  • array $params: parameters for the select coomand

API Tags:
Access: public

boolean save( array $data )

Automatically determines if the data posted from the form should be added or updated. The method use insert and update method for this purpose

Parameters:

  • array $data: data to be saved into the table from the form post

API Tags:
Access: public

void setAjaxOptions( array $aoptions )

Set the options for the ajax submit

Parameters:

  • array $aoptions: options for the ajax submit

API Tags:
Access: public

void setColumnLayout( [string $layout = 'twocolumn'] )

Set the layout of the form. Can be: onecolumn - we have label and below this label the input form element.
twocolumn - the leabel is at one column left and the data in another right

Parameters:

  • string $layout:

API Tags:
Access: public

void setConnection( resource $db )

Set the connection used for add/update of the form post and when get the certain data.

Parameters:

  • resource $db:

API Tags:
Access: public

void setFormFooter( string $content, [array $style = null] )

Set the form footer and properties.

Parameters:

  • string $content: content to be set in the header
  • array $style: properties in the gheader

API Tags:
Access: public

void setFormHeader( string $content, [string $icon = ""], [array $style = null] )

Set the form header and properties.

Parameters:

  • string $content: content to be set in the header
  • string $icon: - icon name from UI Themeroller
  • array $style: properties in the gheader

API Tags:
Access: public

void setFormProperties( string $name, [array $aproperties = array()] )

Set the form properties in the elements array.

Parameters:

  • string $name: - the name of the form
  • array $aproperties: properties

API Tags:
Access: public

void setJSCode( string $code )

Put a valid Java Script code after the form is rendered into the dom

Parameters:

  • string $code:

API Tags:
Access: public

void setPrimaryKeys( string $keys )

Set the primary key(s) for future using in add/update.

Parameters:

  • string $keys:

API Tags:
Access: public

void setTableStyles( [string $table = ''], [string $label = ''], [string $data = ''] )

Set a common style for the table, labels and data input elements

Parameters:

  • string $table: table properties
  • string $label: common label properties
  • string $data: common data properties

API Tags:
Access: public

void setUrl( string $nurl )

Set the url from where to get data and add or update it.

Parameters:

  • string $nurl: the new url

API Tags:
Access: public

boolean update( array $data )

Update the data into the database according the table element A primaryKey should be set.

Parameters:

  • array $data: associative array which key values correspond to the names in the table

API Tags:
Access: public

Last Updated: 10/24/11 | © TriRand Ltd., 2011


 jqForm Tutorials
jqForm Tutorials

For the tutorials please look the Demos
Last Updated: 10/24/11 | © TriRand Ltd., 2011