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);
}
});
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.
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.
phpGrid has decent mobile device support. View the below demo on your mobile device such as iOS and Android phone. It’s recommended to set both autowidth and autoheight to true.
Math Operation
It’s possible to perform math operation on numeric columns with a little bit help from Javascript and “jqGridLoadComplete” event handler.
You can even externalize search fields without ever using phpGrid’s integrated or advanced search feature. It’s more work but you have the liberal to put the search box anywhere on the page.
This feature requires no PHP, only a little bit of HTML and Javascript. The filters are sent to server side via AJAX. It then reloads grid with filtered data without refreshing the entire page.
Below code snippet using “orders” table from the previous integrated search example.
* Please note global search feature is only available in Enterprise edition and above.
Multiple Fields Global Search
In phpGrid, we always try to make PHP developer’s life easier. So we made global search super simple! A single function call enable_global_search() enables global search on any searchable columns. You can search in one or more searchable columns. Multiple search terms can be separated by space.
Like the externalize search demo, the search returns data from server side through AJAX and subsequently reloads the grid with newly filtered data without reloading the entire page, except this time is only one line code. No bull.
1 2 3
$dg=new C_DataGrid("SELECT * FROM orders","orderNumber","orders"); $dg->enable_global_search(true); $dg->display();
* Please note this feature is only available in Enterprise & higher edition.
Parameters:
$enable: true or false
Description:
Enables multi-fields global search on any searchable columns. When set to true, search can perform in one or more searchable columns. Multiple search terms are separated by space.
You should specific PHPGRID_DB_TYPE value in conf.php. It can be one of the following strings. The default database type for phpGrid is “mysql”. PHPGRID_DB_TYPE value is case sensitive.
* Local array data source currently is only available to phpGrid Enterprise and higher.
phpGrid now supports local array data source (version 5.5+). No database is required for local data. So it’s NOT necessary to define PHPGRID_DB_* variables in conf.php when using local array. Simply pass a PHP array as the first parameter to the phpGrid constructor. Everything else is virtually the same.
In the below example, the first segment creates a local PHP array, namely $data1, will be used as the data source for phpGrid. The second segment demonstrates passing the $data1 to the phpGrid constructor and call its methods. All existing phpGrid methods can be used the same way as a database-driven datagrid*.
// set data sort type. With data array, we don't have data type information as we usually do with database fields. $dg->set_col_property("quantity",array("sorttype"=>"integer"));// display different time format $dg->set_col_property("cost",array("sorttype"=>"currency"));// display different time format
$dg->set_databar('quantity','blue');
$dg->display();
Screenshot
* Note that master detail, subgrid, export and file uploads are not yet available when using local array data source.
It’s also possible to use JSON string as a data source with one extra step: use json_decode and set the second parameter to true to return the decoded JSON string to an associative array.
Once you have the array, it can be passed to the phpGrid constructor as if it’s a local array data source. This is useful when your data is real-time or loaded from a remote source such as stock quote and RSS etc.
It’s possible to save local array data back a relatiional DB. The technique uses local array as indirect mean to edit complex database query with JOINS, UNION and etc. See KB: Save local array back to database via Ajax
This is a step-by-step tutorial of how to integrate SmartAdmin, or any other Bootstrap them, with phpGrid.
SmartAdmin is a popular Bootstrap admin theme. It has modern flat design and responsive layout. SmartAdmin comes with 5 different versions: Pure HTML, AJAX Version, PHP version, Modular AngularJS, and ASP.NET MVC5 versions. For this example, we use PHP version, and specifically, the PHP Ajax version.
What you will need
Acquire a copy of phpGrid. You can use either the free, phpGrid Lite or get phpGrid full version here.
Get Bootstrap SmartAdmin. Many Bootstrap themes are also available for free on the Internet.
Now that you’ve downloaded both, let’s get started.
1. Folder Structure
As mentioned earlier, we will use SmartAdmin’s PHP version. InsidePHP_version folder, you will find two subfolders, PHP_Ajax_version andPHP_HTML_version. Here, only PHP_Ajax_version folder is copied to web root directory and renamed as smartAdmin_AJAX (see below).
Secondly, save our phpGrid folder in smartAdmin_AJAX as shown. However, you can save it to any folder.
phpgrid bootstrap folder structure
2. Update phpGrid conf.php
Before you begin coding using phpGrid, you must specify database information in conf.php, phpGrid configuration file in which we specify the following values:
Database connection information,
SEVER_ROOT,
THEME
It’s important that we set THEME value as “NONE”. The reason is that we don’t need to provide a jQuery UI theme as Bootstrap already includes a theme. Using two jQuery themes will likely result in CSS conflicts and style inconsistency.
For the purposes of this demo, we will use a MySQL database. In the figure below, you can see an example of the necessary database definitions as they appear in conf.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php define('PHPGRID_DB_HOSTNAME','localhost:3306'); define('PHPGRID_DB_USERNAME','root'); define('PHPGRID_DB_PASSWORD',''); define('PHPGRID_DB_NAME','sampledb'); define('PHPGRID_DB_TYPE','mysql'); define('PHPGRID_DB_CHARSET','utf8'); define('SERVER_ROOT','/smartAdmin_AJAX/phpGrid'); define('THEME','NONE'); // *** MUST SET TO FALSE WHEN DEPLOYED IN PRODUCTION *** define('DEBUG',false); /******** DO NOT MODIFY ***********/ require_once('phpGrid.php'); /**********************************/ ?>
3. Edit Bootstrap lib/config.php
phpGrid requires PHP SESSION. To ensure that the PHP session starts properly, open the file config.php on the SmartAdmin_AJAX/lib/ directory and copy and paste the following text at the very top of the file.
In this demo, we will add a reference call to phpGrid directly in SmartAdminajax/dashboard.php. . This call can be in any file in SmartAdmin ajax folder.
Note the first line that references phpGrid/conf.php.
“orders” is a database table name from our MySQL sample database. You can find the sample MySQL sample database inside phpGrid/examples/SampleDBfolder.
Now visit the following URL to play around with your newly created PHP grid by using functions such as CRUD, search, and export! You can find a complete list of phpGrid demo here.
1
http://<YOUR WEB SERVER>/smartAdmin_AJAX/
5. Add Custom CSS (Optional)
At this point, the installation is complete. However, I refined jqGrid CSS so the final result would be more aesthetically pleasing. Here’s the final version of the CSS. Feel free to use this code on your page.
This is a step-by-step tutorial of how to integrate Laravel PHP framework with phpGrid.
Laravel is a free, open-source PHP web application framework, architected in model–view–controller (MVC) pattern. phpGrid is a standalone CRUD component encapsulating all necessary server and client side scripts and does not require Laravel packaging system for managing dependency.
Laravel requires PHP version 5.4+ and MCrypt PHP Extension. Check your phpinfo to verify PHP version and MCrypt. In tutorial, we will be using free phpGrid Lite version.
Set up Laravel:
The easiest way is to install Laravel is to use Composer. However, installation procedure is outside the scope of this tutorial. Please visit http://laravel.com/docs/ for Laravel installation process. For the demo, we install Laravel folder in web server root directory.
phpGrid Folder Location in Laravel:
It’s common to save third-party libraries to Laravel “app/libraries”. However, the correct place to put phpGrid is actually in Laravel “public” folder. This is because phpGrid is more than jus the eback-end PHP classes but also contains front-end user accessible stylesheets and javascript to render datagrid. Such library must reside in the application’s “public” directory because Laravel public directory is the root directory that is accessible to users when they visit your website.
phpGrid conf.php
You would need to setup the database connection and script path information in file “conf.php”. Since phpGrid resides in “public” folder, Laravel’s front-end root directory, phpGrid SERVER_ROOT value should be “/phpGrid_Lite”. Pay attention to the beginning slash character.
Learn more about SERVER_ROOT and rest of phpGrid system variables here.
Finally, one must create a view file in Laravel “app/views” folder. Since phpGrid is located in Laravel “public” folder, we can reference path to conf.php with Laravel’s public_path() helper function.
This tutorial walkthrough Laravel 5 and Bootstrap 3 theme integration first, then add PHP datagrid. If you have Laravel and Bootstrap theme already up running, you can skip to “Create “dashboard.blade.php” Child Template View”.
Install Laravel 5 (with Composer)
Let’s get started right away. Laravel 5 has the following system requirements. Please note that the Laravel 5 system requirements apply to both the web and the command line. The possibility is that you could be running different versions of PHP in command line and on web server. If that’s the case, fix your php alias to point to the same php executable. Lastly, acquire a copy of phpGrid from download page for later use.
PHP >= 5.4
Mcrypt PHP Extension
OpenSSL PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
It’s highly recommended to use Composer to install Laravel. Laravel, by itself, does not packed with any third party libraries in order to keep it lightweight. It instead relies on Composer for managing dependency. You can learn more on how to install Composer here.
To install Laravel, in command line, traverse to web root (e.g. /www), and execute the following command:
Technically, AdminLTE can work even without Laravel framework. The benefit to integrate it with Laravel is that we can take advantage of MVC routing and views, ultimately result in cleaner, and more importantly, scalable code. The downside is that one must edit each AdminLTE page to covert it to Laravel views, preferably using Blade template. All Blade templates have file extension “.blade.php”.
Convert AdminLTE “starter.html” to Laravel View
In this tutorial, we will covert AdminLTE’s default “starter.html” to Laravel views to host our PHP datagrid.
Download AdminTLE from almsaeedstudio.com, extract, copy folders “bootstrap”, “dist”, “plugins”, and file “starter.html” to “public” folder. “starter.html” will be used as our starting point to create view.
Create a new view named “admin.blade.php” with content copied from “starter.html” we had eariler. Save the new view in “resources/views”. It will be the admin default layout Blade template later can be extended. Note that all Blade templates should use the “.blade.php” extension.
We now need to further slice admin.blade.php so that it contents reusable sub-views. Create a new folder under “resource/views” called “includes”. It will store admin sub-views.
Move <header> section as a new view as header.blade.php. Change any hyperlink or file reference to use Laravel “asset” help function (http://laravel.com/docs/4.2/helpers). Save it “includes” folder.
<header class="main-header"><!-- Logo --> <aclass="logo"href="index2.html"> <!-- mini logo for sidebar mini 50x50 pixels --> <spanclass="logo-mini"><b>A</b>LT</span> <!-- logo for regular state and mobile devices --> <spanclass="logo-lg"><b>Admin</b>LTE</span> </a>
<!-- Header Navbar -->
<nav class="navbar navbar-static-top"><!-- Sidebar toggle button--> <aclass="sidebar-toggle"href="#" data-toggle="offcanvas"> <spanclass="sr-only">Toggle navigation</span> </a> <!-- Navbar Right Menu --> <divclass="navbar-custom-menu"> <ulclass="nav navbar-nav"> <ulclass="nav navbar-nav"><!-- Messages: style can be found in dropdown.less--> <liclass="dropdown messages-menu"><!-- Menu toggle button --> <aclass="dropdown-toggle"href="#" data-toggle="dropdown"> <iclass="fa fa-envelope-o"></i> <spanclass="label label-success">4</span> </a> <ulclass="dropdown-menu"> <liclass="header">You have 4 messages</li> <li><!-- inner menu: contains the messages --> <ulclass="menu"> <ulclass="menu"> <li><!-- start message --> <divclass="pull-left"><!-- User Image --> <imgclass="img-circle"src="{{ asset('dist/img/user2-160x160.jpg') }}"alt="User Image"/></div> <!-- Message title and timestamp --> <h4>Support Team <small><iclass="fa fa-clock-o"></i> 5 mins</small></h4> <!-- The message -->
Why not buy a new awesome theme?</li> </ul> </ul> <!-- end message -->
Save <aside> sidebar section as a new view sidebar.blade.php. Change any hyperlink or file reference to use Laravel “asset” help function. Save it “includes” folder.
</div><!-- /.tab-pane --> <!-- Stats tab content --> <divclass="tab-pane"id="control-sidebar-stats-tab">Stats Tab Content</div><!-- /.tab-pane --> <!-- Settings tab content --> <divclass="tab-pane"id="control-sidebar-settings-tab"> <formmethod="post"> <h3class="control-sidebar-heading">General Settings</h3> <divclass="form-group"> <labelclass="control-sidebar-subheading">
Report panel usage <inputtype="checkbox"class="pull-right"checked/> </label> <p>
Some information about this general settings option </p> </div><!-- /.form-group --> </form> </div><!-- /.tab-pane --> </div> </aside> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <divclass='control-sidebar-bg'></div>
Include newly created sub-views in admin.blade.php (http://laravel.com/docs/5.0/templates).
In admin.blade.php, add the section between sidebar and footer. Copy and past section <div class=”content-wrapper”> where we will host our main content in which phpGrid is also rendered. Also include @yield(‘content’) in <section class=”content”>
Move the required javascript in the bottom of “starter.html” to <head>.
1 2 3 4 5 6 7 8 9 10 11
!– REQUIRED JS SCRIPTS –> <!– jQuery 2.1.4 –> <scriptsrc=”{{ asset(‘plugins/jQuery/jQuery-2.1.4.min.js’)}}”></script> <!– Bootstrap 3.3.2 JS –> <scriptsrc=”{{ asset(‘bootstrap/js/bootstrap.min.js’)}}” type=”text/javascript”></script> <!– AdminLTE App –> <scriptsrc=”{{ asset(‘dist/js/app.min.js’)}}” type=”text/javascript”></script> <!– Optionally, you can add Slimscroll and FastClick plugins. Both of these plugins are recommended to enhance the user experience. Slimscroll is required when using the fixed layout. –>
Almost done. In admin.blade.php, make sure to change any hyperlink or file reference to use Laravel “asset” help function.
Create “dashboard.blade.php” Child Template View
We just made our admin layout by converting “starter.html” to various views and sub-views. “admin.blade.php” will be our parent layout used as a basis for all other admin layouts. All other admin layouts will extend from “admin.blade.php.” $grid is the variable that holds our datagrid passed from route next.
1 2 3 4 5
@extends('admin')
@section('content')
{!! $grid !!}
@endsection
Where Is phpGrid??
So far Much of the walk-through addresses converting AdminLTE to Laravel views.
Everything in Laravel 5 is autoloaded using PSR-4 within the app/ directory. You can also see this in the composer.json file. phpGrid currently does not support namespace for backward compatibility reason. In the future release it will. Without namespace we cannot call our C_DataGrid class in Laravel Controller. The workaround is to directly call phpGrid inside route file. And instead store phpGrid in app/ directory, we keep phpGrid in public folder. So go ahead and download a copy of phpGrid if you have done so, and extract to Laravel “public” folder. Make sure to setup phpGrid configuration in its conf.php file.
In Laravel route file “app/Http/routes.php”, add the following:
$grid=$dg->get_display(true);// do not include required javascript libraries until later with with display_script_includeonce method. return view(‘dashboard’,[‘grid’ =>$grid]); });
That’s it. You should be able to run the demo.
Where is the controller?
Hope this tutorial will get youn a jump started using phpGrid with Laravel. Now you are probably going to ask where is Laravel controller for our view? The answer is there is simply not needed at this point, at least not for our datagrid. The route we created in previous step essentially does that for us. In a perfect world, we would fancy controller being the only place to handle logic and pass information to views for rendering. Current lack of namespace prohibits calling phpGrid library inside Laravel Controller. However, it’s planned to add namespace in the future.
It’s easy to integrate CodeIgniter with phpGrid. CodeIgniter is a popular, open source PHP framework loosely based on MVC development pattern for use in building dynamic web sites. Out of box, phpGrid is a read-to-use PHP datagrid solution.
Install CodeIgniter
Download CodeIgniter here. CodeIgniter is installed in four steps:
Unzip the package.
Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.
Install phpGrid
Download phpGrid here. Install phpGrid in the followings steps:
Unzip the phpGrid download file.
Upload unzipped phpGrid folder to “aplication/libraries” folder.
Complete the installation by configuring the conf.php file. For instructions on how to do this, see setup phpGrid configuration.
CodeIgniter Controller
For the sake of this tutorial, we will directly modify the default controller file “Welcome.php”. In practice, it can be any existing or new controller file. Pay attention that we did not initialize the class using the standard:
1
$this->load->library('someclass');
Where someclass is the file name, without the “.php” file extension. Instead we simply include phpGrid configuration file. APPPATH constant is path to your application folder. Unlike Laravel framework, you can directly include PHP classes and working with them. phpGrid is a complex component and composed of multiple classes.
require_once(APPPATH.'libraries/phpGrid_Lite/conf.php');// APPPATH is path to application folder $data['phpgrid']=new C_DataGrid("SELECT * FROM Orders","orderNumber","Orders");//$this->ci_phpgrid->example_method(3);
$this->load->view('show_grid',$data); }
Note the last line is our new view we are about to create. The view is called “show_grid”.
Create View
Our view is very simple in this tutorial. All you have to do is to put <?php $phpgrid->display(); ?> somewhere in the view. Learn more about creating a basic PHP grid here.
You can also use Google Spreadsheet as a data source to populate your datagrid. In this tutorial, you will learn how to create a shared Google Spreadsheet and share it in comma-separated values (CSV) format. Note that array data source is a feature only available in Enterprise license.
Loading from Google Spreadsheet is straight forward as if loading from a local array data source. first of all, in order for our system to download the Google Spreadsheet in CSV format, you need to follow this guide to generate a download link for the CSV file of Google Drive Spreadsheet.
Open a Google Drive Spreadsheet
Open an existing Google Spreadsheet like the following:
Share the Google Spreadsheet
Click Change… to change access settings,
Click “Public on the Web” or “Anyone with the link”,
Click Save
Publish on the Web
Click File >Publish on the Web
Click “Advanced”, and make sure “Automatically republish when changes are made” is checked.
Choose “Comma-separated values (.csv) as output type in Link type drop-down
Finally copy document link.You should have a link similar to the following with output=csv in URL parameter: https://docs.google.com/spreadsheets/d/1IvbMsUZTCdY7duciT3lWSXHPP_qPDG8FrJl8dq1ZbI/pub?output=csv
Start Coding
First of all, we need to massage our data into format that phpGrid can recognize. You can read more about it in local array data data example. In our Google Spreadsheet sample file, the first row contains the header information. We will also extract that row as the name for each column in datagrid. After formatting, the data become accessible as if it is a local file.
Finally, we add our phpGrid code. We first add title to each datagrid column. We also enable auto filter in integrated search, and lastly give it a new look using our premium theme “aristo”.
Please note that search auto filter is a new feature that dynamically generates filter drop-down in integrated toolbar search based on column’s unique values. Since Google Spreadsheet does not send separate column header in its .csv format, here we use column index array, e.g. array(1,2,3,5), as our search auto filter.
This tutorial will walk you through the integration of the Zend Framework 2 and phpGrid. Zend Framework (ZF) is a popular open source, MVC web application framework created and maintained by Zend Technologies, the company behind PHP programming language.
Install Zend Framework Skeleton Application
The best way to create a Zend Framework project is to use Composer. This tutorial uses Zend Framework version 2.4 that requires PHP version 5.5 and above. In this tutorial, you will start by installing the ZendSkeletonApplication from Github using Composer. It’s a great starting point to begin a blank Zend project.
Before installing phpGrid, in the ZF2 that we installed in the previous step, find the “vendor” folder, and create a new directory named “phpcontrols” inside. Then download phpGrid and extract the zip file into the “phpcontrols” folder we just created.
You should have folder structure similar to the following screenshot:
Configuring conf.php file in phpGrid
Complete the phpGrid installation by configuring its database information in file “conf.php” inside phpGrid folder. For complete instructions on how to do this, see phpGrid configuration online documentation. phpGrid comes with several sample databases. You can find them under “examples/SampleDB” folder. We will use the MySql sample database for Zend Framework integration tutorial.
Modify composer.json
Before start coding, we need to register our phpGrid library in Zend Framework autoloader by adding autoload files keys in composer.json. Autoloader ensures that any PHP external libraries and components can be easily referenced anywhere in PHP code without using the traditional require or php include function.
Below is a copy of our composer.json. It could be slightly from what you have, and notice the autoload value.
Finally, update composer after making the changes. In the project root, run the following
1
composer update
Start coding!
Open file “module/Application/view/application/index/index.phtml“. Assuming that you have installed phpGrid sample database installed,. Somewhere in index.phtml, add the following:
1 2 3
$dg=new \C_DataGrid("SELECT * FROM orders","orderNumber","orders"); $dg->enable_edit("INLINE","CRUD"); $dg->display();
Note that if you are under a namespace while creating the object, you must use the “\” (root namespace), otherwise you will use the phpGrid class under the current namespace.
That’s all there it is. You should be able to run the demo.
You are probably wondering, “Where is the ZF controller and model for phpGrid?” The answer is they are simply not required. phpGrid encapsulates both database access routines and display so you don’t have to worry about them. It does those magic “behind the scene”.
After months of hard work, phpGrid now finally has native IBM DB2 database support! phpGrid’s DB2 support has been spotty in the past, owing to the fact that the ADOBdb data access library it uses legacy IBM DB2 driver. A new PDO data access class has been implemented specifically for DB2.*
We tried uber-hard to make sure that the existing phpGrid API stayed the same. The changes made were essential, and they are transparent to our users. Simply use the new database by typing “pdo_odbc_db2” as the PHPGRID_DB_TYPE value in conf.php, and viola, you are done! Everything else stays the same.
IBM i Developers, Rejoice.
A large number of IBM i developers have been working with DB2, the IBM’s Relational Database Management System (RDBMS). You can use phpGrid as your data management tool in your IBM i environment because the PHP runtime is already preloaded with IBM i. This means, they can get a super-charged datagrid with built-in CRUD capability, up and working very quickly without much knowledge of the ins and outs of PHP.
The DB2 was fully tested in IBM DB2 Express-C. It requires PDO_ODBC extension through unixODBC. As of PHP 5.1, PDO_ODBC is included in the PHP source. You verify using phpinfo. Both web server and DB2 must be on the same server. If you have trouble install unixODBC, I suggest install Zend Server (free) to easily installs PDO_ODBC (unixODBC) extension through its wonderful admin dashboard. Lastly, set up the DSN in odbc.ini and odbcinst.ini configuration files using DB2 db2sampl database.
*Note that DB2 support is available with an Enterprise license.
A sample of conf.php in phpGrid. Notice the putenv environment variable settings.
conf.php
1 2 3 4 5 6 7 8 9 10
define('PHPGRID_DB_HOSTNAME','localhost');// database host name define('PHPGRID_DB_PORT','50000');// database host name define('PHPGRID_DB_USERNAME','db2inst1');// database user name define('PHPGRID_DB_PASSWORD','xxxxxxxx');// database password define('PHPGRID_DB_NAME','SAMPLE');// database name or DSN name (cataloged) define('PHPGRID_DB_TYPE','pdo_odbc_db2');// database type define('PHPGRID_DB_CHARSET','utf8');// ex: utf8(for mysql),AL32UTF8 (for oracle), leave blank to use the default charset
In the previous phpGrid Laravel 5 tutorial part 1, we have chosen to leave the phpGrid code inside route.php. In this tutorial, we will improve upon what we have learned in part 1. We will move the phpGrid folder out of public directory and move it to app folder instead; and then we will undo changes in route.php and add phpGrid code inside controller file.
Let’s get started.
Move phpGrid folder into Laravel \app folder
Technically, you can put a class itself anywhere you want within \app folder. I personally prefer to create a separate one such as app\Libraries for any external libraries.
Make sure to udpate SERVER_ROOT value in conf.php. See below folder structure
Undo changes made in route.php
In route.php, undo the dashboard route changes back we made in Part I back to default. We will be moving the phpGrid code to controller as it is the properly place to organize your application behaviors.
A better way to include an external library in Laravel 5
Apparently it’s possible to include PHP classes without namespace in controller. Strictly speaking, we will be using the “\” (root namespace) as the default namespace.
First of all, let’s get autoloader to work.
Modify composer.json
Before start coding, we need to register our phpGrid library in Laravel autoloader by adding autoload files keys in composer.json. Autoloader ensures that any PHP external libraries and components can be easily referenced anywhere in PHP code without using the traditional require or php include function.
Below is a copy of our composer.json. It could be slightly from what you have, and notice the autoload value.
Notice: if you make these changes to composer.json file, don’t forget to run composer dump-autoload or composer update for changes to take effect.
1
composer dump-autoload
– OR –
1
composer update
Modify DashboardController.php
Open DashboardController.php in “app\Http\Controllers” folder, and change the index() function to the following. Note that if you are under a namespace while creating the object, you must use the “\” (root namespace), otherwise you will use the phpGrid class under the current namespace.
* Pivot grid is only available in Enterprise version 6.6+.
Parameter(s):
$configuration: Pivot configuration array parameter. Please see pivot demo for more information.
Description:
Create pivot grid from an existing datagrid. It renders the regular datagrid first, and then pivots based on configuration settings. In essence, phpGrid creates pivot in the client side browser without requiring any server side resource.
Remark:
You will first see a loading icon while pivot is rendered before it is displayed. It’s by design.
The example demonstrates date column formatting using functions set_col_date, set_col_datetime, set_col_property(…formatter”=>”date”,…). If you have trouble with date format, most likely you will find answer here. Also pay attention to inline comments.
$dg=new C_DataGrid("SELECT * FROM orders","orderNumber","orders");
// Method 1: change date display and datepicker display (used for edit) to Spanish date $dg->set_col_date("orderDate","Y-m-d","m/d/Y","m/d/yy");
// Method 2: change date display and datepicker display (used for edit) to Spanish date $dg->set_col_property("requiredDate", array("formatter"=>"date", "formatoptions"=>array("srcformat"=>"Y-m-d","newformat"=>"m/d/Y"), "editoptions"=>array( "dataInit"=>"function(el) {
$(el).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'm/d/yy'
})
}")));
// Method 3: Display using jQuery Datetimepicker extension replacing the built-in datepicker plus option time picker $dg->set_col_datetime("contractDateTime","Y-m-d H:i","m/d/Y H:i","m/d/Y H:i");
// Display time only. No date. It cannot be edited, so we also made it hidden on the edit form. $dg->set_col_property("shippedDate", array("formatter"=>"date", "formatoptions"=>array("srcformat"=>"ISO8601Short","newformat"=>"g:i A"), 'editable'=>false,'hidedlg'=>true));
phpGrid now supports pivot grid through a simple function “set_pivotgrid“.
Simply passing the pivot configration array parameter simialr to the following such as xDimension and yDimension, aggregates as well as footer and header in the array.