Zend MVC Framework – forms with dojo / dijit decorators tutorial

I started developing my first application with the Zend Framework using the MVC approach – following the tutorial (http://framework.zend.com/docs/quickstart) is a good entry point, but as soon as you need some “advanced” features, it gets a little tricky.
In my application i will use the integrated Dojo-library, which offers powerful form elements and ajax features – but the integration of Dojo into my applicaion took me a lot of research in the docs – so here is my way to get it work (based on ZF 1.8.1):

Directory structure & Bootstrap

Copy the directory externals/dojo (which comes with the ZF package) to your public directory – in my case, this was /public/js/dojo

Now we need to add an entry to the Bootstrap.php to register the Dojo-ViewHelpers to our application:

protected function _initViewHelpers() {
$this->bootstrap('view');
$view = $this->getResource('view');
$view->addHelperPath(dirname(__FILE__) . '/views/helpers', 'MRV_View_Helper');
$view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper');
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer() ;
$viewRenderer->setView($view) ;
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
}

Register dojo in the layout / view

The dojo – javscript sources must be available in our views – the best way to achieve this is to load them in the main layout – file – in my case layouts/scripts/layout.phtml

<?php
if ($this->dojo()->isEnabled()) {
$this->dojo()->setLocalPath($this->baseUrl().'/js/dojo/dojo/dojo.js')
->addStyleSheetModule('dijit.themes.tundra');
echo $this->dojo();
}
?>

Important: Don’t forget to add the base class name of the dijit theme to your DOM – otherwise, the styles will not be loaded correctly:


<body class=”tundra”>

Use Dijit widgets in your form

To add widgets to our form, the procedure is mainly the same like adding an Zend_Form to the application – the main difference is to derive the class from Zend_Dojo_Form instead of Zend_Form:

class MRV_Form_UserLogin extends Zend_Dojo_Form
{
public function init()
{
$password = $this->addElement('PasswordTextBox', 'password', array(
'filters'    => array('StringTrim'),
'regExp'         => '^[A-Za-z0-9]{3,}$',
'required'   => true,
'label'      => 'Password:',
'invalidMessage' => 'Invalid password; ' .
'must be at least 3 alphanumeric characters',
));
}
}

This example adds a dijit pasword text box with nice javascript validation to our form. Starting your application, you should see the form with the dijit element. For a detailed description of available dijit form decorators, visit the zend framework documentation

3 thoughts on “Zend MVC Framework – forms with dojo / dijit decorators tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *