Use Zend_Form to create SQL table

A quick code snippet that uses a Zend form (in the case below, with subforms) to generate a SQL table create statement. Useful for scaffolding : create your form with Zend Form Elements then the SQL table automatically.

  1. <textarea rows="50" cols="80">
  2. create table yrbeaute (`id` int(10) NOT NULL AUTO_INCREMENT,<?
  3. foreach($this->form as $k=>$subform)
  4.     {
  5.         foreach($subform as $k=>$element)
  6.     { if (get_class($element)!="Zend_Form_DisplayGroup")
  7.      {
  8.    if ($element->getType()=="Zend_Form_Element_Select") $type="varchar(50)";
  9.     if ($element->getType()=="Zend_Form_Element_Radio") $type="varchar(50)";
  10.    if ($element->getType()=="Zend_Form_Element_Text") $type="varchar(255)";
  11.    if ($element->getType()=="Zend_Form_Element_Textarea") $type="text";
  12.    if ($element->getType()=="Zend_Form_Element_MultiCheckbox") $type="varchar(255)";
  13.          ?>
  14.  <?=$element->getName() ?> <?=$type?>,
  15.          <?
  16.     } else
  17.           foreach($element as $k=>$elem )
  18.               {
  19.                   ?><?=$elem->getName() ?> varchar(50),
  20.                   <?
  21.               }
  22.  
  23.     }}
  24. ?>  step int(5), `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  25.   PRIMARY KEY (`id`))</textarea>

5 Opensource applications built around Zend Framework

a lot of expereiences are currently being performed on the Zend Framework platform, but a few are really usable in production environement.

  • Magento is obviously the best example of how Zend Framework can bring power and ease  of development via a PHP enabled template system. The most popular opensource ecommerce application has been downloaded more that a million times and is still considered  a revolutionnary project after 2 years of production.
  • Digitalus CMS is a Zend framework based Content Management System. We covered it a while ago
  • Joobsbox is a job board application developped on top of Zend Framewor, not quite stable yet (nice implementation of hirearchical tree does not handle sub pages very well yet, worth the try)
  • Dodo is a perfect tutorial for starting with the Zend_Application environment, and it is also a good tasks application
  • EasyPhpApp is a CRUD generator that can save you time when working with a lot of database tables (see our previous article on Zend framework scaffolding)

and also you can try, tine 2.0, a powerful groupware application that uses extjs beautifully (covered a while ago too on this blog)

Cahaya, a cms for zend framework

Zend-cms-cayaha

At first sight, nothing really exciting comes from the newly released Cahaya CMS, built entirely around Zend Framework CMS : in fact the toolbar that switches the site to edit mode is an interesting implentation of  insite edition, that allows page building from selected and editable blocks, as illustrated below. The whole web content management interface is built with ext js widgets including drag and drop, and this looks promising, though apparently  quite complex at this early stage. I miss the hierarchical tree for page navigation in the admin, but let’s hope it’s coming.  go to http://cahaya-project.org/ for more.

Generic Data save with Zend Framework

This technical article hilights one the famous ideal goal we all want to achieve : scaffolding, CRUD, BREAD, call it what you want, all we want is to get rid of repetitive sql query writing.  Zend framework provides powerful data abstraction  and here are a few tips to use Zend_DB_Table to its best. Of course this article assumes you have an idea of MVC development with Zend Framework.

Why are we doing this ? in the course of writing ajax actions, we needed our controller to react to any POST provided by specific forms : whatever the fields in the form, we want them to be saved to our table. Code below is a specific implementation of a controller that responds to specific ajax queries. Please bear in mind that it is only provided as an example of generic query action. Other portions of code are not optimal, such as viewless actions in the renderAjax method, not the best.

[update 20090428] Alternative :  Smart save on Zend_Db_Table objects from zfsnippets

Controller Implementation

Our controller is a simple Zend_Controller_Action. We load the database model at init time, and specify the primary key  (node parameter) in a class variable. Note that our data model is also stored in a class variable.

  1. class UserController extends Zend_Controller_Action
  2. {
  3. public function init()
  4.     {
  5.         $this->session = new Zend_Session_Namespace(‘User’);
  6.       //  $this->view->translate = Zend_Registry::get(’Zend_Translate’);
  7.                 require_once ‘models/Users.php’;
  8.                 $this->data=new Users();
  9.                 $this->node = $this->getRequest()->getParam(node);
  10.                 WXC_Log::log("init node : " . $this->node);
  11.     }

Quick look at the model

at this stage I specify on particular function I like to implement in Zend Framework Models : the primary key ! Other functions of the model could include add, delete and update : we’ll see below that our generic data admin prefers to do the job in the controller.

  1. class Users extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_name = ‘users’;
  4.         public function primaryKey()
  5.         {
  6.                 $info = $this->info();
  7.                 return $info[primary][1];
  8.         }
  9. }

Back to the crontroller : the renderAjax method is a quick one that stops the view from being rendered. If you are a specialist of Zend Framework you will notice that this can be better performed with the contextSwitch action helper. Use the code below only for testing, for production you’d rather spend a few minutes learning about helpers !

  1.                 private function renderAjax()
  2. {
  3.                 $this->_helper->layout->disableLayout();
  4.                  $this->_helper->viewRenderer->setNoRender();
  5. }

Action !

Listing records is the first thing you want to look for when working at data scaffolding. the code below reads metadata from the table, lists all columns from your table, fetches data and returns them as JSON (ready for extjs grid display, by the way).

  1. public function listAction()
  2. {
  3.          $this->renderAjax();
  4.  
  5.           if (null === $select)    $select = $this->data->select();
  6.  
  7.       $thRowSet = $this->data->fetchAll( $this->data->select());
  8.  
  9.         $nodes=array();
  10.          $arrMeta=$this->data->info();
  11.                 $arrCols=$arrMeta[cols];
  12.  
  13. foreach($thRowSet as $row ){
  14.         $arr_node=array();
  15. foreach ($arrCols as  $v)
  16.         $arr_node[$v]=$row->$v;
  17.  
  18.         $nodes[]=$arr_node;
  19. }
  20.  
  21.         echo Zend_Json::encode( $nodes );
  22. }

The next step would be to add records : we have not worked on this yet so you’ll want to try this with tables that have a few records in them. The method below works with two types of data sets.

  1. Multiple column form submit :this would be the classical response to a from submission, where each field bears the NAME of the database field, and obvisouly the value is the data. Such forms are transmitted via FORM array with key / value pairs. We read the POST (getRequest->getParam) that match metadata built from the database table column array. We then provide a clean arrData array of new data for the update() method of our Zend_Db_Table instanciation. This method takes two arguments: the first is the associative array mapping columns to change to new values to assign to these columns. The second is the where clause that we built from the primary key
  2. Single column submit : the technique is useful when working with extjs in place editing, where one piece of code can edit multiple fields. The field variable contains the database column name and the value is the data. We add a check that matches the field against database table column names
  1. public function saveAction()
  2. {
  3.         $this->renderAjax();
  4. $id= $this->node;
  5.  $key = $this->data->primaryKey();
  6. $strWhere = $key. ‘=’  . $id;
  7.  
  8.  $arrMeta=$this->data->info();
  9.  
  10. // all columns submit
  11. $arrCols=$arrMeta[cols];
  12. $arrData=array();
  13. reset($arrCols);
  14. while (list($k,$v)=each($arrCols))
  15.         {
  16.                  if ($v!="parent_id"  &amp;&amp; $v!= $this->data->primaryKey()
  17.                   &amp;&amp; array_key_exists($v, $this->getRequest()->getParams()))
  18.                  {
  19.                         $arrData[$v]=$this->getRequest()->getParam($v);
  20.  
  21.                         }
  22.         }
  23.  
  24. //single column submit via field/ value
  25. if ($this->getRequest()->getParam(‘field’)!="")
  26. {$field = $this->getRequest()->getParam(‘field’);
  27. $value= $this->getRequest()->getParam(‘value’);
  28. $arrData[$field] =$value;
  29.  
  30. }
  31.  
  32.   if (is_array($arrData))
  33.         {
  34.           try{      $this->data->update($arrData,$strWhere);
  35.          echo 1;}
  36.           catch(Zend_Exception $e){  echo 0;}
  37.  
  38.         }
  39. else echo 0;
  40.  
  41. }

A good start for extjs development : Hope this is useful for you !!

Monday’s web applications

Javascript libraries

While EXTJS 3.0 is on the way with a roadmap setting deadlines for early 2009, Jquery continues its path on the way to serious lightweight alternative to the massive EXT : JX extension for Jquery includes the viewport paradigm on which relies every EXT JS application.

Web based interfaces

In spite of huge progress and impressive use of ease, Jquery is not there yet : for the development of applications many developers have chosen the exhaustivity of EXT JS. Have a look at google code hosted project in development : ecartcommerce, CMS jimw, both ext js and zend framework based. In the world of content management systems, mysource is making the news with a new video that demonstrates inline editing, and other exciting Rich Application features.

Zend Framework extensions

Zend framework might not be as popular as other famous programming frameworks such as CAKE PHP or symfony. But still it’s getting quite usable with version 1.7 approaching and a growing number of serious of libraries are hitting the ground. We’ve already covered code generation,  scaffolding and RAD with Zend framework in   previous articles, this article covers lower  level libraries from Zym Projet

Zym Project includes a powerful navigation abstraction that can help building pages hierachy in a CMS application for example. Other goodies include the bootstrap class, that takes all configuration from ini files (bootstrap class also exists in another ZF extension, ZENDEX). Some classes of Zym Project have been integrated into 1.6 official release of Zend Framework. API classes Reference guide is available online.

Zend Framework hierarchical Zend_Db_Table extension

After a few hours looking for a good implementation of recursive data with Zend Framework, I came across Hector Virgen’s table abstraction for nested recursive tables, which uses the efficiency of the Modified Preorder Tree Traversal method that retrieves descendents and ancestors faster that with the old parent_id reference. In fact parent_id is not needed any more but in the example below we will keep the parent_id implementation. My aim here is to implement a draggable tree with data from this Zend_DB_Table abstraction. Setting up ext js with Zend Framework is not that hard, especially when many tutorials have been posted around for extjs tree with other frameworks such as Cake PHP .
Read the rest of this entry »

Omeka : exhibit engine

what is nice about Omeka CMS is not the backend : you will find in the admin sandbox that most sections of the restricted area, while perfectly efficient, lack today’s common AJAX reactivity.  But on the front end, the result is stunning :  websites built with Omeka have all gone throught a graphic design expertise that  push the enthousiast to look more into the technology behind (Zend Framework). As such the tool fits perfectly into its mission statement : “web platform for publishing collections and exhibitions online. Designed for cultural institutions, enthusiasts, and educators, Omeka is easy to install and modify and facilitates community-building around collections and exhibits.

Generate code for Zend Framework

Can Zend Framework do scaffolding like Symfony or Cake ? No, would you say after downloading the framework and trying out. But a quick search out there shows that you’re not the only one thinking about it. In fact there are many code generators out there for PHP   : look out for Codecharge, codeigniter, or any cakephp like framework. What was missing was code specific for Zend Framework, which offers the great advantage of being developped actively and offers new versions often. A quick browse on french developers forum popped up a few applications to be tested, and looking a bit further I found some interesting implementations of scaffolding for Zend Framework :

Web developers, have a look at tine 2.0

For those interested in developping the best possible web based application, Tine2.0, formerly eGroupWare2.0, a combination of CRM and ERP,  is worth having a look at. Its multiple feature interface is one of the most intuitive multi panel screen you can imagine, built entirely out of javascript and HTML. Based on Extjs and Zend Framework, it demonstrates that those 2 popular technologies can -finally- work together to build sensible opensource applications with features of most sophisticated desktops : accordion menu that browses between various parts of the application, tere based menu for hierachical structures, dynamic grid for data scrolling, simultaneous record viewing below the data grid. The fact that the source code of Tine2.0 can be downloaded separately from packages you might already have installed ten times on your server will save you the hassle of finding interesting code lines. But i’s not only design we’re after here : PDF export at right click on  TIne2.0 contact management. More technical details would only bring enthusiasts on the project, especially after a quick look at developpers’WIKI where specific  conceptual choices are explained : MVC or not MVC, that is the question. Anyhow, when Rich Internet Applications is what you’re looking for, try out Tine20 !!