Description
Overview¶
The Render Class is the most advanced and feature rich class jqGrid for PHP provides, aimed to do almost everything 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 Render class extends the Edit Class (i.e. jqGrid Class too) . This mean that everything that can be done with these classes is available in this class too.
Methods and Variables¶
For the list of up to date variables and methods, please refer to to the API documentation.
Grid Options¶
Grid options is a object which contain all the properties and events of the grid in a format key value. For the grid options two methods are used:
- getGridOption( $key ) to obtain the desired option, where $key is a name of the options
- setGridOptions(array $aoptions) to set a new option(s) where $aoptions is array where multiple options can be set.
Commonly, with these two command we can do everything with the grid. The method setGridOptions 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
require_once 'path_to_your_project_vendor_dir/autoload.php';
...
// Create the jqGrid instance
$grid = new Guriddo\jqGrid\Render\Render($conn, 'pdo');
$grid->setGridOptions(array("width"=>500,"height"=>350));
...
$grid->renderGrid(...);
the same is equivalent to:
<?php
require_once 'path_to_your_project_vendor_dir/autoload.php';
...
// Create the jqGrid instance
$grid = new Guriddo\jqGrid\Render\Render($conn, 'pdo');
$grid->setGridOptions(array("width"=>500));
$grid->setGridOptions(array("height"=>350));
...
$grid->renderGrid(...);
The list of up to date all available Grid options can be found here
Grid Events¶
Actually grid events are options, but we want to pay special attention to them. The event is action that is raised on the client side when something is happen in the grid. Since this is a client side job in order to use the grid events you will need to write a JavaScript code. The JavaScript code is defined in PHP script and below is a example in which when the user select a grid row, alert message appear.
The PHP method that initializes the event is setGridEvent.
<?php
require_once 'path_to_your_project_vendor_dir/autoload.php';
...
// Create the jqGrid instance
$grid = new Guriddo\jqGrid\Render\Render($conn, 'pdo');
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders';
...
$myevent = <<<ONSELECT
function(rowid, selected)
{
if (rowid) alert("Row:" + rowid + " 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 client side:
("#grid").jqGrid({
...
onSelectRow:function(rowid, selected) {
if (rowid) alert("Row:" + rowid + " is selected");
},
...
});
The list of up to date all available Grid Events can be found here
Writing JavaScript¶
Guriddo Suito PHP support adding a javascript within PHP script. This is done via putting special word "js:" before the script.
Warning
It is very important to note that there are exceptions from this rule. When the following methods are used:
- setGridEvent
- setNavEvent
- setJSCode
placing a js: before the code will not run the script. These methods add the js: automatically before the code
When should be used 'js:'?
The 'js:' word should(can) be used in place where the type definition is function and in the following options - Column Model Options for extending the editing-properties and in Formatters to define custom formatter. Also can be used in Toolbar Filter
In case if the Java Script code is complex we recommend to add it within the following tags
$mycode = <<<CUSTOMCODE
//
// here JavaScript code
CUSTOMCODE;
In this case jou will not worry about the single and double barkets which will cause error in the PHP script.
setGridEvent
With setGridEvent we add a events related to the grid. The method has 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 accept.
Let suppose that we want to alert a message with the OrderID. Using our exsample 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;
?>
The same action written with "js:" will look like this
<?php
...
$onselect = <<<ONSELECTROW
function(rowid, selected)
{
alert(rowid);
}
ONSELECTROW;
$grid->setGridOptions(array("onSelectRow"=>"js:".$onselect);
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
setNavEvent
setNavEvent works the same way as setGridEvent, but it adds a javascript events to the navigator or/and formediting modules.
setJSCode
setJSCode adds a code written in JS just after the creation of jqGrid instance. Using this method you can add what you want JavaScript code.
Column Model¶
The colModel property (part of Grid options) 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 automatically 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 parameters of existing one and addCol method can be used to add additional column in the colModel (grid).
When the method is called it adds the following options automatically: name, index, sorttype, key
The following methods are related to colModel
-
getColModel - return the colModel
-
setColModel - set the ColModel of the grid
- setColProperty - set Individual property in column from colModel
- addCol - add colum to the colModel
The list of all up to date properties for the colModel can be found here. Detailed description of all of these methods can be found in the API documentation.
The syntax of colModel method is as follow:
public function setColModel(array $model=null, array $params=null, array $labels=null)
{
...
}
The Method build the column model of the grid. The model can be passed as array or can be constructed from sql.The method try to determine the primary key and if it is found is set as key:true to the appropriate field. If the primary key can not be determined it set the first field as key:true in the colModel. Return true on success.
-
@param array
$model if set construct the model ignoring the SQL command -
@param array
$params if a sql command is used parameters passed to the SQL - @param array
$labels if this parameter is set it set the labels in colModel. The array should be associative which key value correspond to the name of colModel
Method return true on success
Note
In case there is a need to set a custom primary key it is needed to use the public method setPrimaryKeyId before calling the setColModel
Note
The second parameter $param should be set too in case there are custom parameters passed to the sql command. This is needed to properly get the columns from the query.
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:
- cell editing: edit specific cells in a gird
- in-line editing: edit several cells in the same row
- 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 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 external 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 create the element, and get the value from it in order to be posted to the server.
Functions that should be defined:
- 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.
- 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 additional tasks:
- add a class 'customelement'
- add attribute name with name from colModel
- add id according to the rules for every edited module.
See grid Editing examples 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/events:
| Property | Type | Description |
|---|---|---|
| value | mixed | When set for edittype check-box 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 event 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 own 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. This event is a perfect way to define actions via custom plug-ins like date-picker, auto-complete and etc. |
| dataEvents | array | list of events to apply to the data element; uses jQuery on like $(”#id”).on(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. Also the information is used for server validation to build the properly the needed setting. See method validationFromModel
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. |
| 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 |
Note
Two elements can have equal row position, but different column position. This will place the two elements in one row on the form.
Search Options¶
Guriddo jqGrid uses a common search options that can be used on every search method. Below is a list of these options that can be set in colModel. Note that some options are not applicable for particular method.
Detailed description of all available search methods is described here
searchoptions¶
All the up to date searchoptions are listed here
To use the search options use setColProperty method.
...
$grid->setColModel(...);
$grid->setColProperty('somefield', array( "searchoptions" => array( "defaultValue" => "val", "searchhidden"=>true...), ..));
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(...);
...
?>
All the up to date searchrules are listed here
Warning
The searchrules are used only in the searching dialog (searching and advanced searching) and not in the other search methods.
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.
Warning
The default formatter options are different for different language files.
Here are the default formatter options for the English file:
$.jgrid.regional["en"] = {
...
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"
],
AmPm : ["am","pm","AM","PM"],
S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th';},
srcformat: 'Y-m-d',
newformat: 'n/j/Y',
parseRe : /[#%\\\/:_;.,\t\s-]/,
masks : {
// see http://php.net/manual/en/function.date.php for PHP format used in jqGrid
// and see http://docs.jquery.com/UI/Datepicker/formatDate
// and https://github.com/jquery/globalize#dates for alternative formats used frequently
// one can find on https://github.com/jquery/globalize/tree/master/lib/cultures many
// information about date, time, numbers and currency formats used in different countries
// one should just convert the information in PHP format
ISO8601Long:"Y-m-d H:i:s",
ISO8601Short:"Y-m-d",
// short date:
// n - Numeric representation of a month, without leading zeros
// j - Day of the month without leading zeros
// Y - A full numeric representation of a year, 4 digits
// example: 3/1/2012 which means 1 March 2012
ShortDate: "n/j/Y", // in jQuery UI Datepicker: "M/d/yyyy"
// long date:
// l - A full textual representation of the day of the week
// F - A full textual representation of a month
// d - Day of the month, 2 digits with leading zeros
// Y - A full numeric representation of a year, 4 digits
LongDate: "l, F d, Y", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy"
// long date with long time:
// l - A full textual representation of the day of the week
// F - A full textual representation of a month
// d - Day of the month, 2 digits with leading zeros
// Y - A full numeric representation of a year, 4 digits
// g - 12-hour format of an hour without leading zeros
// i - Minutes with leading zeros
// s - Seconds, with leading zeros
// A - Uppercase Ante meridiem and Post meridiem (AM or PM)
FullDateTime: "l, F d, Y g:i:s A", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy h:mm:ss tt"
// month day:
// F - A full textual representation of a month
// d - Day of the month, 2 digits with leading zeros
MonthDay: "F d", // in jQuery UI Datepicker: "MMMM dd"
// short time (without seconds)
// g - 12-hour format of an hour without leading zeros
// i - Minutes with leading zeros
// A - Uppercase Ante meridiem and Post meridiem (AM or PM)
ShortTime: "g:i A", // in jQuery UI Datepicker: "h:mm tt"
// long time (with seconds)
// g - 12-hour format of an hour without leading zeros
// i - Minutes with leading zeros
// s - Seconds, with leading zeros
// A - Uppercase Ante meridiem and Post meridiem (AM or PM)
LongTime: "g:i:s A", // in jQuery UI Datepicker: "h:mm:ss tt"
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
// month with year
// Y - A full numeric representation of a year, 4 digits
// F - A full textual representation of a month
YearMonth: "F, Y" // in jQuery UI Datepicker: "MMMM, yyyy"
},
reformatAfterEdit : false,
userLocalTime : false
},
baseLinkUrl: '',
showAction: '',
target: '',
checkbox : {disabled:true},
idName : 'id'
},
...
}
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
Note
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.
integer¶
Format a integer number according to the following formatoptions properties:
(The default values of these are set in the language file used)
- thousandsSeparator - determines the separator for the thousands.
- defaultValue set the default value if the source data is empty.
Example:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"integer", "formatoptions"=>array( "thousandsSeparator" => " ", "defaultValue" => "0")));
...
$grid->renderGrid(...);
...
The following code will format the number to:
"1234" => "1 234"
" " => "0"
"123" => "123"
In case the expected number is not a integer, but number with decimal places - decimalPlaces property should be set to 0 in case to convert to integer, like the following code:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"integer", "formatoptions"=>array( "thousandsSeparator" => " ", "defaultValue" => "0", "decimalPlaces" => "0")));
...
$grid->renderGrid(...);
...
"1234.12" => "1 234"
" " => "0"
"123.65" => "124"
number¶
Format a number according to the following formatoptions properties:
(The default values of these are set in the language file used)
- 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 the source data is empty.
Example:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"number", "formatoptions"=>array( "thousandsSeparator" => " ", "decimalSeparator" => "." "defaultValue" => "0.0", "decimalPlaces" => "1")));
...
$grid->renderGrid(...);
...
will produce:
...
1234.12" => "1 234.1"
" " => "0.0"
"123.65" => "124.7"
currency¶
Format a number to currency according to the following formatoptions properties:
(The default values of these are set in the language file used)
- 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
- prefix - string to be inserted before the number
- suffix - string inserted at end of the number
- defaultValue set the default value if the source data is empty.
Example:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"currency", "formatoptions"=>array( "thousandsSeparator" => " ", "decimalSeparator" => "." "defaultValue" => "$ 0.00", "decimalPlaces" => "2", "prefix" : "$ ", "suffix" => "")));
...
$grid->renderGrid(...);
...
will produce:
"1234.12" => "$ 1,234.12"
" " => "$ 0.00"
"123.65" => "$ 124.65"
date¶
Format date with source format srcformat to a new format defined with newformat according to the following formatoptions properties:
(The default values of these are set in the language file used)
- srcformat is the source format - i.e. the format of the date that should be converted
- newformat is the new output format.
- parseRe is a expression for parsing date strings.
- reformatAfterEdit (default false) determine if the date should be reformatted after edited - i.e after the user changes the date and save it to the grid. The reason for this is that the date has no unformat when used in editiong modules.
- userLocalTime (default false) forces the local time offset to be calculated to the date when inserted into the grid. See more information below.
The local time offset in the date appear in jqGrid in the following situations.
- A Microsoft data serialization is used and the response contain a date string with offset like:
"/Date(700000+0500)/" - The srcformat is set to 'ISO8601Long' and the date value contain Z at end to indicate the UTC time zone
- The option userLocalTime is set to true and the time offset (in previous calculations) is = 0.
The definition of the date format uses the PHP date formatting
It is possible to use a set of predefined date format - see the mask options in the default date formatting set. In this case it is not needed to set a mask as option - it is needed to input the correct string defined in this property. See examples below
Examples:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"date", "formatoptions"=>array( "srcformat" => "Y-m-d", "newformat" => "ShortDate" )));
...
$grid->renderGrid(...);
...
The result from this is :
"2017-03-01" = > 3/1/2012
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"date", "formatoptions"=>array( "srcformat" => "ISO8601Long", "newformat" => "m/d/Y H:i" )));
...
$grid->renderGrid(...);
...
If the current time is + 2 GMT, the result from this is :
"2017-03-01 11:19:22Z" => 03/01/2012 13:19
The below example is equivalent to:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"date", "formatoptions"=>array( "srcformat" => "Y-m-d H:i:s", "newformat" => "m/d/Y H:i", "userLocalTime" => true )));
"2017-03-01 11:19:22" => 03/01/2012 13:19
email¶
When used directly is added a href with mailto: before the e-mail
The formatter does not have formatoptions properties:
Example:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"email"));
john.smith@yahoo.com => <a href="mailto:john.smith@yahoo.com">john.smith@yahoo.com </a>
link¶
Convert a url to a href tag with the following formatoptions:
- target - The target attribute specifies where to open the linked document. The default value of the target options is empty. When this options is set, we construct a link with the target property set and the cell value put in the href tag.
The possible values of the target attribute can be:
- _blank Opens the linked document in a new window or tab
- _self Opens the linked document in the same frame as it was clicked (this is default)
- _parent Opens the linked document in the parent frame
- _top Opens the linked document in the full body of the window
- framename Opens the linked document in a named frame
Example:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"link", "formatoptions" => array( "target" => "_blank" )));
http://www.guriddo.net => <a href="http://www.guriddo.net" target="_blank">http://www.guriddo.net</a>
showLink¶
This formatter is the same as the link one, with possibility to add additinal parameters to the link. The following formatoptions properties can be used:
- baseLinkUrl is the link used
- 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 - specifies where to open the linked document
- idName is the first parameter that is added after the showAction. By default, this is id
Example
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"showLink", "formatoptions" => array( "baseLinkUrl" => 'http://myserver.com/', "showaction" => 'editrecord.php', "addParam" => '&action=edit',"idName" => 'id', "target" => "_blank" )));
...
if the cell content is Edit Record and the row id = 10, then
Edit Record => <a href="http://myserver.com/editrecord.php?id=10&action=edit" target="_blank">Edit Record</a>
checkbox¶
Creates a checkbox element. The checkbox is not checked if the source cell value is one of the following: false, f, 0, no, n, off, undefined.
Only one format option is available:
- 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.
Example:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"checkbox", "formatoptions"=>array("disabled" => false )));
true => <input checked="checked" value="true" offval="no" type="checkbox">
Special Formatters¶
We have two special formatters type which perform useful transformations. Actually these formatters use PHP method to perform the needed transformations.
Formatter select¶
The select type is not real select. This is used when we display data in the grid and/or use editing module and have edittype:'select'. The formatter is useful if the data contain key (or code), but we want to display in the grid, the value related to this code or key. The same apply to table field on which we want to relate other description.
The method which construct this special formatter is called setSelect
...
/**
*
* Construct the select used in the grid. The select element can be used in the
* editing modules, in formatter or in search module
* @param string $colname (required) valid colname in colModel
* @param 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
* minimum two fields. The first is the key and the second is the value which will
* be displayed in the select
* @param boolean $formatter determines that the select should be used in the
* formatter of type select. Default is true
* @param boolean $editing determines if the select should be used in editing
* modules. Default is true
* @param boolean $seraching determines if the select should be present in
* the search module. Default is true.
* @param array<string> $defvals Set the default value if none is selected. Typically this
* is useful in search modules. Can be something like array(""=>"All");
* @param string $sep The default separator when select is build
* @param string $delim The default delimiter when select string is build
* @return boolean
*/
public function setSelect($colname, $data, $formatter=true, $editing=true, $seraching=true, $defvals=array(), $sep = ":", $delim=";" )
{
...
}
The two important parameters are colname and data. Where the colname should be a valid name from colModel. This mean that setColModel method should be called before this method.
Example:
...
// Create the jqGrid instance
$grid = new Guriddo\jqGrid\Render\Render($conn);
...
// Write the SQL Query
$grid->SelectCommand = 'SELECT OrderID, CustomerID, Freight, OrderDate, ShipCity FROM orders';
// set the ouput format to json
...
// Let the grid create the model
$grid->setColModel();
$grid->setSelect('CustomerID', "SELECT CustomerID, CompanyName FROM customers");
In the above example when the grid is created it displays not the customer Id code but the customer name related to this code. When editing or search module is used a select is constructed and display the list of the available customer names. When a post to server is initiated (in edit or search) actually the code is send to the script.
The above example actually construct the following javascript:
<script>
jQuery("#grid_id").jqGrid({
...
colModel : [ {name:'CustometID', formatter:'select', formatoptions : {value:"ALFKI:Alfreds Futterkiste;ANATR:Ana Trujillo Emparedados y helados;ANTON:Antonio Moreno Taquería;..."}}, edittype: "select", editoptions:{value:"...."}, ... ]
...
});
</script>
If for some reason your data contain colon ":" or semicolon ";" these can be replaced in the with your own using the last parameters in the php method $sep and delim.
Formatter actions¶
Formatter actions is a special feature where we prepare e function which add editable butons on every row. To do this it is needed to call the method addCol and set property formatter actions.
The following example demostrates how to use:
$grid = new Guriddo\jqGrid\Render\Render($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT EmployeeID, FirstName, LastName, BirthDate FROM employees';
// Let the grid create the model
$grid->setColModel();
// add formatter actions
$grid->addCol(array(
"name"=>"actions",
"formatter"=>"actions",
"editable"=>false,
"sortable"=>false,
"resizable"=>false,
"fixed"=>true,
"width"=>85,
"formatoptions"=>array("keys"=>true)
), "first");
...
this will produce the following :

The formatter uses the nav property from language file to get some text when hover the buttons and common styleUI property to get the needed icons
The following default parameters are used:
array(
"keys" => false,
"editbutton" => true,
"delbutton" => true,
"editformbutton" => false,
"onEdit" => null,
"onSuccess" => false,
"url" => "",
"extraparam" => array(),
"afterSave" => null,
"onError" => null,
"afterRestore" => null,
"restoreAfterError" => null,
"mtype" => 'POST',
"editOptions" => array(),
"delOptions" => array()
)
Note
If a edit button is activated after the fields are in edit mode we automatically add two additinal buttons - save row and cancel editing. These buttons can not be disabled.
Bellow is a short description of the parameters:
- keys - boolean variable if set to true, then when the user press ESC key the editing is restored without to be saved; when the user press Enter the editing is saved; if the current field (focused) is textarea and Enter key is pressed save is not occurred.
- editbutton - boolean enables or disables the edit button
- delbutton - boolean enables/disables the delete button - see delOptions below
- editformbutton - boolean enables/disable the form edit form to appear instead of inline one - see editOptions below
- onEdit - 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.
- onSuccess - this function is called immediately after the request which save the data to the server 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. Useful to notify the user if the operation is successfully or not.
- url - url where the data should be saved, clientArray can be used for local save.
- extraparam - additional user parameters that can be added to be send to the server
- afterSave - 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. The event is called too when the url is set to 'clientArray'.
- onError - 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 and status. The event is called too when the url is set to 'clientArray'. The event is called either on ajax error or the onSuccess event return false.
- afterRestore - this function is called in after restoring the row (esc key or cancel button). To this function we pass the rowid
- mtype - the method type of posting the data(GET or POST).
- editOptions - array/object with valid editGridRow options in case editformbutton is set to true. See form editing
- delOptions - array/object with valid delGridRow options. See form editing
Custom Formatter¶
You can define your own formatter for a particular column. Usually this is a function. The code written is in Java Script.
The definition of custom function should be done in the current jQuery scope in order to be visible or included from javascript file in the head section of the document.
Below is a example:
<?php
...
$grid ->setColProperty('field', array("formatter"=>"js:currencyFormatter"));
$customCode = <<< CUSTOM
function currencyFmatter (cellvalue, options, rowObject)
{
// do something here
return new_format_value
}
CUSTOM;
$grid->setJSCode( $customCode );
...
?>
To the custom formatter are passed the following parameters:
function myformatter ( cellvalue, options, rowObject )
{
// format the cellvalue to new format
return new_formated_cellvalue;
}
Caution
Note the return in the function. This function should always return a value in order to work correctly.
-
cellvalue - is the value to be formatted
-
options - is an object containing the following element
options : { rowId: rid, colModel: cm, gid : gridId, pos : column_position, styleUI : guiStyle , isExported : boolval, exporttype : type_when_export } where
rowId - is the id of the row,
colModel is the object of the properties for this column getted from colModel array of jqGrid,
gid is the id of the grid,
pos is the position of the column in colModel,
styleUI is the style object,
isExported is a parameter passed only when export occur allowing to make custom formatting when export is in action. The parameter in this case is true and is valid only when export to CSV, Excel or PDF,
exporttype is a string which is available only when the isExported property is true. This indicates the type of the export - can be csv, pdf or excel depending on the export method called.
- rowObject - is a row data represented in the format determined from datatype option. If we have datatype: xml/xmlstring - the rowObject is xml node,provided according to the rules from xmlReader If we have datatype: json/jsonstring - the rowObject is array, provided according to the rules from jsonReader
Unformatting¶
As mentioned in Predefined Formatter chapter 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. Also the methods (like getRowData and getCell) that get data, used this unformat in order to get the original value. The question is: What to do if we use a custom formatter function and want to to have the original value back if we use editing or methods getRowData and getCell?
The answer is: You can use your own custom unformatter function to do that. This function can be used in colModel
<?php
...
$grid ->setColProperty('field', array("formatter"=>"js:currencyFormatter", "unformat"=>"js:unformatCurrency"));
$customCode = <<< CUSTOM
function currencyFmatter (cellvalue, options, rowObject)
{
// do something here
return new_format_value
}
function unformatCurrency (cellvalue, options, cell)
{
return cellvalue.replace("$","");
}
CUSTOM;
$grid->setJSCode( $customCode );
...
To the custom unformat function are passed the following parameters:
- cellvalue - is the value to be unformated (pure text).
- options - is an object containing the following element
options : { rowId: rid, colModel: cm} where rowId - is the id of the row colModel is the object of the properties for this column getted from colModel array of jqGrid - cell - is a jQuery cell object. This object can be used to obtain different things from the cell element - by example jQuery(cellobject).html() can be used to get the html content instead of the text.
Common user formatters¶
In case certain custom formatter/unformatter is used many times in the code it is possible to define the formatter functions one time and use it into the code. The formatter module is created so that it can be easy extended from the developer and doing it so make the development process easy. Below is discussion how to make your own formatter functions to be visible all into the code.
After loading the jqGrid Java Script files you can define in script tag the following (or simple create your own file and include it into the head section)
<script type="text/javascript">
jQuery.extend($.fn.fmatter , {
currencyFmatter : function(cellvalue, options, rowdata) {
return "$"+cellvalue;
}
});
jQuery.extend($.fn.fmatter.currencyFmatter , {
unformat : function(cellvalue, options) {
return cellvalue.replace("$","");
}
});
</script>
The code to define the formatter is like this:
<?php
....
$grid->setColModel(...);
$grid->setColProperty('somefield',array("formatter"=>"currencyFmatter"));
Note that in this case it is not needed to specify the unformat function.
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.