CodeProject Archives | phpGrid - PHP Datagrid https://phpgrid.com/category/codeproject/ Create PHP grids in minutes, not hours. Fri, 06 Dec 2024 04:13:41 +0000 en-US hourly 1 CodeProjecthttps://wordpress.org/?v=7.0.3 129966043 Transform HTML Table into Card View Using Nothing But CSS https://phpgrid.com/blog/transform-html-table-into-card-view-using-nothing-but-css/ Fri, 25 Oct 2024 00:26:37 +0000 https://phpgrid.com/?p=10187

I’d like share a recent experiment that explores how to transform a plain, old-fashioned HTML table into a dynamic card view, going beyond the traditional rows and columns. Start With a Simple HTML Table Let’s begin with a simple HTML table such as the following. 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051<table>   <thead>     <tr>       <th>Company</th> […]

The post Transform HTML Table into Card View Using Nothing But CSS appeared first on phpGrid - PHP Datagrid.

]]>

I’d like share a recent experiment that explores how to transform a plain, old-fashioned HTML table into a dynamic card view, going beyond the traditional rows and columns.

Start With a Simple HTML Table

Let’s begin with a simple HTML table such as the following.

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
<table>
  <thead>
    <tr>
      <th>Company</th>
      <th>Contact</th>
      <th>Country</th>
    </tr>
  </thead>
  <tbody>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>  
  <tr>
    <td>Alfreds </td>
    <td>Maria </td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro  </td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Alfreds </td>
    <td>Maria </td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial </td>
    <td>Francisco </td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Alfreds </td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial </td>
    <td>Francisco </td>
    <td>Mexico</td>
  </tr>
  </tbody>
</table>

It looks like this when rendered in browser.

plain table

Just another html table with rows and columns. Nothing fancy.

So how can we transform the traditional rows and columns layout into something more dynamic?

Discover the Power of CSS Grid

Tables don’t have to be boring. With a few simple CSS tricks, you can easily transform a traditional HTML table into a sleek list or card view.

The best part? No JavaScript, just pure CSS!

CSS grid has been an W3C Candidate Recommendation Draft since 2007, however, it has been adopted by the recent versions of all current major browsers.

CSS grid is designed for both rows and columns, making it ideal for complex layouts such as table. It allows you to manage both horizontal and vertical alignments simultaneously, which gives you much more control than Flexbox, which is primarily one-dimensional (row or column).

CSS Grid Properties to Use

  1. Use CSS grid layout for <thead> and <tbody>.
  2. Use CSS display property and set all <td> to be block elements
1
2
3
4
5
6
table tbody, table thead {
  display: grid;
}
table td {
  display: block;
}

With the CSS above, our plain HTML table already magically transforms into a responsive list view, displaying each record neatly in a single column.

table single column

It’s looking good but a bit chaotic! Let’s sprinkle on some CSS borders to give each row in our list a little breathing room.

1
2
3
table, th, tr {
  border: 1px solid black;
}

There you go. Not too shabby for a list view created without a single line of JavaScript!

table singl column with border

Now we got a nice list made from an old-fashioned html table, how do we turn that nice list into a card view?

Spoiler alert: just sprinkle on a few more lines of CSS!

Transform List into Card View

Our final card trick to transform table into cards is to use CSS grid property grid-template-columns:

1
2
3
4
table tbody {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}

grid-template-columns is a CSS property used in the CSS Grid layout to define the structure of the grid’s columns. It specifies the number of columns, their widths, and how the space within the grid is divided.

With the repeat() function, the first parameter lets us decide how many columns we want—let’s say 4. The second parameter tells those columns how big to be—1fr, or one fraction of the available space. It’s like telling your columns to all get an equal slice of the space pie.

Our final card view

final card view

Take a moment to explore the code and see the results for yourself over on CodePen. It’s the perfect place to experiment and play around with CSS grid transformations.

Keep in mind that CSS Grid is also responsive, providing developers with enhanced control over how layouts adjust and reflow across various screen sizes and devices.

Optional: Adding data-label to card view

While the card view is visually appealing, it lacks the clarity of column information, leaving users to guess the data represented in each card.

By incorporating a touch of JavaScript, we can seamlessly add data labels for each column, enhancing the association between the labels and their corresponding cells.

1
2
3
4
5
6
7
8
9
10
11
12
// Store each column header to array
var labels = [];
$('table').find('thead th').each(function() {
    labels.push($(this).text());
});

// Add data-label attribute to each cell
$('table).find('tbody tr').each(function() {
    $(this).find('
td').each(function(column) {
        $(this).attr('
data-label', labels[column]);
    });
});

