Advanced Methods Archives | phpGrid - PHP Datagrid Create PHP grids in minutes, not hours. Sat, 29 Mar 2025 03:48:09 +0000 en-US hourly 1 CodeProjecthttps://wordpress.org/?v=7.0.3 129966043 Simple Shopping Cart Using the Action Column https://phpgrid.com/example/simple-shopping-cart-using-the-action-column/ Wed, 16 Jan 2019 00:11:48 +0000 http://phpgrid.com/?p=9500

In the action column, it is possible to add additional links or buttons beside the CRUD buttons with phpGrid custom JSON property “cust_prop_jsonstr” For example, you can use “cust_prop_jsonstr to insert “add to cart” button via the property called actionsNavOptions. In the example below, the onClick event call back function simply returns an alert message […]

The post Simple Shopping Cart Using the Action Column appeared first on phpGrid - PHP Datagrid.

]]>

In the action column, it is possible to add additional links or buttons beside the CRUD buttons with phpGrid custom JSON property “cust_prop_jsonstr” For example, you can use “cust_prop_jsonstr to insert “add to cart” button via the property called actionsNavOptions.

In the example below, the onClick event call back function simply returns an alert message with the rowid. That is only the tip of the iceberg. By using Ajax, the options.rowid could return the unique key of the row to a server-side script for much more complex workflow such as add to cart, add new users etc.

1
2
3
// Always include namespace and conf.php on TOP of the script.
use phpCtrl\C_DataGrid;
require_once("/path/to/conf.php");
$dg = new C_DataGrid("SELECT * FROM orders", "orderNumber", "orders");
$dg->cust_prop_jsonstr = 'actionsNavOptions: {
                addUsericon: "fa-user-plus",
                addUsertitle: "Add user",
                deleteUsericon: "fa-user-times",
                deleteUsertitle: "Delete user",
                addToCarticon: "fa-cart-plus",
                addToCarttitle: "Add item to the cart",
                custom: [
                    { action: "addUser", position: "first", onClick: function (options) { alert("Add user, rowid=" + options.rowid); } },
                    { action: "addToCart", position: "first", onClick: function (options) { alert("Add to Cart, rowid=" + options.rowid); } },
                    { action: "deleteUser", onClick: function (options) { alert("Delete user, rowid=" + options.rowid); } }
                ]
            },';
$dg->add_column("actions", array('name'=>'actions', 
	'sortable'=>false,
    'index'=>'actions',
    'width'=>'150',
    'formatter'=>'actions',
    'formatoptions'=>array('keys'=>true, 'editbutton'=>true, 'delbutton'=>true)),'Actions');
$dg->enable_edit();
$dg -> display();

Online Demo (Scroll all the way to the right to view the Action column)

The post Simple Shopping Cart Using the Action Column appeared first on phpGrid - PHP Datagrid.

]]>
9500
Save Data in Virtual Column https://phpgrid.com/example/save-data-in-calculatedvirtual-column-to-database/ Tue, 24 Feb 2015 08:16:39 +0000 http://phpgrid.com/?p=3500 It’s possible to save data in virtual column to database.To save data in virtual column or calculated column back to database, you can use jqGridAddEditAfterSubmit event (FORM edit only) to post data to another script through a separate Ajax call. The catch is you need to supply your own save data script. Just iterate the $_POST variables […]

The post Save Data in Virtual Column appeared first on phpGrid - PHP Datagrid.

]]>
It’s possible to save data in virtual column to database.To save data in virtual column or calculated column back to database, you can use jqGridAddEditAfterSubmit event (FORM edit only) to post data to another script through a separate Ajax call. The catch is you need to supply your own save data script. Just iterate the $_POST variables and call appropriate functions to save posted data to database. Should be fairly simple to do.

Below is the code snippet. Replace “orders” with your own table name please. You need to implement save_virtual_column.php to save virtual column data to another page after submit through another Ajax call

