Start Building Professional
Web Apps Today


DHTMLX Integration with Yii PHP Framework

July 10th, 2012

The DHTMLX component library offers a pure JavaScript/CSS solution for building web interfaces. The advantage of developing with the client-side library is that you can use it with your favorite server-side technology. In this tutorial, we will explain how to use the DHTMLX UI components with one of the most popular PHP frameworks, Yii framework.

The tutorial describes how to integrate dhtmlxGrid and dhtmlxScheduler in a Yii application. You’ll learn how to bind the grid and the scheduler to the database and update data on the server when user makes changes on the client side.

The integration with Yii will be done through the dhtmlxConnector layer, which handles client-server data communication. This tutorial gives step-by-step instructions but it is assumed that you have the basic knowledge of the Yii framework and the DHTMLX library.

Download the files of the final demo and keep reading to learn how to use DHTMLX with the Yii framework.

 
Getting Started

Before continuing, make sure that you have Yii installed on your computer. If you don’t, refer to the installation guide to learn how to do it.

Download the packages:

 
In the root folder of your app, create a sub-folder with the name ‘DHTMLX’. Add the required JS/CSS files of dhtmlxConnector, dhtmlxGrid, dhtmlxScheduler, and dataProcessor (included in both dhtmlxGrid and dhtmlxScheduler packages) to the ‘DHTMLX’ folder, or simply copy the folder with the required files from the final demo package (find the download link above).

Thus, you have two folders in the root folder of your demo app: one with Yii files, and the other one with DHTMLX files:

Required files

In our demo Yii app, we use the events database. You can create a local copy of this database by importing the SQL dump file events.sql (find it in the root folder of the final package) or you can just use any available database. Note that if you use your own database, you will need to adapt the code examples by yourself.
 

Creating Model Class

To connect our web application to the database, we need to create a model class. You can make it by using the built-in web-based code generator Gii. For more details of generating a model class, read Creating Your First Yii Application article in the Yii documentation.

The newly created Events model class allows us to access the backend database ‘events’ table, which stores our data for the grid and the scheduler.

 

Grid Integration

 
Creating Controller Object

In the ‘controllers’ folder (which is automatically created by Yii framework), create a new file and name it EventController.php. Place the following code within this file:

• Add the files required for working with dhtmlxConnector and create a root controller class EventController with the primary action:

<?php
    require_once(dirname(__FILE__)."/../../../dhtmlx/connector/grid_connector.php");
    require_once(dirname(__FILE__)."/../../../dhtmlx/connector/scheduler_connector.php");
    require_once(dirname(__FILE__)."/../../../dhtmlx/connector/db_phpyii.php");
 
       class EventController extends Controller {
          public function actionIndex()
          {
            $this->render('index');
          }
              // here you should place all your functions
       }
?>

Note that we’ve also added the connector files for the scheduler, which will be required for the scheduler integration described below. If you don’t plan to use the scheduler in your app, just do not include the file ‘scheduler_connector.php’.

• Create an action that will load a view displaying the grid:

public function actionGrid()
{
    $this->render('grid'); //loads the 'grid' view that we will create later
}

• Create an action that will load data to the grid:

public function actionGrid_data()
{
    $grid = new GridConnector(Events::model(), "PHPYii");
    $grid->configure("-", "event_id", "start_date, end_date, event_name");
    $grid->render();
}

GridConnector takes as parameters a DB connection variable and a database type. Since we’re working with Yii, these parameters have the following values:

Events::model()

- refers to the model Events used in the app,

"PHPYii"

- a constant value.

The configure method generates an SQL query and takes as parameters:

  • ‘-’ – a hardcoded value
  • $id – the name of the id field
  • $text – a comma separated list of rendered data fields
  • $extra – (optional) a comma separated list of extra fields
  • relation_id – (optional) used for building hierarchy in case of Tree and TreeGrid

 
You can see the resulting EventController.php file in the demo package. This file processes all the operations with data (add, edit, remove records) and saves the changes made by user to the database on the server.

 
Creating View Object