The same code above using ES6 vanilla javascript without jQuery

1
2
3
4
5
6
7
8
9
10
11
12
// Store each column header to array
const labels = [];
document.querySelectorAll('table thead th').forEach(th => {
    labels.push(th.textContent);
});

// Add data-label attribute to each cell
document.querySelectorAll('table tbody tr').forEach(tr => {
    tr.querySelectorAll('td').forEach((td, column) => {
        td.setAttribute('data-label', labels[column]);
    });
});

Here’s card view new look with data label:

card view enhanced

Demo

It’s nothing like the html table that we started with. With CSS Grid, the layout options are endless because it allows for full control over both rows and columns in a two-dimensional space.

Final thought…

This tutorial only scratches the surface of the iceberg. You can easily create more responsive layouts, overlap elements, span items across multiple rows or columns, and adjust grid areas dynamically, making it highly versatile for various layout needs.

Happy gridding!

Richard

The post Transform HTML Table into Card View Using Nothing But CSS appeared first on phpGrid - PHP Datagrid.

]]>
10187
Show Remaining Characters in Textarea/Input https://phpgrid.com/example/show-remaining-characters-textareainput/ Tue, 25 Apr 2017 03:54:50 +0000 http://phpgrid.com/?p=9282

In a recent user support request, the user would like to see the remaining characters allowed for data input in a text input. This is not a phpGrid standard feature. How can it be achieved? Custom event comes to rescue! First of all, we must insert a new html node for our counter right after […]

The post Show Remaining Characters in Textarea/Input appeared first on phpGrid - PHP Datagrid.

]]>

In a recent user support request, the user would like to see the remaining characters allowed for data input in a text input. This is not a phpGrid standard feature. How can it be achieved?

Custom event comes to rescue!

First of all, we must insert a new html node for our counter right after the text input. In our demo, we use the “status” field. The new counter will display the text of remaining allowed characters for data entry.

1
<span id='counter'></span>

We bind a new “onkeyup” JavaScript event to the “status” text input. The phpGrid event you should use is “jqGridAddEditAfterShowForm” so that the counter is only displayed AFTER the form is shown.

1
2
3
4
5
6
7
8
$afterShowForm = <<<AFTERSHOWFORM
function ()
{
    $("#tr_status > td.CaptionTD + td.DataTD").append("<span id='counter'></span>");   
    $("#status").attr("onkeyup","updateCounter()");
}
AFTERSHOWFORM
;
$dg->add_event('jqGridAddEditAfterShowForm', $afterShowForm);

We use the CSS selector to style our counter. Most importantly, we make sure it is displayed in the right place (at the end of the text input box).

1
2
3
4
5
6
7
8
9
/* move the counter atop */
#counter{
    font-size: 8px;
    position: relative;
    top: -15px;
    float: right;
    padding-right: 25px;
    display:inline-block;
}

Lastly, insert the javascript function below that updates our counter during each key press.

1
2
3
4
5
6
7
8
// show how much characters in "status" field input. Max is 10
function updateCounter() {
  var maxChar = 10;
  var pCount = 0;
  var pVal = $("#tr_status > td.CaptionTD + td.DataTD  input").val();
  pCount = pVal.length;
  $("#counter").text(pCount + '/' + maxChar);
}

Run Live Demo! (Click “Status” input box, and start typing)

The post Show Remaining Characters in Textarea/Input appeared first on phpGrid - PHP Datagrid.

]]>
9282
Drag & Drop Rows Between Grids https://phpgrid.com/example/drag-drop-rows-grids/ Wed, 22 Mar 2017 06:58:32 +0000 http://phpgrid.com/?p=9270 You can drag and drop rows between two or more grids using a mouse. In the demo, we have both orders and employees datagrids on the same page. 123456use phpCtrl\C_DataGrid; require_once("/file/path/to/conf.php");   $dg = new C_DataGrid("select * from employees", "employeeNumber", "employees"); $dg->enable_edit("FORM", "CRUD"); $dg->display(); We add the following Javascript to enable drag and drop between […]

The post Drag & Drop Rows Between Grids appeared first on phpGrid - PHP Datagrid.

]]>
dnd-phpgrid

You can drag and drop rows between two or more grids using a mouse.

In the demo, we have both orders and employees datagrids on the same page.

1
2
3
4
5
6
use phpCtrl\C_DataGrid;
require_once("/file/path/to/conf.php");  

$dg = new C_DataGrid("select * from employees", "employeeNumber", "employees");
$dg->enable_edit("FORM", "CRUD");
$dg->display();

We add the following Javascript to enable drag and drop between the two php grids.

The Ondrop event posts the row data to another url “save_dropped_row.php”. You must implement this server side script to handle how you would like the row data to be saved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
$(function(){
  jQuery("#orders").jqGrid("sortableRows", {});
  jQuery("#employees").jqGrid("sortableRows", {});

  jQuery("#orders").jqGrid('gridDnD',{
    connectWith:'#employees',
    drop_opts:{
      hoverClass: "ui-state-active",
    },
    ondrop: function(evt, obj, data){
      $.ajax({
          method: "POST",
          url: "save_dropped_row.php",
          data: data,
        }).done(function( msg ) {
            console.log( "Data Saved: " + msg );
        })
    },

  });  
})
</script>

Complete Drag and drog API documentation can be found on jQuery UI draggable and droppable widgets.

Run Live Demo!

The post Drag & Drop Rows Between Grids appeared first on phpGrid - PHP Datagrid.

]]>
9270
Create a Database Management System in 15 Lines of Code https://phpgrid.com/example/database-content-administration-application-15-lines-php-code/ Mon, 02 Jan 2017 04:15:11 +0000 http://phpgrid.com/?p=9186

  Introduction We will learn how to build a fully functional, single-page database content administration system using phpGrid and other PHP components with a minimum amount of code. The application will perform common data operations such as Create, Read, Update, Delete, otherwise known as CRUD on MySQL database tables. Note the demo application requires phpGrid […]

The post Create a Database Management System in 15 Lines of Code appeared first on phpGrid - PHP Datagrid.

]]>
Download this demo

 

Introduction

We will learn how to build a fully functional, single-page database content administration system using phpGrid and other PHP components with a minimum amount of code. The application will perform common data operations such as Create, Read, Update, Delete, otherwise known as CRUD on MySQL database tables.

Note the demo application requires phpGrid version 7 and above. The demo uses MySQL, however, the same basic code should work with other databases with the use of a different SQL schema SELECT statement.

Design

Our application will have a list of database schemas and tables on the left side – the sidebar – and a database table on the main screen – the main. Both the sidebar and the main are datagrids. On the main datagrid, which contains the database table, we will also add a search bar so users can search within the displayed grid.

Our design mockup:

db-admin-mockup

2-Column Layout

Let’s start by creating the layout. What we need is a fixed-width sidebar on the left while the main – a grid – stays “fluid” so it fills the remaining document width. The main grid will be populated with data from the database table selected from the left sidebar.

Luckily, CSSPortal has an excellent layout tool which easily generates a column-based layout with only point and click.

http://www.cssportal.com/layout-generator/

An alternative is to download this boilerplate (File -> Save As) which contains all the HTML and CSS code needed for this demo application.

Setup

Let’s start coding. Presumably, you have already installed phpGrid on your web server. If not, follow this guide to learn how – http://phpgrid.com/documentation/installation/

First, add the following lines to the TOP of our page

1
2
use phpGrid\C_DataGrid;
require_once("phpGrid/conf.php");

The first line adds the phpGrid namespace so PHP knows where to find phpGrid in the system. Otherwise, PHP will throw a nasty error – “Fatal error: Class ‘C_DataGrid’ not found”.

The second line references phpGrid by including its conf.php. The Installation Guide – http://phpgrid.com/documentation/installation/ – explains this in greater length.

Sidebar

The left sidebar contains a list of the tables found in each respective database in a subgrid.

Sidebar – Step 1

The first step is to return a list of current schemata from the selected database. In MySQL, the following SQL statement retrieves a list of schema names.

1
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA

The PHP code to return a list of schemas is as follows:

1
2
3
4
// schema list
$dbs = new C_DataGrid("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA", "SCHEMA_NAME", "INFORMATION_SCHEMA.SCHEMATA");
$dbs->set_dimension('300px');
$dbs->set_pagesize(999)->set_scroll(true);

How the above code works:

set_dimension sets the width of the left sidebar to 300 pixels.
set_pagesize sets the height of the page to a very large number, e.g. 999. Thus, all data will be displayed on a single page. set_scroll removes the pagination controls normally found in the bottom footer.

Sidebar – Step 2

The second step displays a list of available database tables in each schema in a subgrid.

The PHP code to return a list of tables appears below.

1
2
3
4
// table list    $tbl = new C_DataGrid("SELECT TABLE_NAME, TABLE_SCHEMA, TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES", "TABLE_NAME", "INFORMATION_SCHEMA.TABLES");
$tbl->set_col_hidden('TABLE_SCHEMA');
$tbl->set_pagesize(999)->set_scroll(true);
$tbl -> set_col_dynalink("TABLE_NAME", "db_admin.php", array("TABLE_NAME", "TABLE_SCHEMA"), '', "_top");