jqGridAddEditAfterSubmit works only in FORM edit mode.
X
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$afterSubmit = <<<AFTERSUBMIT
function (event, status, postData)
{
    selRowId = $("#orders").jqGrid ('getGridParam', 'selrow');
    virtual_data1 = $("#orders").jqGrid("getCell", selRowId, 'total');   // data in virtual column
    virtual_data2 = $("#orders").jqGrid("getCell", selRowId, 'foo');
    console.log('going to post virtual column data ' + virtual_data1 + ', ' + virtual_data2 + ' to another page through a separate AJAX call');
    $.ajax({ url: 'save_virtual_column.php',
        data: {v_data1: virtual_data1, v_data2: virtual_data2}, // replace customerNumber with your own field name
        type: 'post',
        success: function(output) {
                    alert(output);
                }
        });

}
AFTERSUBMIT
;
$dg->add_event("jqGridAddEditAfterSubmit", $afterSubmit);

The screenshot illustrates values in virtual columns named “total” and “foo” are saved after users submit form. It posts to a file named “save_virtual_column.php” with posted form data v_data1, v_data2.

 

save_virtual_column_data

 

This is also a good technique to save any other additional data to database because it does not require modifying edit.php. Note that jqGridAddEditAfterSubmit works only in FORM edit mode.

The post Save Data in Virtual Column appeared first on phpGrid - PHP Datagrid.

]]>
3500
Column Methods https://phpgrid.com/example/column-methods/ Sat, 20 Apr 2013 22:34:45 +0000 http://phpgrid.com/?p=2453 Version 5.5.5 introduced set_grid_method() method. You can use this method to call any jqGrid javascript method that can perform actions on the grid as a whole. However, it’s not possible to manipulate the grid on a row or cell level using set_grid_method. The example below demonstrates set_grid_method to grouping header by calling the jqGrid “setGroupHeader” […]

The post Column Methods appeared first on phpGrid - PHP Datagrid.

]]>
Version 5.5.5 introduced set_grid_method() method. You can use this method to call any jqGrid javascript method that can perform actions on the grid as a whole. However, it’s not possible to manipulate the grid on a row or cell level using set_grid_method.

The example below demonstrates set_grid_method to grouping header by calling the jqGrid “setGroupHeader” method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use phpCtrl\C_DataGrid;
require_once("/file/path/to/conf.php");  

$dg = new C_DataGrid("SELECT * FROM payments", "customerNumber", "orders");

$dg->set_col_width("customerNumber", 30);
$dg->set_col_width("checkNumber",50);
$dg->set_col_width("amount",50);

$dg->set_grid_method('setGroupHeaders',
                        array(
                            array('useColSpanStyle'=>true),
                            'groupHeaders'=>array(
                            array('startColumnName'=>'customerNumber',
                            'numberOfColumns'=>2,
                            'titleText'=>'Numbers Header')
                        )));

$dg->display();

See Live Example!

The post Column Methods appeared first on phpGrid - PHP Datagrid.

]]>
2453
Custom Data Validation https://phpgrid.com/example/custom-data-validation/ Tue, 08 Jan 2013 23:40:33 +0000 http://phpgrid.com/?p=2386 phpGrid automatically does data validation based on database data type such as a string cannot be used when the data type is integer and non-null field must have a value. It’s sufficient in most everyday use cases. Client Side Validation Starting version 5.5, users can use their own validation javascript function for more complex data […]

The post Custom Data Validation appeared first on phpGrid - PHP Datagrid.

]]>
phpGrid automatically does data validation based on database data type such as a string cannot be used when the data type is integer and non-null field must have a value. It’s sufficient in most everyday use cases.

Client Side Validation

Starting version 5.5, users can use their own validation javascript function for more complex data edit rules. Use set_col_customrule() method is created for this purpose. Below is an example of three Javascript functions used for custom validation. You can even compare data among multiple columns. The Javascript functions in example is rather over simplified, but you get the picture. Once obtained the cell value, you can develop even more complex Javascript function to validation your data.

Server Side Validation

For server side data validation, in your javascript function, use jQuery.ajax to call your server side validation routine. An example of Ajax call can be found on Hyperlink to Call JavaScript Function example

Make sure that you play around with the live example after the code snippet!

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// validation (FORM and INLINE)
function price_validation1(value, colname) {
    if(value < 0){
       return [false,colname + " must be zero a positive integer."];
    }
    return [true, ""];
}

// validation (INLINE only). Note the technique to obtain a specific cell value
function price_validation2(value, colname) {
    var rowId = jQuery("#products").jqGrid('getGridParam','selrow');
    if(parseFloat(jQuery('#' + rowId + '_' + 'buyPrice').val()) >  parseFloat(jQuery('#' + rowId + '_' + 'MSRP').val()))
        return [false,"buyPrice must be equal or less than MSRP."];
    else
        return [true,""];
}

