Showing posts with label Zend Framewrork. Show all posts
Showing posts with label Zend Framewrork. Show all posts

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);

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

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;
?>

Thursday, July 2, 2009

Create Dojo grid in Zend Framework- a nice example

About a month or two earlier when I used dojo calendar in my application and write article about the Zend Framework and dojo I was wondering why zend make collaboration with zend. But today when I created a grid using zend dojo I feel the real power of the dojo in Zend framework. In this article I am going to give a simple example and create a grid using Zend framework and dojo.

At the end of this tutorial we will have a grid like the following

So let’s feel the power of dojo in zend.
First execute the following query for creating a table.
CREATE TABLE 'jobs' (
'id' int(11) NOT NULL auto_increment,
'title' varchar(50) NOT NULL,
'description' text,
'posted_date' datetime default NULL,
PRIMARY KEY ('id')
)

This will create a table in your database.

Create a model in your models directory and write the following code in it.
class Jobs extends Zend_Db_Table_Abstract
{
protected $_name='jobs';
public function getJobsData()
{
$select = $this->_db->select()
->from($this->_name);
$results = $this->getAdapter()->fetchAll($select);
return $results;
}
}


and save this table as Jobs.php

In the code above, we first extend our model from Zend_Db_Table_Abstract, define its name and define our custom function getJobsData() that fetch all the rows in the jobs table. We return the results as an array.

Next create a controller JobsController in you controller’s directory and place the following code in it.
<?php
class JobsController extends Zend_Controller_Action
{
public function viewAction()
{
}

public function recordsAction()
{
$jobs = new Jobs();
$data= $jobs->getJobsData();
$dojoData= new Zend_Dojo_Data(’id’,$data,’id’);
echo $dojoData->toJson();
exit;
}
}

In the above code we create two action view and records. We have placed nothing in the view action. In the recordsAction, we create an instance of Jobs model class.and then call its getJobsData() method which will give us an array of records. Next we create an instance of Zend_Dojo_Data() and give the fetched data to it. And finally we echo the data converted it into the Json.

We don’t need to create a view for the records action because we have placed exit it the end of this action which will stop rendering of the view. As we will call this action form our grid view template page so no need to define phtml file for it.

However we will need to create template file for our viewAction. In scripts/views/ directory create view.phtml file and place the following code in it.
Zend_Dojo_View_Helper_Dojo::setUseDeclarative();
$this->dojo()->setLocalPath('http://localhost/Zend/js/dojo/dojo/dojo.js')
->addStyleSheetModule(’dijit.themes.tundra’)
->addStylesheet('http://localhost/Zend/js/dojo/dojox/grid/_grid/tundraGrid.css');
echo $this->dojo();

<script type="text/javascript">
dojo.require("dojox.data.QueryReadStore");
dojo.require("dojox.grid.Grid");
dojo.require("dojo.parser");
</script>
<body class="tundra">
<div dojoType="dojox.data.QueryReadStore" jsId="activeStore", url="records"></div>
<div dojoType="dojox.grid.data.DojoData" jsId="model" rowsPerPage="20″ store="activeStore"></div>
<table id="activePastes" dojoType="dojox.grid.Grid" model="model" style="height:300px; width:700px;">
<thead>
<tr>
<th field="id">Id</th>
<th field="title">Title</th>
<th field="description">Description</th>
<th field="posted_date">Posted</th>
</tr>
</thead>
</table>
</body>


Keep in mind this is the main template file where we are creating our gird.

In the first statement I told zend to use declarative instead of programmatic behavior which is default. Next I set local path and add specific stylesheets. Then in the javascript code I used statement

Dojo.requre(’dojox.data.’) etc

To include specific dojo js modules.

In the body tag I specify a class “tundra”. This is important for the stylesheet I have added.

Next tow div’s and table are the main code for creating grid.

The first div fetch the records from the url specified. This url may be different if you fetch records form the other controller or source. Please specify valid url otherwise you will not get what you want.

The next div act as a bridge between our first div and the table. This div take data from the first div and give it to the table for display purposes.

Keep in mind that all the attributes of the div’s and table are compulsory. Removing any of the attribute may result in unvalid records or empty page. So define everything that I have defined. Once you become able to display your records, you can play with these attributes.

Zend Framework: Storing session data in database

In one of my previous post I wrote how to save session data in the database. The reason behind saving session data in database is that data become more secure and can be easily retrieved later on.
Let’s look how simple and easy it is to save session data in database using Zend_Session_SaveHandler_DbTable in Zend Framework.
1. Creating database table for holding session data
Before writing code you will need to create a table in the database for holding session data. Execute the following query for this purpose.
CREATE TABLE `session` (
`id` char(32),
`modified` int,
`lifetime` int,
`data` text,
PRIMARY KEY (`id`)
);


2.Making necessary configuration in your bootstrap file.
You will only need only few lines of code in your bootstrap file.
After making database configuration in your bootstrap file, write the following code.
$config = array(
'name' => 'session',
'primary' => 'id',
'modifiedColumn' => 'modified',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime'
);

Zend_Session::setSaveHandler(new
Zend_Session_SaveHandler_DbTable($config));
Zend_Session::start();

In the $config array we tell the name of the table that will store the session information, primary key of the table, column that will store the session modification timestamp(*nix timestamp), column that will store the session data, and the column that save the information about how long the session will last.

After defining this configuration array we call setSaveHandler() method- static method, of the Zend_Session. This setSaveHandler() method accept Zend_Session_SaveHandler_DbTable object. Zend_Session_SaveHandler_DbTable take configuration array as an argument.

We have now done all the necessary configuration. The only thing we will need to do now is to start our session. Session can be started in the bootstrap file, however it’s not necessary for the session to be started here. You can start it in any controller you needed.

Anywhere in your controller, write
$namespace = new Zend_Session_Namespace();
$namespace->name = "faheem";


and check your session table. The table will not only hold session id, but also the modified timestamp of when session was modified, life time of the session and the session data in special format.
Try it. Its really cool.

Applying Zend_Form decorators to all elements

After writing two posts on how to setDecorators to different form elements I think it is now time to provide a simple way to set decorators to all form elements at once.
Take a look at the following code.
class SimpleForm extends Zend_Form
{
public function __construct($options = null)
{
parent::__construct($options);
$countryList=array(
'United States',
'United Kindom',
'Pakistan'
);

$firstName = $this->createElement('text', 'firstName');
$firstName ->addValidator('alnum')
->addValidator('regex', false, array('/^[a-z]+/'))
->addValidator('stringLength', false, array(6, 20))
->setRequired(true)
-> setLabel('First Name:')
->addFilter('StringToLower');

$lastName = $this->createElement('text', 'lastName');
$lastName ->addValidator('StringLength', false, array(6))
->setRequired(true)
-> setLabel('Last Name:');

$address1 = $this->createElement('text', 'address1');
$address1->setLabel('Address1:')
->addValidator('StringLength', false,array(3,50))
->setValue('')
->setRequired(true);

$address2 = $this->createElement('text', 'address2');
$address2->setLabel('Address2:')
->addValidator('StringLength', false,array(3,50))
->setValue('')
->setRequired(false);

$postalCode = $this->createElement('text', 'postalCode');
$postalCode->setLabel('Postalcode:')
->addValidator('StringLength', false,array(3,15))
->setValue('')
->setRequired(false);

$city = $this->createElement('text', 'city');
$city->setLabel('City:')
->setValue('')
->setRequired(false)
->setAttrib('tabindex','6');

$state = $this->createElement('text', 'state');
$state->setLabel('State:')
->setAttrib('maxlength', 2)
->setValue('')
->setRequired(false)
->setAttrib('tabindex','7');

$country = $this->createElement('select', 'country');
$country->setLabel('Country:')
->setAttrib('class','select')
->addMultiOptions($countryList)
->setRequired(false);

$phone = $this->createElement('text', 'phone');
$phone->setLabel('Phone:')
->setAttrib('maxlength', '25')
->setValue('')
->setRequired(true);

$emailAddress = $this->createElement('text', 'emailAddress');
$emailAddress->setLabel('Email:')
->addValidator('StringLength', false,array(5,50))
->addValidator('EmailAddress')
->setValue('')
->setRequired(true);

$this->addElements( array (
$firstName,
$lastName,
$address1,
$address2,
$postalCode,
$city,
$state,
$country,
$phone
));

$this->setElementDecorators(array(
'viewHelper',
'Errors',
array(array('data'=>'HtmlTag'),array('tag'=>'td')),
array('Label',array('tag'=>'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))
));

$this->setDecorators(array(
'FormElements',
array(array('data'=>'HtmlTag'),array('tag'=>'table')),
'Form'
));
}
}

If you have read my previous post on decorators, you will easily understand the code. However those how are new to my blog and decorators may need some explanation.
As usual we are extending our form from Zend_Form, define our constructor, call parent constructor and then define our elements.
The most important line are after we add elements to our form. The code
$this->setElementDecorators(array(
'viewHelper',
'Errors',
array(array('data'=>'HtmlTag'),array('tag'=>'td')),
array('Label',array('tag'=>'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))
));

simply set decorators to all the elements to the form elements. Here we are define that close label in “td”, form elements in “td” and put both these in “tr”.
If you want to set decorators to only few elements then
$this->setElementDecorators(array(
'viewHelper',
'Errors',
array(array('data'=>'HtmlTag'),array('tag'=>'td')),
array('Label',array('tag'=>'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

),array('firstname','lastname'));

This code will set decorators to only fistname and lastname element of the form. Rest of the form elements will be render in the default decorators.
At the end we define
$this->setDecorators(array(
'FormElements',
array(array('data'=>'HtmlTag'),array('tag'=>'table')),
'Form'
));

This define the form level decorators. We are putting “table” tag after “form” tag. So all the row will be wrapped in table.

Zend Framework Session usage and examples

Session handling was one of the boring topic in plan php atleast for me, but in Zend Framework it really shines. If you like to work with Object oriented programming, you will definitely become fan of it.
In this article I’m going to discuss some useful techniques of using Zend Framework Session and Session namespace.
Keep in mind that Both Zend_Session and Zend_Session_Namespace extends abstract class Zend_Session_Abstract. So both inherit methods avaliable in Zend_Session_Abstract automatically.
If you want to go under the hood, you can open Zend/Session/Abstract.php and have a look at the functions available.
Instead of delve into the function available, I’d rather discuss some useful techniques.
Although you can create Zend_Session class object, however I would recommend Zend_Session_Namespace object instead. You can instantiate session as
$sess = new Zend_Session_Namespace(’MyNamespace’);

Here the argument is optional, however it is better to pass it. If don’t pass, Zend Session Namespace will assign its name a string “default”.
To store values, you will need to do the following.
$sess->username = ‘you_name’;

Later in your code, you will need to do the following to retrieve value from the session.
    $session = new Zend_Session_Namespace(’MyNamespace’);

$userName = $sess->username;

This was a simple example of how to assign values to session and later retrieve. Now I’m going to discuss some of its important method.
To check whether or not session exist, write the following.
    If (Zend_Session::sessionExist()) {

// do something.

}

sessionExist() is static method available in Zend_Session.

Another very important method is rememberMe() available in Zend_Session. This is used to make your session persistent.
Its syntax is
Zend_Session::rememberMe(60*60*24*7);

The number passed as an argument specify for how long the session will be available. What I have done means that session will be there for a week.
To destroy this you will need to call the following function on the logout of your application.
Zend_Session::forgetMe();

Another method
destroy(bool,bool), take two Boolean arguments. This destroy the entire persistent data. Keep in mind that Zend_Session_Namespace data will not be destroyed. You can retrieve that data even after you call
Zend_Session::destroy(false);

To completely logout you will need to do the following
Zend_Session::destroy(true);

We now passed true instead of false.
The above methods were anyhow related to Zend_Session class. To check the individual namespaces you can use the following function
Zend_Session::namespaceIsset(’MyNamespace’);

This will check whether the specified namespace has been set.
To unset the particular namespace, you will need to write the following.
Zend_Session:: namespaceUnset(’MyNamespace’);

There are plenty of other options available. But I don’t thing you will mostly need those.

If you do need extra functionality, don’t hesitate to open Zend_Session_Abstract.php, Zend_Session_Nampspace.php, and Zend_Session.php.
If you still finding it difficult to understand, do post your comments. I’d be glad to give you solution to your problem.

Wednesday, July 1, 2009

Zend Framework and dojo checkbox example

Few weeks back, I used dojo check box in my Zend framework application. Scenario was a bit different at that time. I was submitting Zend dojo form on the click event of the checkbox. When I created a form and submitted that onclik, It didn’t give me desired results.
I set its checked value to 1 and unchecked value to 0, however when I submited it always gave me a single value. I was looking for 0 and 1, but it always gave me 0. I thought that It was because I was not using proper submit button for the posting of form.
However when today I used checkbox in normal zend dojo form, it gave me the same result. Oh God, how to fix it.
However as I have played with dojo js files, so I got the solution.
Let’s tell you the trick.
First of all create check box as
$checkbox= $form->createElement(
'checkBox',
'checkbox',
array(
'label' => 'Tricky check box',
'checkedValue' => 1,
'uncheckedValue' => 0
)
);

Now add onclick event to this checkbox element as
$checkbox->setAttrib('onclick','changeValue()');

Now in your view, where you display this form, write the following javascript function
<script>
function changeValue()
{
if(dijit.byId('checkbox').checked){
dijit.byId('checkbox').setValue('1');
} else {
dijit.byId('checkbox').setValue('0');
dijit.byId('checkbox').checked=false;
}

}
</script>

The above code isn’t simple?

Hmm. First we see if we have checked the checkbox, if yes we assign value 1 to it, if not we assign it value 0 and set its checked status to false. This will uncheck the checkbox.

That’s it. Submit your form and you will get desired results.

Doesn’t it help you. Do you have smarter solution than this.

Tell me……

Zend Framework Form(Zend_Form) tutorial

I got “The Zahir”, a novel by Paula Coelho about a month back, very sweat one and highly intrigued. It was highly entertaining and most importantly author shared his experiences in a nice way. I learned plenty of new ideas.
Eh, you may think that I am insane, supposed to write about Zend Framework, but discussing a novel.
Well, novel can not only be a good companion of yours, but it also put shade of light on simple things from many angles. This make you think dynamically.
If you are solving a puzzle or implementing your logic, do not think straight forward, give multiple tries and chose a more appropriate solution. Solving a problem will not be hard. You should chose a solution that require less code, small maintenance overhead and most importantly one that will be less resource intensive.
Now lets stick to the topic and discuss how you can use Zend_Form component for creating html form easily, handling filters and errors messages and how to see how easily you can fetch data from the data source and present that in html form and let the visitors change/modify the existing data and save changes to the data source.
I am gona break this topic in three steps.
1. Creating Zend_Form
Although I’ve already discussed creation of Zend_Form in some of my articles but it will be better to discuss it here again.
Creating Zend form is simple is this.
class CustomForm extend Zend_Form
{
public function init()
{

}
}

defined a class by extending it from Zend_Form. This allow access to many of methods already defined in Zend_Form.
The only thing you need to do is to override init() method and create your own element such as input box, select statement, checkboxes, radio buttons and so on.
Defining your own elements don’t take much code. Have a look at the following code.
class CustomForm extend Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('process/form');

$username = $this->createElement('text','username');
$username->setLabel('Username:')
->setAttrib('size',50);

$this->addElement($username);
}
}

In the code above we have overridden init() method of Zend_Form, set the form request method and action and then defined input element called username. You can put as many elements in this form as you wish. The last statement is used to add element to the forms. To add several elements to the form at once, use addElements() passing array of elements as an argument. You will look an example in the next example.

My entire form look likes
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');

$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
));
}
}


Most of the functions are simple and self explanatory. The only method that I think I’d better explain here is setIgnore() method. The method setIgnore() has a very valuable usage. Well, if we see the entire form you will feel that we need all values when form is submitted. The only value we don’t need is the value of the submit button as this only used to submit the form. We are not interested in its value, so we call setIgnore() method passing Boolean value true.

2. As we have now created a form, next step is to create its object in controller and write code that will save data for us. Create a controller as
class UsersController extends Zend_Controller_Action
{
.....

public function addAction()
{
//$this->_helper->layout->disableLayout();
$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);
}
}
}
}

What we are doing here, is pretty simple. Create an object of Users model. Well I haven’t discussed Users model yet. I would discuss it for you soon. The next line creates an object of the form created earlier. Next we assign the form to the view template, in our case the template is add.phtml.
Next few lines are of much importance.
We check whether the request is first one or the post back. If form has been submitted, method $this->getRequest()->isPost() return ture. In this case we will need to take care of the data being submitted.
To handle the post back we get the data been posted back through form, check its validity, check if the password and confirm password matches, and insert the values in the “users” table using $users->insert(); statement.
If form is not valid, the code for inserting the data in the database will not be executed.
Now lets discuss “Users” model.
We have a table in our database called “users” containing different fields such as username, firstname, lastname etc.
We will need to create our model as
class Users extends Zend_Db_Table
{
protected $_name = "users";
}


That’s it, a simple model.
3. The third step in creating a full fledge form application in Zend Framework is presentation layer, called view/template.
In your scripts/users/ directory create add.phtml and put the following code in it
<h3>Add User</h3>
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>


The code above is self explanatory.
The above process only shows a form and submits data to the database. If you want to create edit form, you will need to make a bit of change in your controller.
Let’s create another action called editAction containing the following code.
class UsersController extends Zend_Controller_Action
{
.....

public function editAction()
{
//$this->_helper->layout->disableLayout();
$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']);
//Zend_Debug::dump($formData);exit;
$users->update($formData,"id = $id");
}
}
$this->view->form = $form;
}

}

You can clearly see that I’ve made only few lines of changes.
First I get the id of the user through $this->_getParam() method. I then create a select statement on the users table and then fetch a row. Once I get the data row, I populate the form using populate() method.
The only thing you will need now, is to create a view template in your scripts/users/ directory named edit.phtml and write the following code.
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>


Well I was thinking to explain everything in three steps, but I think it would be incomplete if I don’t explain how to show the data inserted in the database. For this reason I going to add 4th step.
4. Showing list of data
Create an action called indexAction in your controller with the following code.
class UsersController extends Zend_Controller_Action
{
public function indexAction()
{
//$this->_helper->layout->disableLayout();
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data->toArray();
//Zend_Debug::dump($data->toArray());
}

.....

}

First we create an object of our mode. And then fetch the data using the fetchAll() method. The last statement assigns the fetched data to the view template.
Now create scripts/users/index.phtml and write the following code in it.
<h4>List of users</h4>
<h5><a href="add">Add new user</a></h5>
<table>
<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']?>">Edit</a></td>
</tr>
<?php }?>
</tbody>
</table>

Here we are creating a table that shows the list of data. I don’t think this need to be explained.