How the above code works:

First, we hide the TABLE_SCHEMA column because it is redundant. The page size is set to a large number (999) and scroll is set to true. Finally, and  most importantly, set_col_dynalink forms a dynamic URL for each database table used to populate the main datagrid.  You can learn more about the set_col_dynalink function here: http://phpgrid.com/documentation/set_col_dynalink/

Sidebar – Step 3

Lastly, set the subgrid. The subgrid displays an inline detail grid for each row in the parent grid. If you are not familiar with phpGrid subgrids, check out the subgrid demo online – http://phpgrid.com/example/subgrid/.

1
2
$dbs->set_subgrid($tbl, 'TABLE_SCHEMA', 'SCHEMA_NAME');
$dbs->display();

db-admin-sidebar

Main Column

The main column contains the datagrid for the database table. Recall that in the code to create the sidebar, Step 2, we used a function called “set_col_dynalink” which set a dynamic URL for every database table name in the URL query string. Now we need to retrieve the schema name and table name by using the following code:

1
2
$schemaName = (isset($_GET['TABLE_SCHEMA']) && isset($_GET['TABLE_SCHEMA']) !== '') ? $_GET['TABLE_SCHEMA'] : 'sampledb';
$tableName = (isset($_GET['TABLE_NAME']) && isset($_GET['TABLE_NAME']) !== '') ? $_GET['TABLE_NAME'] : 'orders';

The first line of code gets the schema name and the second gets the table name. There’s nothing special about this except we set a default value for each variable to be used in cases where the parameters are missing – such as as when the page is first loaded.

Below is the code for the main grid:

1
2
3
4
5
6
7
8
9
$dg = new C_DataGrid("SELECT * FROM $tableName",'orderNumber', "$tableName",
array("hostname"=>"localhost",
"username"=>"root",
"password"=>"",
"dbname"=>$schemaName,
"dbtype"=>"mysql",
"dbcharset"=>"utf8"));
$dg->enable_global_search(true);
$dg -> display();

How the above code works:

The first line uses phpGrid’s multiple database reference feature. This is essential because we need to reference different tables found in different databases. See http://phpgrid.com/example/multiple-databases-support/ for more information about how phpGrid can be configured to work with multiple databases.

Note that it is important to use the correct corresponding primary key when referencing the default database table.  In this case, we are referencing the “orders” table with the primary key “orderNumber”.

enable_global_search adds the global search bar to top of the grid. Finally, the last line displays our datagrid.

db-admin-main

That’s all there is to it! You now have a web-based database content management console using fewer than 15 lines of code.

But Wait, There’s More!

We can beef up the grid and take advantage of the fluid layout design by adding a few more lines of code.

First, we add a caption to show the current schema and table name. Then, we set the auto width, enable edit and then add a global search to the top.

1
2
3
4
5
$dg->set_caption(strtoupper("$schemaName.$tableName"));
$dg->enable_autowidth(true);
$dg->enable_edit();
$dg->set_scroll(true);
$dg->enable_global_search(true);

Finally, before we go, let’s add the following javascript event to make sure that the grid will only resize in its container and not in the browser window itself.

1
2
3
4
// set grid width to parent DIV
$dg->before_script_end .= 'setTimeout(function(){$(window).bind("resize", function() {
phpGrid_'
. $tableName .'.setGridWidth($(".right").width());
}).trigger("resize");}, 0)'
;

Summary

Congrats! You have built a content management system for your database!

Download this demo

The post Create a Database Management System in 15 Lines of Code appeared first on phpGrid - PHP Datagrid.

]]>
9186
phpGrid Symfony Integration https://phpgrid.com/example/phpgrid-symfony-integration/ Mon, 12 Dec 2016 07:48:19 +0000 http://phpgrid.com/?p=9106

Files needed for this demo phpGrid Lite (free) Symfony 3 (free)   Where to keep phpGrid files in Symfony (Hint: not in “vendor” folder) The short answer is “web” folder. Symfony web assets are used to keep things like CSS, JavaScript and image files that renders the front-end of your site. phpGrid encapsulates both database […]

The post phpGrid Symfony Integration appeared first on phpGrid - PHP Datagrid.

]]>

Files needed for this demo

 

Where to keep phpGrid files in Symfony (Hint: not in “vendor” folder)

The short answer is “web” folder. Symfony web assets are used to keep things like CSS, JavaScript and image files that renders the front-end of your site. phpGrid encapsulates both database access routines and display so you don’t have to worry about them. It does this magic “behind the scenes”.