// validation (FORM only). Note the technique to obtain a specific cell value is different from INLINE edit.
function price_validation3(value, colname) {
    if(parseFloat(jQuery('#buyPrice').val()) >  parseFloat(jQuery('#MSRP').val()))
        return [false,"buyPrice must be equal or less than MSRP."];
    else
        return [true,""];
}

PHP

1
2
3
4
5
6
7
8
9
// Always include namespace and conf.php on TOP of the script.
use phpCtrl\C_DataGrid;
require_once("/path/to/conf.php");  

$dg = new C_DataGrid("SELECT * FROM products", "productCode", "products");
$dg->enable_edit('FORM');
$dg->set_col_customrule('quantityInStock', 'price_validation1');
$dg->set_col_customrule('buyPrice', 'price_validation3');
$dg->display();

See Live Example! (Try set quantityInStock to a negative number, and buyPrice < MSRP.)

The post Custom Data Validation appeared first on phpGrid - PHP Datagrid.

]]>
2386
Virtual/Calculated Column https://phpgrid.com/example/virtual-column-aka-calculated-column/ Tue, 08 Jan 2013 23:18:48 +0000 http://phpgrid.com/?p=2383 Starting version 5.5, you can now add virtual column, AKA calculated column, to your existing datagrid. Virtual, by definition, is that it doesn’t exist in the database table. It’s a calculated field created from other columns. The virtual columns are added to the END of the existing datagrid. phpGrid only adds a “virtual” column and […]

The post Virtual/Calculated Column appeared first on phpGrid - PHP Datagrid.

]]>
Starting version 5.5, you can now add virtual column, AKA calculated column, to your existing datagrid. Virtual, by definition, is that it doesn’t exist in the database table. It’s a calculated field created from other columns. The virtual columns are added to the END of the existing datagrid.

phpGrid only adds a “virtual” column and does NOT change the database table structure. Front-end user should not be able to add/change a column in your database table structure. It should be done only by a very smaller number of people such as DBA, and ultimately through a back-end database administration program.

It’s important that virtual column name is NOT an existing database column name used by PHP datagrid.
X
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use phpCtrl\C_DataGrid;
require_once("/path/to/conf.php");  

$dg = new C_DataGrid("SELECT * FROM orders", "orderNumber", "orders");
$dg->enable_edit('INLINE');

// calculated value to be displayed in the virtual column
// n1 stores column 1 value, n2 stores column 7 value..and so on.
$col_formatter = <<<COLFORMATTER
function(cellvalue, options, rowObject){
    var n1 = parseInt(rowObject[0],10),      
        n2 = parseInt(rowObject[6],10);      
    return n1+n2;
}
COLFORMATTER;

$dg -> add_column(
        'total',
        array('name'=>'total',
            'index'=>'total',
            'width'=>'360',
            'align'=>'right',
            'sortable'=>false,
            'formatter'=>$col_formatter),
        'Total (Virtual)');
$dg->display();

See Live Example! (The last two columns “Total” and “Foo” are virtual.)

The post Virtual/Calculated Column appeared first on phpGrid - PHP Datagrid.

]]>
2383
Column Property https://phpgrid.com/example/column-property/ Sun, 15 Jul 2012 19:33:21 +0000 http://phpgrid.com/?p=2189 You can now directly manipulate individual column properties without using helper set_col_* functions such as set_col_format() and set_col_readonly() .  This is suitable for users who are already familiar with jqGrid colMdel API (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options). The new column property method does not replace existing helper functions. It should be used beside by side with the existing set_col_* helper functions. […]

The post Column Property appeared first on phpGrid - PHP Datagrid.

]]>
You can now directly manipulate individual column properties without using helper set_col_* functions such as set_col_format() and set_col_readonly() .  This is suitable for users who are already familiar with jqGrid colMdel API (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options).

The new column property method does not replace existing helper functions. It should be used beside by side with the existing set_col_* helper functions.

1
2
3
4
5
6
7
8
9
10
11
use phpCtrl\C_DataGrid;
require_once("/path/to/conf.php");  

