Friday, July 31, 2009

Creating dojo datepicker with dojo script

Dojo date picker is nice and beautiful widget. The nice thing about any dojo widgets is that they can be easily attached to appropriate html tag. To assign date picker to input box take the following cod.


<html>
<head>
<script src=”path/to/dojo.js”>
require(‘dijit.form.DateTextBox’);
</script>
<style type=text/css>
@import "path/to/dojo/dijit/themes/tundra/tundra.css";
</style>
</head>
<body class= “tundra”>
<input type=”text” dojoType=”dijit.form.DateTextBox” name=”dd” id=”dd”/>
</body>
</html>



If you correctly include dojo.js and tundra.css, you will see a nice

Read More

Monday, July 27, 2009

Zend Framework, dojo and Json

I have already written about json in one, actually some of my articles. Cool functionality can be achieved using json. Thanks to http://www.json.org, http://www.zend.com and http://www.dojotoolkit.org for provide easier solutions.

I'm not gonna talk what these three are all about, but instead share a little secret about these.
Json creation in dojo is as simple as this.
var arr = new Array();
arr[0] = “apple”;
arr[1] = “ball”;
arr[2] = “cat”;

dojo.toJson(arr);


Using Zend to convert array into json took only one line of code.
Zend_Json::encode($arr);

And decoding- converting json to array, is as simple as this
Zend_Json::decode(json_string);

Tuesday, July 14, 2009

Apache: Setting virtual host on localhost

It was up to this task since yesterday. I haven’t done this before, setting sub domain- virtual host on local system. I tried a lot yesterday but in vain, however when I came to office today I configured it successfully.
As I was stuck in the middle and feel lot of pain, so I better write it for those facing the same issue.
Why I was up to this task?
Well, actually my client was facing problem and reported that session is not working properly on domain and sub domain. So I was having no way other than setting virtual host.
However before leaving yesterday, I talked to my client that I am unable to solve this problem. He told me that I shouldn’t be worried about it because he will take care of this issue. The more important thing is that when I arrived today, I found that the problem has already been solved. Thanks to him for giving my favor.
Thought the problem has been solved, but still is worthy to write a small post here because I have successfully solved the problem.
Before going to discuss it, I would like to tell you that the configuration has been taken place on window so the paths may not be same.
Let have a look.
First of all you will need to open.
C:\xampp\apache\conf\extra\httpd-vhosts.conf

I assumed that you have install xampp.
And add following lines to httpd-vhosts.conf file.

NameVirtualHost *:80


<VirtualHost *:80>
ServerName localhost
DocumentRoot "C:/xampp/htdocs/"
ServerAdmin admin@localhost
</VirtualHost>


<VirtualHost *:80>
ServerName mysite.com.localhost
DocumentRoot "C:/xampp/htdocs/mysite/"
ServerAdmin admin@mysite.com.localhost
<Directory "C:/xampp/htdocs/mysite/">
Options Indexes FollowSymLinks
AllowOverride FileInfo
Order allow,deny
Allow from all
</Directory>


Here I have defined server localhost pointing to my default htdocs directory and another host mysite.com.localhost pointing to "C:/xampp/htdocs/mysite/".
Another important thing is
Here you would need to specify the port. In my case its 80.
If you don’t specify the port on which apache listen, apache may take you to the same page for both the server. So be careful.

Next go to your Window/system32/dirvers/etc/ and open hosts file.
You will find
127.0.0.1       localhost

At the end of the file. Add following line next to it.
127.0.0.1    mysite.com.localhost

Reboot your system and you are done.

Method chaining in object oriented programming

In my previous article I discussed some of the nice thing of object oriented programming. Inheritance –creating sub classes from inheriting parent, contain all the attributes of the parent class plus its own. Polymorphism means different form, like overloading and overriding methods and dynamic binding- deciding which class in the inheritance tree should be called on runtime, are techniques that give great benefits to programmers.
In this article I am going to show you a simple but very useful trick while using “this” keyword for method chaining. “this” when use in the class, refer to the same class.
Consider the following example.
class Person {
protected $_name;
protected $_age;
protected $_gender;

public function setName($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
public function setAge ($age) {
$this->_name = $age;
}
public function getAge() {
return $this->_age;
}

public function setGender($gender) {
$this->_gender = $gender;
}
public function getGender() {
return $this->_gender;
}

}

In object oriented programming it’s always a good practice to define getter and setters. In php you can define __set and __get as setters and getter.

To create an object of the above class and define person properties, we will need to write the following code.
$person = new Person();
$person->setName(“person_name”);
$person->setAge(24);
$person->setGender(“male”);


And now If you want to get these values, write
$person->getName();
$person->getAge();
$person->getGender();


Well, if you want to set values using a single statement, you will need a code similar to this.
$this->setName(‘person_name’)->setAge(24)->setGender(“male”);

To achieve this, you will need to write the following statement in all your setters.
public function setName($name) {
$this->_name = $name;
return $this;
}

The only thing we need here is “return $this”. This statement return a reference to the same object.
Place this statement in your setAge() and setGender(), and now you can write
$this->setName(‘person_name’)->setAge(24)->setGender(“male”);

for setting all the three properties.
Any suggestion is welcome. Cheers

PHP: Object Oriented Programming

Object oriented programming concepts were introduced in PHP1.4, I guess.
How many people around you play with object oriented programming?
If not working in any kind of MVC frameworks, I guess very short number of people.
Developers are often used to structured programming and don’t bother themselves learning object oriented programming concepts and paradigm.
Well, when software engineers realized that it’d become very difficult to manage and maintain thousand lines of code as well as impossible to represent real world object in computer world, object oriented programming was introduced. Since then dramatic improvements have been made to OOP.

In object oriented programming inheritance, polymorphism, encapsulation, dynamic binding and exception handling has great value, usage and advantages, however class and objects are the most basic concept.

Class is blue print containing properties and method associated with same entity. Object is the instance of the class and is used to access properties and method of the class.
In addition to OOP, design pattern make jobs easier for the programmers.
Singleton, factory and specially MVC design patterns are very useful these days.

In singleton design pattern one object of the class exist throughout the life cycle of the software application. If programmer tries to instantiate another object of the same class, a reference to the object instantiated earlier, is granted.

A class implementing factory design pattern works as bridge between multiple classes. Consider an example of using multiple database servers like SQL Server and Oracle. If you are developing an application using SQL Server database as backend, but in future need to change backend database to oracle, you will need to modify all your code, if you haven’t written your code following factory design pattern.
In factory design pattern you need to do very little work to achieve this. A class implementing factory design pattern takes care for you and lessen your burden. Switching from database server won’t bother you at all. You just need to make some small changes in your configuration file.

Revolution of MVC design patterns cause dramatic changes in software development life cycle. Prior to MVC, developers were mixing code all around. It was difficult to figure out where the business code resides and where presentation code is written. Intelligent software engineers, though, were trying hard to separate their business logic from presentation logic; this however wasn’t effective enough for new comers to understand their code and to do necessary maintenance. Without the help of the person behind the project, it’d taken more time to understand the directory structure used.
These draw backs were mostly addressed when MVC design patterns were introduced.

In MVC design pattern M stands for Model. Model contains your application’s business logic.
V stands for View. It’s the presentation layer.
While C stands for controller that work as glue between view and model. From glue I mean it takes data from view and give it to the model, model then process the data and produced desired results. The data, thus obtained, is given to the view. Controller can also be compared to event handlers. It responds to certain events such as posting the data back to server by clicking submitted data.
Hopefully I will unveil some other fact about OOP and design pattern later some time.

Monday, July 13, 2009

Create dojo tab cotainer in Zend Framework

Try online: Tab Container
In my previous posts I discussed how to create accordion container holding accordion panes and border container having content panes.
In this article I am going to show you how easy it is to create tab continer that hold contents panes. Each content pane having different contents. Contents in one tab pane are shown at a time. when use click on the tab pane's title, contents in that tab pane are shown.
Before reading this post, you better read and implement what I have discussed in my article "Zend Framework and Dojo: configuration". Before creating tab continer and panes, you will need to understand and perform necessary configuration.I assume that you have read the post I have mentioned and have done the necessary configuration. Now let's get started.
First of all, you will need to create your controller as


<?php
class ContainerController extends Zend_Controller_Action
{
public function tabAction()
{

}
}


In the code above we have defined our ContainerController extending it from Zend_Controller_Action, and then we have defined our tabAction.
Now, the next step is to create tab.phtml in /application/views/scripts/container/ and place the following code in it.
<?php

$this->tabContainer()->captureStart('main-container',
array('design' => 'headline'),
array(
'style'=>'height:400px;width:800px'
));

echo $this->contentPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);

echo $this->contentPane(
'gallery',
'Contents of gallery here',
array('region' => 'left', 'title'=>'Gallery'),
array('style' => 'width: 200px; background-color: white;')
);

echo $this->contentPane(
'Blog',
'Blog post here',
array('region' => 'center','title'=>'Blog'),
array('style' => 'background-color: white;')
);

echo $this->contentPane(
'about',
'Information about your company etc',
array('region' => 'bottom', 'title'=>'About Us'),
array('style' => 'background-color: white;')
);

echo $this->tabContainer()->captureEnd('main-container');
?>


Here we first call captureStart() method of tabContainer() dojo view helper, giving it an id, and array containing tab container special attributes. Next we define content panes. Each content pane holds the data. The contents panes in the tab container will become tab panes.
each content pane is defined as
echo $this->contentPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);

Here "home" is the id of the content page, Next "string" is the contents that will appear in the tab pane. Next we have defined the array of the special attributes of the contents. Here title is the most important attribute. This title will appear on the tab. The last array contain css related attributes.
That's it. we have now written all necessary code for creating nice and beautiful Tab container.
Cheers.

Sunday, July 12, 2009

Zend Framework SQL Joins Examples

You may have custom of using advanced queries. It often requires writing complex queries if you are working on enterprise, large scale web application(s).
The use of joins can never be ignored.
Zend Framework developers have done tremendous job by providing simple method for implementing joins.
Lets look some examples of different type of joins.
Before discussing joins lets consider we have two tables, “authors” and “books”.
These are associated with author_id.

1. Inner Join
The simplest query will be
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinInner('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->order('column name ASC/DESC');

2. Left Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinLeft('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');

3. Right Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinRight('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');

4. Full Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');

5. Cross Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');

Once you write these queries, you can fetch a single row or multiple rows as

$result = $this->getAdapter()->fetchRow($select);
$result = $this->getAdapter()->fetchAll($select);

The first statement fetch only one row, while the second statement fetch the entire dataset.

Creating Json response in php, a nice example

While working with AJAX, you will need to get data after sending request to the server. You can use three ways to get the data form the server.
1. In xml Format
2. HTML Format
3. Json Format
Though xml has several advantages, however processing data at the client will put extra burden.
HTML, can easily be handle, is however more resource or you can say bandwidth extensive.
So JSON fall in the middle of both.
PHP provide a very easy way to create JSON response. Once you get data at client side you will need much later code to process response than xml document.
Let’s first look at the server side.
For example we have the following array.
$data = array(
'items'=>array(
'firstname'=>'faheem',
'lastname'=>'abbas',
'address'=>'pakistan'
)
);

To create JSON response, simply write
echo json_encode($data); 

This will give the following result
{"items":{"firstname":"faheem","lastname":"abbas","address":"pakistan"}}

Now at the client side to send AJAX request, you will need to create the following code.
Keep in mind that we are using prototype for making AJAX request.
<script>
function getData()
{
new Ajax.Request(

“http://localhost/getdata.php", /* this is url of the php file that create JSON response.*/
{
method:'post',
onSuccess: processData
}
);
}
function processData(rsp)
{
var response = eval('(' + rsp.responseText + ')');
var firstname = response.items(0).firstname;
var lastname = response.items(0).lastname;
var address = response.items(0).address;
}
</script>


That's it.

Creating dojo border container in Zend Framework

Try Online : Border Container
In my previous artilce I discuss how to create accordion container and panes. If you wish to create accordion container and panes, read my article "Creating dojo accordion Container in Zend".
If you don't know how to configure dojo and Zend Framework, read here.
In this article, however I am going to discuss how to create border container. Border continer divide our page in different section so that we can display different contents in those sectitons.

To create the border container we first need to create our controller as


<?php
class ContainerController extends Zend_Controller_Action
{
public function borderAction()
{

}
}


Now in your /application/views/scripts/container/border.phtml, place the following code.
<?php

$this->borderContainer()->captureStart('main-container',
array('design' => 'headline'),
array(
'style'=>'height:400px;width:800px',
'align' => 'center'
));

echo $this->contentPane(
'menuPane',
'This is the menu pane',
array('region' => 'top'),
array('style' => 'background-color: darkblue;color:white')
);

echo $this->contentPane(
'navPane',
'This is the navigation pane',
array('region' => 'left'),
array('style' => 'width: 200px; background-color: lightblue;')
);

echo $this->contentPane(
'mainPane',
'This is the main content pane area',
array('region' => 'center'),
array('style' => 'background-color: white;')
);

echo $this->contentPane(
'statusPane',
'Status area',
array('region' => 'bottom'),
array('style' => 'background-color: lightgray;')
);

echo $this->borderContainer()->captureEnd('main-container');
?>


Here we have called captureStart() method to start our border container, and then we have placed different content panes.
Each content pane has an "id", "contents" it holds, array containing content panes attributes, and an array containing css attributes.

Creating dojo accordion Container/panes in Zend

Try Online : Accordion Container
Dojo provide very easy and nice way of creating different containers such as accordion, tab, border, and stack etc.
These containers hold different type of panes. These different panes in turn use to hold contents. contents can be simple text or it can be complete html.
Zend Framework collaboration with Dojo has made things quite easy. Zend Framework provide view helpers to achieve different type of dojo functionality.
In this article I am going to discuss how to create Accordion Container. accordion Container hold accordion panes. Each accordion pane hold different contents and open in a stylish way when user click on the title of the pane.
In order to enable dojo helpers in you Zend Framework application, you will need to make some initial configuration. read my tutorial "Zend Framework and Dojo: configuration" before reading this tutorial. After successfull configuration create a controller called "ContinerController.php" in your controllers directory and place the following code in it.


<?php
class ContainerController extends Zend_Controller_Action
{
public function accordionAction()
{

}
}


We have only defined an action in our controller, putting no code at all. you however can put whatever code you wish.
Now in /application/views/scripts/container/accordion.phtml place the following code.

<?php

$this->accordionContainer()->captureStart('main-container',
array('design' => 'headline'),
array(
'style'=>'height:400px;width:400px'
));

echo $this->accordionPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);

echo $this->accordionPane(
'gallery',
'Contents of gallery here',
array('region' => 'left', 'title'=>'Gallery'),
array('style' => 'background-color: white;')
);

echo $this->accordionPane(
'Blog',
'Blog post here',
array('region' => 'center','title'=>'Blog'),
array('style' => 'background-color: white;')
);

echo $this->accordionContainer()->captureEnd('main-container');
?>


The code is pretty simple. we first call captureStart() method on accordionContainer(). this will start accordion container for us.
Once the accordion continer is started, we need to put accordion panes in it and at the end we will need to call captureEnd() method to end our accordion container.
The container holding the following accordion pane.
echo $this->accordionPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);

The above code call accordionPane() helper method. This dojo helper method take an "id", "contents" to be displayed in the accordion pane, an array containing the special attributes of the accordion pane, and array of css attributes.

Implementing Ajax with Zend Framework and Json

Well, while working with ajax, it better to have an xml as response. Xml, however need more coding and parsing on client side than json.
Zend framework provides very easy way to generate json response.
In this article I’m going to discuss how to create Ajax request using prototype and how to use Zend_Json to generate response.
For generating Ajax request, you will need to write
<script>
new Ajax.Request(
"url",
{
method: 'post',
parameters: {'val1': 1, 'val2': 2},
onComplete: displayResults
}
);
function displayResults(rsp)
{
var results = eval('('+rsp.responseText+')');
}
</script>


If response is the form of this
[
{"firstName":"Faheem","lastName":"Abbas","username":"fahim","email":"faheem.abbas@nxb.com.pk"},

{"firstName":"Shazil","lastName":"Hassan","username":"shazil","email":"shazil.hassan@yahoo.com"}
]


Then to acess the values of the first row, write
var firstName = results[0].firstName;
var lastName = results[0].lastName;

and the values of the second row can be accessed as
var firstName = results[1]. firstName;
var lastName = results[1].lastName;


To create Json response, you will need to write the following in your controller action
$users = new Users();
$username = $this->_getParam('username');
$select = $users->select();
$data = $users->fetchAll($select);
$results = $data->toArray();
echo Zend_Json::encode($results);


Keep in mind that “users” is our model, having the following code.
<?php
class Users extends Zend_Db_Table
{
protected $_name = "users";
}


That's it. cheers.

Thursday, July 9, 2009

Joomla component in Zend Framework example

Joomla is a nice CMS(content management system) and Zend Framework is once of the famous and widely adopted MVC Framework since its first release. One of the nice thing about Zend is its loosely coupled components.

Keep in mind that component in joomla and Zend Framework don’t refer to the same concept. Those who have worked in Joomla and Zend Framework know the difference.

In this article I’m not going to discuss what Zend and Joomla are all about and how component is different in both, but instead I’m going to share a little secret of how to develop joomla component in Zend Framework.

This article is not for those who are unaware of joomla and Zend.

Although joomla has own API for developing its components and modules, but you can use any php code in addition to its own API.

Reason is simple. Joomla is developed in php.

As Zend also used php behind the scene, so both can interact easily.

This was a bit of introduction.

While discussing all these things I assumed that you have little knowledge of joomla and have some knowledge of Zend Framework as well.

So let’s dig in.

Before writing any code you will need to successfully download and install joomla. Also download Zend and save it in the directory of your choice.

Once successfully installed joomla, open joomla/administrator/components and create a folder called com_yourcomp.

This is your component folder. You will need to create a file named yourcomp.php

If you want to add component in your administrator, the name should be admin.yourcomp.php.

That’s it, you have now created a the necessary directory structure for your joomla component development.

If you write a line “Hello world!” in youcomp.php or admin.yourcomp.php and browse your page as

http://localhost/joomla/index.php?option=com_yourcomp

you will see

“Hello world” printed.

These are the minimum requirements for developing joomla component.

Now we will using Zend Framework classes to add code to this file plus we will create Zend directory structure in order to work with Zend MVC.

Create following directory structure in your joomla/administrator/components.


Here you can see that my component name is com_advertisers.

In this directory I’ve

* admin.advertiser.php file
* application directory
* Joomla directory

The file admin.advertiser.php will serve as the bootstrap file.

Application directory contain specific directory for controllers, models and views.

The most important role is played by our Joomla directory in developing joomla component in Zend Framework.

This directory contain Controllers/Plugins/Router.php file.

This file contains code for calling specific action based on particular task. Before going to discuss code in the Router.php file, I’m going to show the code need in our admin.advertisers.php file.
<?php
define('ROOT_DIR', dirname(__FILE__));
set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/'
. PATH_SEPARATOR . ROOT_DIR . '/application'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . get_include_path()
);

require_once "Zend/Controller/Front.php";
require_once "Joomla/Controllers/Plugins/Router.php";

$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);

$frontController->registerPlugin(new Joomla_Controllers_Plugins_Router());
$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');

$frontController->dispatch();

In the first few lines I have included path to our com_advertisers directory, application directory and models directory.

Next I include Zend Front Controller files and Router.php file. I’ll discuss code in the Router.php file later as it contain the most important code.

Next I initialize front controller, register Router Plugin class which is defined in our Router.php file, set controller directory and call dispatch.

That’s it. We have now defined our bootstrap file.

One important thing is setting path to our library files that contain Zend component.

You can include path using set_include_path or set it in your php.ini file.

If you don’t include this path, your application will not work as you expected.

Now go to controllers directory and create IndexController.php and write the following code in it.
<?php

require_once('Zend/Controller/Action.php');
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
}
public function editAction()
{
}
public function saveAction()
{
}
}

Noting special here. I’ve created only three actions.

Go to your application/views/scripts directory and create directory called index and create three files index.phtml, edit.phtml and save.phtml.

The code above is what you will need to work with Zend Framework MVC. In order to integrate this code with joomla will need one additional files. In my case the file is Router.php

I have create this file in com_advertiser/Joomla/Controllers/Plugins/ directory.

The code contain in this file is
<?php

require_once('Zend/Controller/Plugin/Abstract.php');
class Joomla_Controllers_Plugins_Router extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$task = $request->getParam('task')
switch($task) {
case 'edit':
$request->setActionName('edit');
break;
case 'save':
$request->setActionName('save');
break;
default:
$request->setActionName('index');
break;
}
}
}

First I’ve include plugin class and then extended my Router class from Zend_Controller_Plugin_Abstract.

This Zend_Controller_Plugin_Abstract class contain a method preDispatch that is called before any controller is called in the routing process.

In the preDispatch method, I get the param “task” and write a switch statement to check this param. If it is edit, I give control to my editAction of the default IndexController. And similarly if it is save, I route request to my saveAction and by default, if no parameter is specified, the request will be dispatched to indexAction of my IndexController.

That’s it.

Now if you write

http://localhost/joomla/administrator/index.php?option=com_advertisers&task=save

It will show what ever you have written in your save.phtml file.

And similarly if you write

http://localhost/joomla/administrator/index.php?option=com_advertisers&task=edit

it will route you to editAction and will display whatever you have define there.

Any question and suggestion are welcomed.

Monday, July 6, 2009

Zend Framework: Zend_Config examples

Zend_Config is used to simply access to, and use of configuration data in Zend Framework application.
Zend_Config currently provide adapters for getting configuration data from xml and ini files. You can also store configuration data in array and pass that array to the Zend_Config constructore, this however is not a recommended way. Configuration data is mostly stored in either xml files or ini files.
In this tutorial I am going to put shad on the usage of Zend_Config and will give you example of how to keep data in array, ini and xml file and then use that using Zend_Config.
So let’s have a look.
To hold configuration data in form of array, you will need to write
$configArray = array(
'database' => array(
'adapter' => 'pdo_mysql',
'params' => array(
'host' => localhost',
'username' => 'user_name',
'password' => 'user_password',
'dbname' => 'database_name'
)
)
);


You can clearly see that we have defined an associative array containing database information.
Now as you have defined an array having configuration information, next step is to create an object of Zend_Config class passing the above array. The code will look like the following
$config = new Zend_Config($configArray);

Now, if you want to make database configuration, simply write
$db= Zend_Db::factory($config->database);

To store the above information in ini file, create config.ini somewhere in your application directory structure, and write the following code in it.
[development]

database.adapter = pdo_mysql
database.params.host = localhost
database.params.username = user_name
database.params.password = user_password
database.params.dbname = database_name


After defining ini file, simply write
$config = new Zend_Config_Ini(‘path/to/ini/config.ini’,’ development’);

in your application.

The database configuration is same as we done earlier.
$db = Zend_Config::factory($config->database);

Similarly if you like to use, xml file for you application configuration, create config.xml somewhere in your application directory structure and write
<?xml version="1.0"?>
< development >
<database>
<adapter>pdo_mysql</adapter>
<params>
<host>db.example.com</host>
<username>dbuser</username>
<password>secret</password>
<dbname>dbname</dbname>
</params>
</databse>
</ development >


Now either in your bootstrap file or where you want to initialize configuration, write
$config = new Zend_Config_Xml(‘path/to/xml/config.xml’,’development’);
For database configuration, simply write
$db = Zend_Db::factory($config->database);

That's it. cheers.

Sunday, July 5, 2009

Creating radio button in Zend Framework

Zend Framework Form: working with radio buttons
I have already discussed creation of Zend_From in my previous articles. In this article I'd discuss how to work
with radio buttons in Zend Framework Form.

In your Zend_Form, radio buttons can be created using two methods.
The first one is
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$gender = $this->createElement('radion','gender');
$gender->setLabel('Gender:')
->addMultiOptions(array(
'male' => 'Male',
'female' => 'Female'
))
->setSeparator('');
}
}


In the above code we first create our form by extending it from Zend_Form, override its init() method and setting its method and action attributes.
Next we create our radio button as
$gender = $this->createElement('radion','gender');

Here first argument specify that we want to create radion button element of the form and the second argument set the name
and id of the radio button element group. In the next line we call addMultiOptions() method giving its array of optional
values. and lost but not least, I am calling method setSeparator for placing both radio buttons on the same line. If this
setSeparator method is not called, each radion button will appear on separate line.

The above radio button can also be created as
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$gender = new Zend_Form_Element_Radio('gender');
$gender->setLabel('Gender:')
->addMultiOptions(array(
'male' => 'Male',
'female' => 'Female'
))
->setSeparator('');
}
}


The only difference in the above two example is that I have placed
$gender = $this->createElement('radion','gender'); 

With
$gender = new Zend_Form_Element_Radio('gender');

Both statements give the same result.

For setting different radio button options, you can also use the following method.
$gender->addMultiOption(‘male’,’Male’);
$gender->addMultiOption(‘female’,’Female’);

Ajax with Json and prototype in Zend Framework

I used JSon for the first time in my application today. Zend provide a very easy way to create JSon response.
In this article I would use Prototype to make ajax call. Hopefully you will now a bit about Prototype. Anyway if not, it would not be a hard job to understand it after reading my article.
So let’s get started.
Consider you have the following form.


The scenario is
When user select name from the dropdown, the entire form is filled with the data from the database for that particular user.

For this purpose you would need to have a controller/Action(s), a model and template file.
In your form attach the following attrib to your name element as

<?php
$name = $this->createElement('select','name');
$name->addMultioptions(array(
'select'=>'[select]',
'1' => 'Faheem',
'2' => 'Abbas'
));

$name->setAttrib('onchange','AutoFill()');

In the lines above we first create a dropdown give it two values. And then attach javascript function “AutoFill” function using setAttrib method.

In your controller initialize your form and assign it to the view template as
$form = new MyCustomForm();
$this->view->form = $form;

Now in your view template file write the following.
Write the following javascript code.
<script>
function AutoFill()
{
new Ajax.Request(
"<?=$this->url(array('controller'=>'user','action'=>'getdata'))?>",
{
method:'get',
parameters: {id: value},
onSuccess: FillForm
}
}

function FillForm(rsp)
{
var card = eval('(' + rsp.responseText + ')');
$('address1').value = card.items[0].address1;
$('address2').value = card.items[0].address2;
$('postalcode').value = card.items[0].postalcode;
}
</script>

To get response you will need to create an action and write the following code
<?php
class User extends Zend_Controller_Action
{
public function indexAction()
{
$form = new MyCustomForm();
$this->view->form = $form;
}

public function getdataAction()
{
$this->_helper->layout()->disableLayout();
$users = new Users();

$this->_helper->viewRenderer->setNoRender();
if ($this->getRequest()->isXmlHttpRequest()) {
$id = $this->_getParam('id');
$userData = $ users ->getData($id);
$dojoData= new Zend_Dojo_Data('id',$userData,'id');
echo $dojoData->toJson();
}
}
}

In the above code getdataAction is called using ajax call. In the first line we have disabled the layout, because we don’t need layout in case of ajax response. Next we create object of our model class(discussed later). Next we tell zend to disable view rendering.
In the next few lines we check for ajax request, get id, call our getData model method.
We then create dojo data object. This object provide a very useful method to convert data retrieved into json format. The method used is toJson().

In our model we have code like the following.
<?php
class Users extends Zend_Db_Table
{
protected $_name = 'users';

public function getData($id)
{
$select = $this->_db->select()
->from($this->_name,
array('address1','address2'….))
->where('id = ?', $id);
$result = $this->getAdapter()->fetchAll($select);
return $result;
}
}


That's it. Cheers.

select box in Zend framework: code and example

Though I’ve already discuss how to create dropdown in one of my previous article, however here I would discuss it a bit in detail.

You can create it using the following code.
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$country = $this->createElement('select',’countries’);
$country ->setLabel('Countries:')
->addMultiOptions(array(
'US' => 'United States',
'UK' => 'United Kingdom'
));
}
}


Or can also be created using the following code.
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$country = new Zend_Form_Element_Select('countries');
$country ->setLabel('Countries:')
->addMultiOptions(array(
'US' => 'United States',
'UK' => 'United Kingdom'
));
}
}


The options are hard code in both of the cases. This will not be requirement always.
Sometime or most of the time application need that drop down should be populated fetching records from the data base. So for this purpose I would like to implement the following code.
Fist in your model write the following.
<?php
class Countries extends Zend_Table
{
protected $_name = 'countries';
public function getCountriesList()
{
$select = $this->_db->select()
->from($this->_name,
array('key' => 'id','value' => 'country_name'))
$result = $this->getAdapter()->fetchAll($select);
return $result;
}
}

Keep in mind that the records we fetch will have an associated array having id as key and country name as value. If you don’t defined the above array, array(‘key’ => ’id’,’value’ => ‘country_name’), as I have defined, you will not get what you want. So be careful while fetching records for constructing drop down.

And now in your form write the following code.
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');

$countries = new Countries();
$countries_list = $countires->getCountriesList();

$country = new Zend_Form_Element_Select('countries');
$country ->setLabel('Countries:')
->addMultiOptions( $countriesList
));
}
}


In the above code the only thing changes is
1. I have instantiated model using
$countries = new Countries();

2. Call getCountiresList() method. And assign the list to the instead of assign hard coded values.

Sending Email with attachment in Zend Framework

You may have used Php for sending emails in your application. I haven’t experienced it in plain php, so I don’t know whether its easy or difficult. I, however, know that Zend Framework provide very easy way for sending emails. You can even attach files with your email with single method call.
In this article I am going to discuss how to send email with attachments. Please do tell me whether it helped you or not.

In your controller, write something like this.
$emial_body = “<table><tr><td>Body of the email</td></tr></table”;

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($email_body);
$mail->setFrom('support@example.com', 'Example');
$mail->addTo('user@abc.com', 'Username');
$mail->setSubject('Sending email using Zend Framework');
$mail->send();


This, although, will send email, however it’s not a good approach to create email in your controller as your mail body may contain thousands of words.

The best approach is to create a template, that contain the contents that will act as body of the email. To achieve this, create a file called emailExample.phtml in your /application/views/scripts/templates/ directory. And write the contents you want to put, those contents will serve as body of the email you are going to send.

I am having the following code in my emailExample.phtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<table>
<tr>
<td>
all my contents here.
</td>
</tr>
</table>
</body>
</html>




Now in your controller, write
$myView = new Zend_View();
$myView->addScriptPath(ROOT_DIR . '/application/views/scripts/templates/');
$html_body = $ myView ->render(emailExample.phtml');

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($html_body);

$mail->setFrom('support@example.com', 'Example');
$mail->addTo('user@abc.com', 'Username');
$mail->setSubject('Sending email using Zend Framework');
$mail->send();


Here we are first creating an instance of Zend_View, call addScriptPath() to add script path- directory path where our template file reside and which serve as body of our email.
We then get the template by calling render() method on that view object, giving it the name of the template. The rest of the process is same, creating Zend_Mail object, setting body and so on.
Another question come to mind is how
to send an attachment?
This is pretty simple too.
First you will need to get the contents of the file, by calling a method file_get_contents(), like this.
$fileContents = file_get_contents(‘path/to/file’);

And then call a simple method called createAttachment (), as
$file = $mail->createAttachment($fileContents);

And set the name of the attachment as
$file->filename = "yourfile.doc";

That’s it. Cheers.

Saturday, July 4, 2009

Zend Framework building complete application

Well, I have written lots of separate article on Zend Framework. Hopefully most of folk out there searching for valuable help may have gotten some from my articles.
This time my objective is to share everything with you, from basic configuration till to building complete Zend Framework application.
This article will cover
1. How to make initial configuration.
2. How to use Zend_Auth for authentication
3. Using Zend_Session for handling sessions
4. What are models and how to create them
5. Using Zend_Db to handle backend database for storing valuable information.
And much more.
So let’s get started.
1. Creating directory structure and making initial configuration
Zend Framework is based on MVC design patterns. MVC stands for Model, View, Controller. A simple definition of MVC design pattern is to separate business logic from presentation logic.
In order to work with Zend Framework MVC design pattern, you’ll need to make necessary directory structure. There are various ways of making directory structure, I, however will use the most easier to create and understand structure.

The structure I created is.
html_root
/application
/controllers
IndexController.php
/models
Users.php
/forms
LoginForm.php
/views
/scripts
/dojo
index.phtml
/libaray
/Zend
/js
/css
/images
/index.phtm


On the top level we have html_root directory, containing application directory, library, js, css and images. It also contain index.phtml called our bootstrap file. This file contain all our configuration code. Further more application directory contain controller, models forms and views directories. Library directory contains Zend components. Js contain all our js files, css contains css files and images contains all images used in our application.
On the hard drive our directory structure looks like

Keep in mind that controllers directory contain our entire controllers, form directory contain all forms used in our application. Model contains php files contain our business logic. Views/scripts contain template files against each controllers.

Now as we have made necessary directory structure, next step is to make necessary configuration in our bootstrap file.
2. Making necessary configuration in our bootstrap- index.php file.
The most important file, that will get all request and route them to specific controllers. It contain code for setting include path, initializing front controller, set controllers path and call dispatch method.
<?php
define('ROOT_DIR', dirname(__FILE__));

set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/library'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . ROOT_DIR . '/application/forms'
. PATH_SEPARATOR . get_include_path()
);

require_once "Zend/Loader/Autoloader.php";
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);

$frontController = Zend_Controller_Front::getInstance();

$frontController->throwExceptions(true);

$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');
$frontController->dispatch();
?>


The code is very simple to explain. The first line define path to our root directory.
The next lines set include path to /library, /application/models and /application/forms.

Next lines are very important
require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();


Help in loading all php files we need in our application. If we don’t use this code, we will need to include require_once statement to load php files needed.

In next lines we get instance of the front controller, set controllers directory and call dispatch method.
Front controller is responsible for handling the user request. It takes the request and on specific criteria take appropriate action.
That’s it. Its our configuration file. Simple and easy.

3. Creating controllers and views
In html_root/application/controllers, create IndexController.php and put the following code in it.
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
}
}


Every controller must be extended from Zend_Controller_Action and can contain as many methods as possible. Method defined in controllers is called action. Once you create action in the controller, next step is to create view template. For this purpose, in html_root/application/views/scripts/, create index/index.phtml and put the following code in it.
Hello world


That’s it.
Now if you browse
http://localhost/html_root/

You will see
Hello World
If you don’t see “Hello world” printed, read the above guide lines again.
As we have now successfully created directory structure and bootstrap file, its time to make other necessary configuration for database.

4. Configuration for working with database
How a web application can be completed without usage of database. Different web application uses different database. Some uses Mysql, other SQLite, SQL server and Oracle. One of the nice thing about Zend Framework is that it support multiple database servers.
Here we are going to making configuration for Mysql server.
For database configuration, first create config.ini in html_root/application/ and write the following code in it.
[general]
db.adapter = PDO_MYSQL
db.params.host = localhost
db.params.username = root
db.params.password =
db.params.dbname = zend


Now in your bootstrap file make the following changes.
<?php
define('ROOT_DIR', dirname(__FILE__));

set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/library'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . ROOT_DIR . '/application/forms'
. PATH_SEPARATOR . get_include_path()
);

require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();

$config = new Zend_Config_Ini(ROOT_DIR.'/application/config.ini', 'general');
$db = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($db);


$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');
$frontController->dispatch();
?>


First we load our config.ini file that contain our database configuration. Next we call static factory method of Zend_Db giving it $config->db for database configuration and at the end we set default adapter for our database tables.
That’s it. We have now done all necessary configurations.
Next step is to store and retrieve data from database
5. Working with database data
Now we are going to make an application that will save, display and edit data in the database.
First execute the following query.
CREATE TABLE `users` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`firstName` VARCHAR( 50 ) NOT NULL ,
`lastName` VARCHAR( 50 ) NOT NULL ,
`username` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 100 ) NOT NULL ,
`password` VARCHAR( 50 ) NOT NULL
)


This query create a table called users in the database.
Next step is to create model against this table. In your html_root/application/models/ create Users.php and write the following code in it.
<?php
class Users extends Zend_Db_Table
{
protected $_name = "users";
}


The only thing we have done is extend our Zend_Db_Table and define name of the model. This name must be same as the database table name.
Now in your html_root/application/controllers/IndexController.php, write
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data;
}
}


After making changes in IndexController.php, next step is to make changes in html_root/application/views/scripts/index/index.phtml. write the following code in it.
<h4>List of users</h4>
<h5><a href="add" style="color:blue">Add new user</a></h5>
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tboody>
<?php foreach ($this->data as $d) {?>
<tr>
<td><?=$d['firstName']?></td>
<td><?=$d['lastName']?></td>
<td><?=$d['username']?></td>
<td><?=$d['email']?></td>
<td><a href="edit/id/<?=$d['id']?>" style="color:blue">Edit</a></td>
</tr>
<?php }?>
</tbody>
</table>


This will show the list of users.
Next we are going to create a form for adding data to users table.
In your html_root/application/forms/ create CustomForm.php and write the following code in it.
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
//$this->setAction('add');

$id = $this->createElement('hidden','id');
$firstname = $this->createElement('text','firstname');
$firstname->setLabel('First Name:')
->setAttrib('size',50);
$lastname = $this->createElement('text','lastname');
$lastname->setLabel('Last Name:')
->setAttrib('size',50);
$username = $this->createElement('text','username');
$username->setLabel('Username:')
->setAttrib('size',50);
$email = $this->createElement('text','email');
$email->setLabel('Email:')
->setAttrib('size',50);
$password = $this->createElement('password','password');
$password->setLabel('Password:')
->setAttrib('size',50);

$password2 = $this->createElement('password','password2');
$password2->setLabel('Confirm Password::')
->setAttrib('size',50);
$register = $this->createElement('submit','register');
$register->setLabel("Register")
->setIgnore(true);

$this->addElements(array(
$firstname,
$lastname,
$username,
$email,
$password,
$password2,
$id,
$register
));
}
}


We have successfully created our form, next we are going to write necessary code in our IndexController.php
Write the following code in it
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data->toArray();
}

public function addAction()
{
$users = new Users();
$form = new CustomForm();
$this->view->form = $form;


if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->insert($formData);
}
}
}
}


The code in addAction create form, get posted data, check whether password and confirm password match and then insert data in the users table.

Now create add.phtml in html_root/application/views/scripts/index/ and write the following code in it.
<h3>Add User</h3>
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>


Next we are going to create action for editing the users table data. Write the following code in the your IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
//$this->_helper->layout->disableLayout();
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data->toArray();
}

public function addAction()
{
$users = new Users();
$form = new CustomForm();
$this->view->form = $form;


if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->insert($formData);
}
}
}

public function editAction()
{
$users = new Users();
$form = new CustomForm();

$id = $this->_getParam("id",1);
$select = $users->select()
->where("id = ?",$id);
$data = $users->fetchRow($select);
$form->populate($data->toArray());


if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->update($formData,"id = $id");
}
}
$this->view->form = $form;
}

}


The above code fetch the data and populate the form, and then get the posted data and update the users table based on the id.

Create edit.phtml in html_root/application/views/scripts/index/ and write the following code in it.
<h3>Edit User</h3>
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>


6. Create authentication application
As now we have created database application successfully, we are going to create authentication application.

(i). Creating login form
in your html_root/application/forms/ create LoginForm.php and write the following code in it.
<?php
class LoginForm extends Zend_Form
{
public function init()
{
$this->setName('login');
$this->setMethod('post');

$userName = $this->createElement('text', 'userName',array('label' => 'username' ));
$userName->addFilters(array('StringTrim'))
->addValidator('StringLength', false,array(5,50))
->setValue('')
->setRequired(true);

$password = $this->createElement('password','password',array('label' => 'password' ));
$password ->setRequired(true)
->addValidator('StringLength', false,array(5,50))
->setValue('');

$submit = $this->createElement('submit','save',array('label' => 'login'));
$submit->setRequired(false)
->setIgnore(true);

$this->addElements(array(
$userName,
$password,
$submit,
));
}
}


In the above form we add two elements, a text box for entering username and password field for entering user password. We also add submit input box.
(ii).Next we create AuthController.php in html_root/application/controllers/ and write the following code
<?php
class AuthController extends Zend_Controller_Action
{
public function loginAction()
{
$form = new LoginForm();
if ($this->getRequest()->isPost()) {
$values = $this->_request->getPost();
if ($form->isValid($values)) {
$users = new Users();
$auth = Zend_Auth::getInstance();
$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter());
$authAdapter->setTableName('users');
$authAdapter->setIdentityColumn('userName');
$authAdapter->setCredentialColumn('password');

$authAdapter->setIdentity($values['userName']);
$authAdapter->setCredential($values['password']);
try {
$result = $auth->authenticate($authAdapter);
} catch (Zend_Exception $e) {
$this->view->errorMsg = $e->getMessage() . "<br>";
}

if ($result->isValid()) {
$data = $authAdapter->getResultRowObject();
$sess = new Zend_Session_Namespace();
$sess->username = $data->useruame;
echo "Welcome <b>".$data->username.'</b><br>You successfully logged in.';
} else {
echo "invalid username or password try again.";
}
}
}
$this->view->form = $form;
}
}


In login action we initialize our login form, check for submitted data. We then instantiate our user model as well as Zend_Auth. Setting table name, identity column and credential column. We then pass values submitted through form to identity column and credential column. After setting these things we call authenticate() method.
This authenticate column perform authentication for us.
We then call isValid() method that return true or false based on the authentication.
If isValid() return true, we get the user specific information by calling getResultRowObject() method.
We then create session and assign username to it.
The last thing we will need to create is view template against login action. In html_root/application/views/scripts create auth/login.phtml and write the following code in it.
<fieldset style="width:400px">
<legend>Login</legend>
<?php
echo $this->form;
?>
<div><a href="../index/add" style="color:blue">New user Sign up here</a></div>
</fieldset>


That’s it. Our login authentication. For registration, you can use add form I have previously created.
I think its enough for now. I will discuss other things later on hopefully.

Friday, July 3, 2009

Creating a nice Dojo Form in Zend Framework

Well, after writing few separate article about Zend Framework and dojo, I feel that I’d need to write a complete Zend_Dojo_Form. So here I am with complete example.
I am going to explain everything step by step.
1. Download Zend Framework latest version
Download least stable version from http://www.zend.com. Copy external/dojo to js/.
Hopefully you will create your directory structure as
html_root
/application
/controllers
DojoController.php
/models
/forms
CustomDojoForm.php
/views
/scripts
/dojo
index.phtml
/libaray
/Zend
/public
/js
/dojo
/css
/images
/bootstrap.php
/index.phtm

It’s not compulsory to create the similar directory structure I have created, this can vary. For best practice read Zend Quick start from Zend Framework documentation.

2. Enable dojo in the bootstrap file

I am not going to discuss everything you will need to have in your bootstrap file. I am explaining only the line of code needed to enable dojo.
You may have initialized your view in the bootstrap file as
$view = new Zend_View();
if you haven’t, you will need to write the following code.
$view = new Zend_View(); 
$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);

If you already have
$view = new Zend_View();
in your bootstrap, no need to initialize it twice.
The second line is compulsory. It add helper path. This means that your view now can access all the helpers in library/Zend/Dojo/View/Helper/ directory.
In the next lines, I initialize viewRenderer, add view to it, and add viewRenderer to HelperBroker.
That’s it. We have now made all necessary changes in our bootstrap file.
3. Making necessary changes in your layout file.
Well, if are newbie. You will need to understand two step view before making the following changes. Read my article http://zendguru.wordpress.com/
The changes we will need in our layout file are
<?php
$this->dojo()->setDjConfigOption('usePlainJson',true)
->addStylesheetModule('dijit.themes.tundra')
->setLocalPath("http://localhost/zend/public/js/dojo/dojo/dojo.js");

echo $this->dojo();
?>

<body class="tundra">

Nothing hard to understand here. In the first line we set dojo configuration option. In the second line we add style sheet module, and the third line we add path to our dojo.js file.
After setting these option, we call dojo() helper method as
echo $this->dojo();

We have now made the entire necessary configuration in our bootstrap and layout file. It’s now time to play with Zend_Dojo_Form.
4. Creating Zend_Dojo_Form
Creating a dojo form as simple as this.
<?
class DojoForm extends Zend_Dojo_Form
{
public $_selectOptions;
public function init()
{
$this->_selectOptions=array(
'1' => 'red',
'2' => 'blue',
'3' => 'gray'
);

$this->setMethod('post');
$this->setAttribs(array(
'name' => 'masterform'
));
$this->setDecorators(array(
'FormElements',
array(
'TabContainer',
array(
'id' => 'tabContainer',
'style' => 'width:660px; height:500px',
'dijitParams' => array(
'tabPosition' => 'top',
)
),
'DijitForm'
)
));

$textForm= new Zend_Dojo_Form_SubForm();
$textForm->setAttribs(array(
'name'=> 'textboxtab',
'legend' => 'Text Elements',
'dijitParams' => array(
'title' => 'Text Elements',
)
));
$textForm->addElement(
'TextBox',
'textbox',
array(
'value' => 'some text',
'label' => 'TextBox',
'trim' => true,
'propercase' => true,
)
);
$textForm->addElement(
'DateTextBox',
'datebox',
array(
'value' => '2008-07-05',
'label' => 'DateTexBox',
'required' => true,
)
);
$textForm->addElement(
'TimeTextBox',
'timebox',
array(
'label' => 'TimeTexBox',
'required' => true,
)
);
$textForm->addElement(
'CurrencyTextBox',
'currencybox',
array(
'label' => 'CurrencyTexBox',
'required' => true,
'currency'=>'USD',
'invalidMessage' => 'Invalid amount',
'symbol' => 'USD',
'type' => 'currency',
)
);
$textForm->addElement(
'NumberTextBox',
'numberbox',
array(
'label' => 'NumberTexBox',
'required' => true,
'invalidMessage'=>'Invalid elevation.',
'constraints' => array(
'min' => -2000,
'max'=> 2000,
'places' => 0,
)
)
);
$textForm->addElement(
'ValidationTextBox',
'validationbox',
array(
'label' => 'ValidationTexBox',
'required' => true,
'regExp' => '[\w]+',
'invalidMessage' => 'invalid non-space text.',
)
);
$textForm->addElement(
'Textarea',
'textarea',
array(
'label' => 'TextArea',
'required' => true,
'style' => 'width:200px',
)
);

$toggleForm= new Zend_Dojo_Form_SubForm();
$toggleForm->setAttribs(array(
'name' => 'toggletab',
'legend' => 'Toggle Elements',
));
$toggleForm->addElement(
'NumberSpinner',
'ns',
array(
'value' => '7',
'label' => 'NumberSpinner',
'smallDelta' => 5,
'largeDelta' => 25,
'defaultTimeout' => 1000,
'timeoutChangeRate' => 100,
'min' => 9,
'max' => 1550,
'places' => 0,
'maxlength' => 20,
)
);
$toggleForm->addElement(
'Button',
'dijitButton',
array(
'label' => 'Button',
)
);
$toggleForm->addElement(
'CheckBox',
'checkbox',
array(
'label' => 'CheckBox',
'checkedValue' => 'foo',
'uncheckedValue' => 'bar',
'checked' => true,
)
);
$selectForm= new Zend_Dojo_Form_SubForm();
$selectForm->setAttribs(array(
'name' => 'selecttab',
'legend' => 'Select Elements',
));
$selectForm->addElement(
'ComboBox',
'comboboxselect',
array(
'label' => 'ComboBox(select)',
'value' => 'blue',
'autocomplete'=>false,
'multiOptions' => $this->_selectOptions,
)
);
$selectForm->addElement(
'FilteringSelect',
'filterselect',
array(
'label' => 'FilteringSelect(select)',
'value' => 'blue',
'autocomplete'=>false,
'multiOptions' => $this->_selectOptions,
)
);

$this->addSubForm($textForm,'textForm')
->addSubForm($toggleForm,'toggleForm')
->addSubForm($selectForm,'selectForm');
}
}






I don’t think I can explain everything in the form. Just giving you a clue.
I’ve created three sub forms, a text form contain elements such as textbox, date textbox, time textbox etc, a toggle sub form contain elements like number spinner, button and checkbox, and a select sub form containing select box and filtering select. I also have set different attributes for these elements.

3. Instantiating Zend_Dojo_Form in your controller
Your DojoController must have the following code.
class DojoController extends Zend_Controller_Action
{
function indexAction()
{
$form= new DojoForm();
$this->view->form= $form;
}
}


I don’t think anything needs to be explained.

4. Displaying form in template
Your template in views/scripts/dojo/ called index.phtml must have the following code.
<?php
echo $this->form;
?>