Edit conf.php in phpGrid

Remember to change the database credentials in conf.php. You do not need to set SERVER_ROOT value because phpGrid is inside public accessible “web” folder.

Enable PHP templating engine

Before we start phpGrid Symfony integration, make sure the “php” templating engine is enabled in your application configuration file under app/config .Symfony defaults to Twig for its template engine, but you can still use plain PHP code if you want. Symfony adds some nice features on top of PHP to make writing templates with PHP more powerful.

1
2
3
4
5
# app/config/config.yml
framework:
    # ...
   templating:
        engines: ['twig', 'php']

Create Symfony Controller

Symfony Controller needs to call our grid view file because we do not want to use Controller to render our datagrid. In this demo, we will modify the default controller located in folder “src/AppBundle/Controller/”. For simplicity, we keep the route path the same as the view folder structure.

1
2
3
4
5
6
7
8
/**
 * @Route("/phpgrid/simple")
 */

public function gridAction(){
   
   return $this->render('phpgrid/simple.html.php');

}

Create Symfony View file

First of all, create a new folder named “phpgrid” in “app/Resources/views”. Secondly, create a view file named “simple.html.php”, or whatever view file name used in your Controller in the previous step.

Include the phpGrid config file.

1
2
$webDir = $this->container->getParameter('kernel.root_dir');
require_once($webDir ."/../web/phpGrid_Lite/conf.php");

Load a simple datagrid from phpGrid sample database table “orders” (The sample database is located under examples/SampleDB)

1
2
$dg = new C_DataGrid("SELECT * FROM orders", "orderNumber", "orders");
$dg->display();

Congrats! You’ve just created your first datagrid in Symfony! Now visit “your_domain.com/phpgrid/simple” to see the datagrid.

 
 
Download complete demo files

The post phpGrid Symfony Integration appeared first on phpGrid - PHP Datagrid.

]]>
9106
Announcing phpGrid v6.7 https://phpgrid.com/example/announcing-phpgrid-v6-7/ Sun, 24 Jan 2016 16:15:27 +0000 http://phpgrid.com/?p=8570 Today we released phpGrid version 6.7. It updates several major core components to support PHP 7. List of main changes: PHP 7 support! PDF class updated to support PHP 7 Native Excel export (requires PHPExcel) ADOdb 5.20 data access library update for PHP 7 support Bug fix subgrid to add readonly fields support Minor theme […]

The post Announcing phpGrid v6.7 appeared first on phpGrid - PHP Datagrid.

]]>
Today we released phpGrid version 6.7. It updates several major core components to support PHP 7.

List of main changes:

  • PHP 7 support!
  • PDF class updated to support PHP 7
  • Native Excel export (requires PHPExcel)
  • ADOdb 5.20 data access library update for PHP 7 support
  • Bug fix subgrid to add readonly fields support
  • Minor theme update.

New and updated online demos:

  1. Column auto width. Noted in green banner.
  2. Pivot grid
  3. New date format demo
  4. New header tooltip function set_col_headerTooltip 

Thank you and have a grid day!

Richard
p.s. check out the complete phpGrid version history.

The post Announcing phpGrid v6.7 appeared first on phpGrid - PHP Datagrid.

]]>
8570
phpGrid Now Has Improved IBM DB2 Support! https://phpgrid.com/example/ibm-db2-support/ Tue, 27 Oct 2015 09:26:54 +0000 http://phpgrid.com/?p=8279

THIS TUTORIAL IS OUTDATED. “ibm_db2” is now the recommended extension to access the DB2 database. You should only use “PDO_ODBC” driver to access DB2 as a fallback when “ibm_db2” extension fails to work. To access DB2 through “ibm_db2” extension, please refer to phpGrid DB2 with “ibm_db2” extension tutorial. DB2 supports database access for client applications […]

The post phpGrid Now Has Improved IBM DB2 Support! appeared first on phpGrid - PHP Datagrid.

]]>
THIS TUTORIAL IS OUTDATED.

“ibm_db2” is now the recommended extension to access the DB2 database. You should only use “PDO_ODBC” driver to access DB2 as a fallback when “ibm_db2” extension fails to work. To access DB2 through “ibm_db2” extension, please refer to phpGrid DB2 with “ibm_db2” extension tutorial.

DB2 supports database access for client applications written in the PHP programming language using either or both of the “”ibm_db2” extension and the “pdo_ibm” driver for the PHP Data Objects (PDO) extension. This tutorial uses the unixODBC as the PDO_ODBC driver to connect to DB2. To access DB2 through “ibm_db2” extension, please refer to phpGrid “ibm_db2” tutorial.