$dg = new C_DataGrid("SELECT * FROM orders", "orderNumber", "orders");
$dg -> set_row_color('yellow', 'blue', 'lightgray');
$dg -> set_col_property("orderNumber", array("name"=>;"Order Number", "width"=>;40));
// display only time
$dg -> set_col_property("orderDate",
                        array("formatter"=>;"date",
                              "formatoptions"=>;array("srcformat"=>;"ISO8601Short","newformat"=>;"g:i A"));
$dg -> display();

See Live Example!

The post Column Property appeared first on phpGrid - PHP Datagrid.

]]>
2189
Custom Event Handler https://phpgrid.com/example/custom-event-handler/ Sun, 15 Jul 2012 05:09:07 +0000 http://phpgrid.com/?p=2179 phpGrid supports custom event handlers using the add_event() method. The event handlers are essentially JavaScript functions or they can be enclosed with PHP heredoc. Events used in examples jqGridSelectRow jqGridrowattr jqGridAddEditBeforeSubmit jqGridAddEditAfterSubmit 12345678910111213// Always include namespace and conf.php on TOP of the script. use phpCtrl\C_DataGrid; require_once("/path/to/conf.php"); $dg = new C_DataGrid("SELECT * FROM orders", "orderNumber", "orders"); […]

The post Custom Event Handler appeared first on phpGrid - PHP Datagrid.

]]>
phpGrid supports custom event handlers using the add_event() method. The event handlers are essentially JavaScript functions or they can be enclosed with PHP heredoc.

Events used in examples

  • jqGridSelectRow
  • jqGridrowattr
  • jqGridAddEditBeforeSubmit
  • jqGridAddEditAfterSubmit
1
2
3
4
5
6
7
8
9
10
11
12
13
// Always include namespace and conf.php on TOP of the script.
use phpCtrl\C_DataGrid;
require_once("/path/to/conf.php");

$dg = new C_DataGrid("SELECT * FROM orders", "orderNumber", "orders");

$dg->add_event("jqGridSelectRow", 'onSelectRow');
$dg->add_event("jqGridrowattr", 'onRowAttr');
$dg->add_event("jqGridAddEditBeforeSubmit", 'beforeSubmit');
$dg->add_event("jqGridAddEditAfterSubmit", 'afterSubmit');
$dg->enable_edit('FORM');

$dg -> display();

In this particular demo, using “jqGridAddEditAfterSubmit” event handler, you will also be able to obtain the auto-generated ID value during insert/add from the “status” parameter in the Javascript callback function.

Here’s the JSON value returned from “status” where its “responseText” contains the newly auto-generated ID value.

1
2
3
4
5
6
7
8
{
  readytate:4,
  responseText:{
    id:8
  },
  status:200,
  statusText:OK
}

custom_event_addeditaftersubmit-console

Event Handlers in JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<script>
function onSelectRow(status, rowid)
{
    alert('event 1');
    console.log(rowid);
    console.log(status);

// ******* Example to redirect a new URL when select a row  *******
// orderNumber = $('#orders').jqGrid('getCell',rowid,'orderNumber');
// customerNumber = $('#orders').jqGrid('getCell',rowid,'customerNumber');
// window.location = encodeURI("http://example.com/" + "?" + "orderNumber=" + orderNumber + "&amp;customerNumber="+customerNumber);
}

function onSelectRow2(status, rowid)
{
  alert('event 2');
  console.log("here");
}

function onRowAttr(rowData, inputRowData)
{
    return rowData.status === "OnHold" ? {style: "background-color:blue"} : {};
}

// post data another page after submit
function beforeSubmit(event, postData)
{
    console.log(event);
    console.log(postData);

    alert('beforeSubmit: post customerNumber ' + postData.customerNumber + ' to another page through AJAX call');

    $.ajax({ url: 'test.php',
        data: {custNum: postData.customerNumber}, // replace customerNumber with your own
            type: 'post',
            success: function(output) {
                alert(output);
        }
    });
}

// post data another page after submit
function afterSubmitFunc(event, status, postData)
{
    $.ajax({ url: '/my/site',
        data: {custNum: postData.customerNumber}, // replace customerNumber with your own field name
        type: 'post',
        success: function(output) {
                    alert(output);
                }
        });
}
</script>

See Live Example! (click on any row to trigger event)

 

Also see Cell Select Custom Event Examples and entire custom events examples on KB.

The post Custom Event Handler appeared first on phpGrid - PHP Datagrid.

]]>
2179