In the ‘views’ folder create a new file and name it grid.php. In the view file, add the following code:

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <script src="/dhtmlx/grid/dhtmlxcommon.js"  type="text/javascript" charset="utf-8"></script>
    <script src="/dhtmlx/grid/dhtmlxgrid.js"    type="text/javascript" charset="utf-8"></script>
    <script src="/dhtmlx/grid/dhtmlxgridcell.js"    type="text/javascript" charset="utf-8"></script>
 
    <script src="/dhtmlx/dhtmlxdataprocessor.js"    type="text/javascript" charset="utf-8"></script>
    <script src="/dhtmlx/connector/connector.js"    type="text/javascript" charset="utf-8"></script>
 
    <link rel="stylesheet" href="/dhtmlx/grid/dhtmlxgrid.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="/dhtmlx/grid/skins/dhtmlxgrid_dhx_skyblue.css" type="text/css" media="screen" title="no title" charset="utf-8">   
</head>
 
<body>
    <div id="grid_here" style="width:600px; height:400px;"> </div>
 
        <script type="text/javascript" charset="utf-8">
         mygrid = new dhtmlXGridObject('grid_here');
         mygrid.setHeader("Start date,End date,Text");
         mygrid.init();                          
         mygrid.loadXML("./grid_data"); //refers to the 'Grid_data' action we created in the previous step
 
         var dp = new dataProcessor("./grid_data"); //refers to the 'Grid_data' action as well
         dp.init(mygrid);
 
        </script>
</body>

It’s a standard code that initializes dhtmlxGrid on a page. If you have already worked with the grid component before, it won’t be difficult for you to understand the code. If anything is not clear, refer to the grid documentation.

When the grid.php file is ready, run webhost/cdemo/event/grid. The page should now display the grid filled with data from the server-side database. The grid is editable and all the changes you make in grid are saved to the database.

dhtmlxGrid in Yii App

 

Scheduler Integration

 
Creating Controller Object

We have already created EventController.php file (see the instructions for the grid integration above). Now we just need to add the following code to display the scheduler on a page and fill it with content from the database table:

• Create an action that will load a view displaying the scheduler:

public function actionScheduler()
{
    $this->render('scheduler'); //loads the 'scheduler' view that we will create later
}

• Create an action that will load data to the scheduler:

public function actionScheduler_data()
{
    $scheduler = new SchedulerConnector(Events::model(), "PHPYii");
    $scheduler->configure("-", "event_id", "start_date, end_date, event_name");
    $scheduler->render();
}

 
Creating View Object for Scheduler

The next step is creating a view file for the scheduler. In the ‘views’ folder create a new file and name it scheduler.php. The file should include the following code:

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <script src="/dhtmlx/scheduler/dhtmlxscheduler.js" type="text/javascript" charset="utf-8"></script>
    <link rel="stylesheet" href="/dhtmlx/scheduler/dhtmlxscheduler_glossy.css" type="text/css" media="screen" title="no title" charset="utf-8">
</head>
 
<body>
    <div id="scheduler_here" class="dhx_cal_container" style='width:800px; height:600px;'>
        <div class="dhx_cal_navline">
            <div class="dhx_cal_prev_button">&nbsp;</div>
            <div class="dhx_cal_next_button">&nbsp;</div>
            <div class="dhx_cal_today_button"></div>
            <div class="dhx_cal_date"></div>
            <div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
            <div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
            <div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
        </div>
        <div class="dhx_cal_header">
        </div>
        <div class="dhx_cal_data">
        </div>
    </div>
 
<script type="text/javascript" charset="utf-8">
    scheduler.config.multi_day = true;
 
    scheduler.config.xml_date="%Y-%m-%d %H:%i";
    scheduler.config.first_hour = 5;
    scheduler.init('scheduler_here',new Date(2010,7,5),"week");
    scheduler.load("./scheduler_data");
 
    var dp = new dataProcessor("./scheduler_data");
    dp.init(scheduler);
</script>
</body>

Again, we used a standard code that initializes the scheduler component. For a deeper learning of dhtmlxScheduler initialization, read the documentation.

Now, if you run webhost/cdemo/event/scheduler, you should see the scheduler that loads data from the ‘events’ table in the database. The same as with the grid – all changes made in the scheduler are saved to the database. Users can create, modify or delete events, and the data in the database will be updated automatically.

dhtmlxScheduler in Yii App

 
That’s all. We now have a Yii demo application created with dhtmlxGrid, dhtmlxScheduler, and the dhtmlxConnector library. We have integrated editable data grid and scheduler that can update the database table when user make changes on the client side. The application logic was not the goal of the tutorial but we hope that this example will inspire you to create fully functional web apps with DHTMLX and Yii.

Download the demo files and get a closer look to the integration approach.

We also have the tutorials explaining how to integrate the DHTMLX components with other PHP frameworks. Check these articles in the documentation:

Comments

  1. Thomas,
    August 10, 2012 at 3:09 pm

    Thank you for this tutorial. This is exactly what I needed.

  2. Bonnie,
    August 14, 2012 at 2:17 am

    This is what I have been searching for on the internet to get something that is easy to integrate in YII structure. I want to developer a school management application and this tutorial has just nailed it. I know we have other js framework but they do not plug in YII as this one. Am going to start developing my app now using this library.
    Thanks again.

    • Ivan,
      August 14, 2012 at 2:05 pm

      Bonnie, we hope that you’ll enjoy developing with the DHTMLX library. Should you have any technical questions, you can post them to our forum (registration is free):
      http://forum.dhtmlx.com

  3. Simon,
    August 17, 2012 at 2:59 am

    Great that these library components can be used with Yii.

    Couple of things that I ran into that might help others when going through this demo.

    1. On line 16 of the file dhtmlx/connector/db_phpyii.php there is an error:

    Shows – $temp[]=&$obj->getAttributes();
    Should read – $temp[]=$obj->getAttributes();

    2. This demo only seems to work if Yii is set to use URLs in path-format
    (eg. localhost/myappname/event/grid) but doesn’t work if using the default Yii URLs
    (eg. localhost/myappname/index.php?r=event/grid).

    • Ivan,
      August 20, 2012 at 7:45 pm

      Simon, thank you for your pointing out these issues. This will be fixed in the future release of dhtmlxConnector.

  4. nirmal roka,
    August 18, 2012 at 6:17 am

    Great Work and I loved this. I will sure to use this and try in my project.

  5. Ayyapillai,
    August 31, 2012 at 6:03 pm

    Thanks for your grateful PHP Tutorial informations.

  6. Ruggero Domenichini,
    September 5, 2012 at 4:54 pm

    I have installed DHTML PRO (eval) successfully and I have been able to run the Yii framework connection example (cdemo).
    I have then created a grid within my applicaton in Yii and again this works fine.
    I have modified the grid to test checkboxes, calendars, date and number formatting and all works fine.

    I am now trying to use combo box inside a column but as soon as I change the “ed” editor type to co or coro or combo I have an error, can anyone please help.

    PHP Error [8]
    Undefined index: value (/Users/rujero/Dropbox/Websites/dhtmlx/connector/base_connector.php:255)
    #0 /Users/rujero/Dropbox/Websites/dhtmlx/connector/base_connector.php(255): CWebApplication->handleError()
    #1 /Users/rujero/Dropbox/Websites/dhtmlx/connector/base_connector.php(235): DataItem->to_xml_start()
    #2 /Users/rujero/Dropbox/Websites/dhtmlx/connector/strategy.php(26): DataItem->to_xml()
    #3 /Users/rujero/Dropbox/Websites/dhtmlx/connector/base_connector.php(605): RenderStrategy->render_set()

    Can you please help? Tx!

    • Ivan,
      September 5, 2012 at 5:02 pm

      Ruggero, please submit a ticket to the online support system (find the login instructions in the email with the download link to the evaluation version). Support team will help you to solve this issue. You can also use forum for your technical questions (registration is free):
      http://forum.dhtmlx.com

      • Ruggero Domenichini,
        September 6, 2012 at 1:45 pm

        Thank you Ivan, I’ve done it and Stanislav came back with suggestions that I am going to try soon.

  7. Andrei,
    September 7, 2012 at 11:40 am

    Thank you for really great lib!
    Scheduler connector work fine but when I trying use units or matrix view I can’t set sections.
    Seems “typeid(value),name(label)” syntax work only for pure mysql but phpyii.
    May be there is a workaround of this issue?
    Thanks.

    • Ivan,
      September 17, 2012 at 4:11 pm

      Andrei, the issue has been confirmed. We’re trying to find a solution for this problem.

  8. sarabjeet,
    September 12, 2012 at 6:53 pm

    Great post indeed and thanks for all the information, it was very helpful i really like that you are providing information on PHP and MYSQL with basic JAVASCRIPT, being enrolled here. I was looking for such information online to assist me on php and mysql and your information helped me a lot. Thanks.

  9. Anil Herath,
    October 6, 2012 at 3:47 pm

    Thanks for the great library and documentations.
    I tried to use the demo application as follows.
    01. Download and extracted to htdocs directory.
    02. Set database configurations and import the ‘Events.sql’ script

    The application loaded without any problem. Then I clicked on the link ‘Grid’. It redirects me to localhost.

    Then i accessed those pages by manually typing the address. But unfortunately the grid or scheduler not loaded.

    I checked the results with firebug and it says following errors respectively.

    01. Grid :
    ReferenceError: dhtmlXGridObject is not defined
    grid()
    mygrid = new dhtmlXGridObject(‘grid_here’);

    02. Scheduler
    ReferenceError: scheduler is not defined
    scheduler()
    scheduler.config.multi_day = true;

    I am using xampp with php 5.2.

    It’s highly appreciated if anyone can help me to find the issue.

    • Ivan,
      October 10, 2012 at 8:16 pm

      Anil, the demo is configured to be executed from the root of web-server. Path to the grid’s demo should be like:

      http://localhost/event/grid or http://some.com/event/grid

      If you have run the app from some sub-folder, not the root of web-server, then the paths to js file will be invalid.

  10. Anil Herath,
    October 17, 2012 at 8:42 am

    Thank you very much Ivan. Now it’s work like a charm. Thanks for the help and the great library.

  11. Almix,
    December 21, 2012 at 12:46 am

    Is it good that .js scripts go in body (not in head) section? I don’t know does it important, but right now i include 12 .js files in view for dhtmlxGrid… and feel that it is just a beginning.

    • Ivan,
      December 27, 2012 at 2:06 pm

      You can include a single dhtmlx.js (grab dhtmlxsuite package from the site) which includes all functionality.

      Also, you can include script tags in head section of course, there is no any limitations here.

  12. Ravichandran,
    April 1, 2013 at 5:41 pm

    It doesn’t work for me. can you please see my question in forum and give me the fix as soon as possible.

    link: http://forum.dhtmlx.com/viewtopic.php?f=19&t=29400&start=0

    • Ivan,
      April 3, 2013 at 8:16 pm

      Please see our replies in the forum.

  13. Claudio,
    June 15, 2013 at 4:33 pm

    Thank you for the great tutorial!
    I have a question:
    I tried to follow the mvc pattern as you show in this tutorial using a dhtmlxLayout to display the main application interface, but I cannot figure out what are the steps to work respecting the mvc pattern with a layout. The only way I can guess is to declare all the interface logic in the main index files. Do you know a more “mvc way” to do it? Can you provide a tutorial for yii and dhtmlxlayout in the future?
    Thank you and best regards

    • Ivan,
      June 19, 2013 at 4:05 pm

      Claudio, unfortunately there is no a better (more MVC) way to use dhtmlxLayout.

  14. Claudio,
    July 16, 2013 at 12:17 pm

    Thanks Ivan,
    I found a problem with dataprocessor, I had troubles to insert and update rows that have non a numerical “ID” containing underscores.
    I solved it modfying the code of “dataprocessor.php”.
    I think it may be a problem for more than a few users. I write it here because I’m not a licensed customer of dhtmlx and cannot submit support/bug tickets.

    Regards.

  15. Prawee Wongsa,
    October 3, 2013 at 8:54 am

    Thank you. so many benefit for me. ^^

  16. Chintan,
    March 19, 2014 at 9:18 am
  17. syamsuri,
    March 25, 2014 at 4:30 am

    Thank you for this tutorial. This is exactly what I needed.
    from indonesia

Leave a Reply