After months of hard work, phpGrid now finally has the PDO_ODBC DB2 database support! phpGrid’s DB2 support has been spotty in the past, owing to the fact that the ADOBdb data access library uses non-supported legacy IBM DB2 driver. A new PDO data access class has been implemented specifically for DB2.*

We worked uber-hard to ensure that the existing phpGrid API stayed the same. The only changes we made were essential, and they are transparent to our users. To use the new database, simply type “pdo_odbc_db2” as the “PHPGRID_DB_TYPE“” value in “conf.php”, and 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). phpGrid can be used as a data management tool in an IBM i environment because the PHP runtime module is already preloaded with IBM i. This allows for a super-charged datagrid with built-in CRUD capability to be up and running very quickly with minimal knowledge of the ins and outs of PHP.

The DB2 was fully tested in IBM DB2 Express-C. It requires the “PDO_ODBC(unixODBC) extension“. As of PHP 5.1, PDO_ODBC is included in the PHP source. You should verify it in phpinfo.

Both the web server and DB2 must be on the same server. If you have trouble installing unixODBC, I suggest you install the Zend Server (free) and install PDO_ODBC (unixODBC) extension extension quickly and easily through Zend Server’s wonderful admin dashboard. Finally, set up the DSN in the odbc.ini and odbcinst.ini configuration files.

odbc.ini

1
2
3
[sample]
Description = Test to DB2
Driver      = DB2

odbcinst.ini

1
2
3
4
5
6
[db2]
Description = DB2 Driver
Driver      = /opt/ibm/db2/V10.5/lib32/libdb2.so
Driver64    = /opt/ibm/db2/V10.5/lib64/libdb2.so
FileUsage   = 1
DontDLClose = 1

*Note that DB2 support is only available with the Enterprise license. Here’s 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

putenv('ODBCSYSINI=/etc');
putenv('ODBCINI=/etc/odbc.ini');

Finally, the sample code using the DB2 db2sampl database:

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

$dg = new C_DataGrid("SELECT * FROM EMPLOYEE", "EMPNO", "EMPLOYEE");
$dg->set_col_title('EMPNO', 'Employee #');
$dg->set_col_title('PHONENO', 'Phone Number');
$dg->set_col_width('SEX', 50)->set_col_align('SEX', 'center');
$dg->set_col_width('MIDINIT', 30)->set_col_align('MIDINIT', 'center');
$dg->enable_search(true);
$dg->enable_edit('FORM');
$dg->enable_export('CSV');
$dg->enable_autowidth(true);
$dg->set_col_edittype('WORKDEPT', 'select', 'select DEPTNO, DEPTNAME from DEPARTMENT');
$dg->set_col_edittype('SEX', 'select', 'M:M;F:F');
$dg->set_conditional_format("SEX","CELL",array(
    "condition"=>"eq","value"=>"F","css"=> array("color"=>"black","background-color"=>"#FDA6B2")));
$dg->set_conditional_format("SEX","CELL",array(
    "condition"=>"eq","value"=>"M","css"=> array("color"=>"black","background-color"=>"#A6D7FC")));
$dg->set_conditional_format("SALARY","CELL",array(
    "condition"=>"gt","value"=>75000,"css"=> array("color"=>"black","background-color"=>"lightgreen")));
$dg -> display();

Sample datagrid output:
 

phpgrid-db2sampl-employee

 

To use PHP “ibm_db2” extension, please see the phpGrid “ibm_db2” tutorial.

The post phpGrid Now Has Improved IBM DB2 Support! appeared first on phpGrid - PHP Datagrid.

]]>
8279
phpGrid and Zend Framework Integration https://phpgrid.com/example/phpgrid-and-zend-framework-integration/ Sun, 13 Sep 2015 09:52:59 +0000 http://phpgrid.com/?p=8157

Introduction IntroductionZend Framework (ZF) is a popular open source, MVC web application framework created and maintained by Zend Technologies, the company behind the PHP programming language. This tutorial will walk you through the integration of Zend Framework 2 and phpGrid. It uses Zend Framework version 2.4 which requires PHP version 5.5 and above. Install the […]

The post phpGrid and Zend Framework Integration appeared first on phpGrid - PHP Datagrid.

]]>

Introduction

IntroductionZend Framework (ZF) is a popular open source, MVC web application framework created and maintained by Zend Technologies, the company behind the PHP programming language.

This tutorial will walk you through the integration of Zend Framework 2 and phpGrid. It uses Zend Framework version 2.4 which requires PHP version 5.5 and above.

Install the Zend Framework Skeleton Application

The best way to create a Zend Framework project is with Composer. Start by using Composer to install Github’s ZendSkeletonApplication. It’s a great starting point to begin a blank Zend project.

Create your new ZF2 project:

1
composer create-project -n -sdev zendframework/skeleton-application path/to/install

“path/to/install” should be a folder in web root.

Install phpGrid

Before installing phpGrid, in the ZF2 that we created in the previous step, find the “vendor” folder. 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:

zendframework-folder

 

Configuring the conf.php file in phpGrid

Complete the phpGrid installation by configuring its database information in the “conf.php” file inside the phpGrid folder. For complete instructions on how to do this, see the phpGrid configuration online documentation.

phpGrid comes with several sample databases. You can find them under the “examples/SampleDB” folder. We will use the MySQL sample database for this Zend Framework integration tutorial.

Modify “composer.json”

Before start coding, we need to register our phpGrid library in the Zend Framework autoloader. This is done by adding autoload files keys in “composer.json”. The 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 vary slightly from what you have, and notice the autoload value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "license": "BSD-3-Clause",
    "keywords": [
        "framework",
        "zf2"
    ],
    "homepage": "http://framework.zend.com/",
    "require": {
        "php": ">=5.5",
        "zendframework/zendframework": "~2.5"
    },
    "autoload":{
        "files": ["vendor/phpcontrols/phpGrid/conf.php"]
    }
}

Finally, once these changes have been made, we update the composer. In the project root, run the following command:

1
composer update

Start coding!

Open the file “module/Application/view/application/index/index.phtml“. Assuming that you have installed the phpGrid sample database installed,. Somewhere in “index.phtml”, add the following code:

1
2
3
4
5
6
use phpCtrl\C_DataGrid;
require_once("/file/path/to/conf.php");  

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

Note that if you are working 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 is to it. You should now be able to run the demo.

Run Demo

What about the controller and model?

You may be 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 this magic “behind the scenes”.

The post phpGrid and Zend Framework Integration appeared first on phpGrid - PHP Datagrid.

]]>
8157
Integrate with .CSV or Google Spreadsheets https://phpgrid.com/example/google-spreadsheet-datagrid-integration/ Mon, 03 Aug 2015 14:11:52 +0000 http://phpgrid.com/?p=7907 You can use a local .csv or 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 the array data source feature is only available with a commercial license. Loading from Google Spreadsheet is […]

The post Integrate with .CSV or Google Spreadsheets appeared first on phpGrid - PHP Datagrid.

]]>
You can use a local .csv or 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 the array data source feature is only available with a commercial license.

Loading from Google Spreadsheet is straight forward and much the same as loading from a local array data source. In order 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 such as the one shown here:

google-spreadsheet-original

 

Share the Google Spreadsheet

  1. Click Change… to change access settings,
  2. Click “Public on the Web” or “Anyone with the link”,
  3. Click Save
     

    google-spreadsheet-sharing

     

Publish on the Web

  1. Click File >Publish on the Web
     


    google-spreadsheet-publish-menu

  2. Click “Advanced”, and make sure “Automatically republish when changes are made” is checked.google-spreadsheet-publish
     
  3. Choose “Comma-separated values (.csv) as output type in Link type drop-down
     

    google-spreadsheet-share-csv-output

     
  4. Finally, copy the document link created in the previous step. You should have a link similar to the following with “output=csv” in the URL parameter:
    https://docs.google.com/spreadsheets/d/1IvbMsUZTCdY7duciT3lWSXHPP_qPDG8FrJl8dq1ZbI/pub?output=csv

     

    google-spreadsheet-share-link

     

Start Coding

First of all, we need to massage our data into a format that phpGrid can recognize. You can read more about this in the  local array data data example. In our Google Spreadsheet sample file, the first row contains the header information. We will extract that row and use the contents of each cell in the row as the name for each column in the datagrid. Once the data has been formatted, it becomes accessible as though it were a local file.

1
2
3
4
5
6
7
8
9
10
11
12
$spreadsheet_url = 'https://docs.google.com/spreadsheets/d/1IvbMsUZTCdYb5z34jT3lWSXHPP_qPDG8FrJl8dq1ZbI/pub?output=csv';
$csv = file_get_contents($spreadsheet_url);
$rows = explode("\n",$csv);
$data = array();
$names = array();
for($i=0; $i<count($rows); $i++) {
if($i==0){
$names = str_getcsv($rows[$i]);
}else{
$data[] = str_getcsv($rows[$i]);
}
}

The final step is to add the phpGrid code. We add the title to each datagrid column. We then enable auto filter in integrated search, and give the datagrid a new look using our premium theme “Aristo”.

Please note that “search auto filter” is a new feature. It generates a filter drop-down in integrated toolbar search based on a column’s unique values.

Since Google Spreadsheet does not put in a separate column header when a file is saved as a .csv, we compensate for this by using a column index array, e.g. array(1,2,3,5), as our search auto filter.

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

$dg = new C_DataGrid($data, "id", "Google_Spreadsheet");
for($i=0; $i<count($names); $i++) { $dg->set_col_title($i, $names[$i]);
}
$dg->enable_search(true, array(1,2,3,5));
$dg->set_theme('aristo');
$dg->display();

That’s how you populate datagrid from a Google Spreadsheet. Enjoy!

Demo

The post Integrate with .CSV or Google Spreadsheets appeared first on phpGrid - PHP Datagrid.

]]>
7907
phpGrid and CodeIgniter Integration https://phpgrid.com/example/phpgrid-and-codeigniter-integration/ Thu, 09 Jul 2015 12:42:29 +0000 http://phpgrid.com/?p=7764

Introduction CodeIgniter is a popular, open source PHP framework loosely based on the MVC development pattern. It is used to build dynamic web sites. Out of box, phpGrid is a ready-to-use PHP datagrid solution. Integrating phpGrid with CodeIgniter couldn’t be easier. Here’s how. Install CodeIgniter Download CodeIgniter here. To install CodeIgniter, follow these four steps: Unzip […]

The post phpGrid and CodeIgniter Integration appeared first on phpGrid - PHP Datagrid.

]]>

Introduction

CodeIgniter is a popular, open source PHP framework loosely based on the MVC development pattern. It is used to build dynamic web sites. Out of box, phpGrid is a ready-to-use PHP datagrid solution. Integrating phpGrid with CodeIgniter couldn’t be easier. Here’s how.

Install CodeIgniter

Download CodeIgniter here. To install CodeIgniter, follow these four steps:

  1. Unzip the package.
  2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at the root.
  3. 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.
  4. 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. To install phpGrid, follow these steps:

  1. Unzip the phpGrid download file.
  2. Upload the unzipped phpGrid folder to the “application/libraries” folder.
  3. Complete the installation by configuring the conf.php file. For instructions on how to do this, see setup phpGrid configuration.

CodeIgniter Controller

For the purpose of this tutorial, we will directly modify the default controller file “Welcome.php”. In practice, the changes can be made in any new or existing controller file. Notice 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 the phpGrid configuration file. The “APPPATH” constant is the path to your application folder. Unlike with the Laravel framework, with CodeIgniter you can directly include PHP classes and working with them. phpGrid is a complex component and composed of multiple classes.

1
2
3
4
5
6
7
8
9
public function index()
{
    // $this->load->view('welcome_message');

    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”.

phpGrid-Codeigniter-code

Create View

Creating a view is very simple.  All you have to do is to put  <?php $phpgrid->display(); ?> somewhere in the view. Learn more about creating a basic PHP grid here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Show Grid</title>
</head>
<body>

<div id="container">
    <h1>Welcome to CodeIgniter! Show me the grid!</h1>

    <div id="body">
        <?php $phpgrid->display(); ?>
    </div>

</div>

</body>
</html>

That’s it! phpGrid handles all the CRUD operations. We don’t need to create a Model for our PHP datagrid to run in CodeIgniter.

Screenshot

phpGrid-Codeigniter-outcome

CodeIgniter and PHP Session

We recommended that you stick to a native PHP session in CI. By default, CI stores session information in a cookie, which is neither secure nor efficient.

You can also use the “out of proc” session by storing the session info in a database. This method is more sophisticated but inevitably more complex. It is not recommended unless you need to develop a large eCommerce website needs a session persistent shopping cart. phpGrid also uses a native PHP session to store secure data such as database connections and SQL data.

If you are using a native PHP session, make sure set “save_path” value to php.ini in an existing folder with write permissions.

http://php.net/manual/en/session.configuration.php#ini.session.save-path

Update: CodeIgniter 3+ Permission Update

Since CodeIginter 3, application and system folder has a new .htaccess for security the URL rewrite. It’s recommended to replace .htaccess with the following in application folder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<IfModule mod_rewrite.c>
    RewriteEngine On
    #RewriteBase /your_project/

    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    ErrorDocument 404 /index.php
</IfModule>

The post phpGrid and CodeIgniter Integration appeared first on phpGrid - PHP Datagrid.

]]>
7764