Sunday 29 May 2011

PHP Multilanguage Site Using Arrays

PHP Multilanguage

Here we can develop multilanguage site with the use of arrays

So, here we go:

First of all we need a configuration setting inside our script’s config.php file. For the sake of our example, we’ll add a manual variable change:

// language settings
$lng = 'en';

Next, our header file, dubbed header.php (could be head.php or top.php in your script) will contain these lines:

include('includes/config.php');
include('languages/'.$lng.'.php');

You now, obviously, have to create a languages directory and create a new file called en.php. This file will hold our array of words and expressions:

/*
@Package: My Multilanguage Script
@Language: English (English)
*/

$lang = array();

$lang['REGISTER'] = 'Register';
$lang['USERNAME'] = 'Username';
$lang['PASSWORD'] = 'Password';
$lang['LOGIN'] = 'Log in';
$lang['LOGOUT'] = 'Log out';
$lang['DASHBOARD'] = 'Dashboard';

Notice how I tried to keep the array index name as close to translation as possible. For example, you’ll have the string “Separate tags with commas” as $lang['SEPARATE_TAGS_COMMAS']. It’s easier after a couple of months when you’ll make changes.

Also, try to keep consistent naming of your language files, such as fr.php, de.php, ru.php, cn.php.

Now, call in you script . It will display “Register”, just as you translated it in your language file.

Scrolling div with Javascript

You can scroll div with javascript. You need to have one mainContainer which will contain the child for it. eg.

I will have mainArea div with child div myReport.







You need to fixed the height for the mainArea div with style







Now your div can scroll, You now need to write one line code in any javascript function

function scrollMainArea()
{
document.getElementById(“mainArea”).scrollTop = 0;
}

This will move your myReport div to show the top portion of your division.

Thursday 5 May 2011

Zend Framework: Storing session data in 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 = "Viral";

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.

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

Wednesday 4 May 2011

How to Charm Your Way Through Life

Charismatic people are those who have the ability to inspire and influence others. Such people often have an aura of magnetism surrounding them.

However, Charisma is not a magical power and can be acquired by anyone who wishes to. Following are the suggestions which can help you build up the charismatic factor in you.

Find Ease in Yourself
In order to feel charismatic, you need not incorporate any artificial swagger or machismo. You just have to feel comfortable in your own skin and emphasize your real self with others as well.

No Bargain
While trying to maintain their self-assertion, people often come across as aggressive. This, however, does not mean that you hide your individuality. You should find the ability to draw a line between assertion and aggression.

Accept Your Flaws
Charismatic people never fail to compliment someone or embrace their own weaknesses. Similarly, you should never shy away from admitting your mistakes. It not only increases your charm quotient but also makes you a better person.

Be Full of Life
Contrary to the pre-conceived notion that charming people have to be intelligent or witty, it is the good-humouredness of a person that can more hearts. So, don't try too hard to be too scholarly; just go ahead and have fun with the people around you.

Be Aware of Yourself
The key to becoming a charming person is to know yourself and your beliefs as it reflects in personality. A person who is unsure of himself fails to strike a positive impact on others. Discover yourself and let the light of your self-awareness shine upon others too.

Practice Makes Perfect
Being charismatic is a skill which which everyone can learn. You cannot expect to wake up one morning as the most charismatic individual on the planet just because you desired so. It has to be built over time and with precision. After all, nothing comes easy in life.

Monday 2 May 2011

How to Get Over with Negative Thoughts

Our thoughts are the doorway of our emotions. “I'm completely stuck in this” - if such thoughts crop up in your mind quite often, it's time to give a serious thought to the things going wrong. A possible reason can be the responsibility of playing of several roles in life.


Many times we experienceinsomnia, mood swings, emotional turmoil and uneasiness while carrying out various duties in our lives. This can further make you passive on many fronts in life.


We then lose all our positive energy and become the storehouse of negative energy.


Here are a few tips of regaining the lost positive energy in life:


Take Out Time for Yourself: Try and do a division of your heavy workload. Make a list of tasks which can be split into smaller chunks. If there are some tasks which you carry out regularly but at the back of your head you realise they aren't really important, give them up. Try and learn the art of time management. Make attempts to strike a balance between your personal and family life.



Bad Times would Eventually Go Away: Downbeat circumstances can become a cause of sorrow. But bear this in your mind that this time would eventually be over. Try and see if any benefits can be extracted from such harsh times. This would promote optimism in you.


Good Company: Try and avoid the company of people whose favourite pastime is exploring negativities in others. This can only aggravate your problem.



Think Positive: Don't let thoughts like: “I'm trapped”, “things are never going to change” etc. cloud your head. Easier said than done but you can at least give it a try.


At your Workplace: If you're finding it difficult to handle things in your office, do not hesitate in walking up to your boss and discussing things with him. These days many companies provide counseling to their employees.


Leisure Activities: Though clichéd but activites like watching movies, listening to music, gossiping, travelling can actually help you overcome negativities in your life.


Getaways: If you're stuck in the din and bustle of your city life, it's time to go for a nonchalant break. Plan getaways to hills, jungles, beaches et al (there's no point going to just another city for that would not help you escape from the usual uproar). You would feel rejuvenated and. Some personal experience here. I recently went for holidaying in the Corbett jungles. After coming back I felt refreshed and more optimistic.


Eat Healthy: Eating healthy food is a key to not just remain physically fit but also to attain good mental health. 

"If it is to be, it is up to me!"

A set of ten two-letter words to help from a new you


Have you heard of the rather unique funeral held in an office in New York some years ago? As employees of the firm came in to work one Monday morning, they were greeted by a solemn notice at the entrance: "The person responsible for inhibiting your growth died yesterday. The body has been placed in the cafeteria, till 2 pm today."


Sad to think a colleague had passed away, and curious who the person might be, the employees trooped into the cafeteria to pay their last respects. A crowd of company staff had gathered inside. 'Who is this chap who has been hindering our growth?' each wondered, as they walked up to the coffin to take a dekko. One by one, as each person took a look inside the coffin, there was shocked silence - and a look of disbelief.

Inside the coffin was a mirror. And below it was a placard on which was written: "There's only one person who can set limits to your growth. And that's YOU." Now that's a message we would all do well to remember.

When we find ourselves falling short of the success we think we deserve, we often blame our bosses, our employers, the industry, or the current favourite - the recession! Everyone and everything, in fact, except ourselves. For things to change in your life, you don't need to change your job, or your company or your town. You only need to change yourself. Start now. Adopt a new philosophy for your life. Tell yourself the magic phrase: "If it is to be, it is up to me!" It's not often that you can get a set of ten two-letter words to form one whole sentence. And no ordinary sentence but one, which has the power to become a life-changing philosophy for you, for me and for all of us: "If it is to be, it is up to me!" Just say it to yourself, believe in it, and see the difference.

The power to change our lives and chart our future lies within each of us. Resist the temptation to blame others for your plight. When you blame other people, you take away your inherent power to change. You weaken yourself. But by taking responsibility, you empower yourself to change your fortunes. And that one act - taking responsibility for yourself - is really what separates winners from losers.

Have you ever seen sailing boats wander into the sea? They all take off from one place, around the same time, and yet reach different shores. Why is that? The winds are the same. The water currents too are the same for all the boats. Yet, they reach different destinations, because, where the boat will reach is determined not by the direction of the wind, but by the set of the sails.

Our lives are like that too. So stop blaming the winds of your company policy or the currents of the economy. Stop worrying that you did not go to a premier B-School, or that you grew up in a non-English-speaking home. Take charge of your life. Change your mindset and get your thinking right. To reach your goals, it's important to set your sails properly. For things to get better, you need to get better. Need new skills? Invest in training yourself don't wait for your employer to do it. I find it puzzling that while young people spend money on trendy new clothes, and on new cellphones and on the monthly visit to the beauty salon, they want the company to spend money on training them, on making them better employees, smarter people. 'Training myself is not my responsibility' seems to be the general dictum!

For things to change, we must change our beliefs, and our mindsets. Do yourself a favour. Stick this ten-word aphorism on your bathroom mirror: "If it is to be, it is up to me!" And wake up to a new you.


Sunday 1 May 2011

Zend Framework Form(Zend_Form) tutorial

Here you can see 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.

Applying Zend_Form decorators to all elements

Hear is 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 Form Decorators

I’d felt a lot of pain when I first used Zend_Form. The reason was that I wasn’t able to layout form elements the way I wanted them to be. Zend was rendering elements in dt and dd whilst I was looking forward to place them in row and cells.
In short I wasn’t aware of Zend_Form decorators in the beginning and when I studied them for some time I felt uncomfortable using them.
So I decided to use html forms in my phtml files-template file. Though by doing so I achieved the desired layout however I missed entire facilities/functionalities that Zend_Form component provide us such as validation, filtering, dispaying error messages and so on.
When I first created form with Zend_Form component I was served with layout like the following.


Label on the top of the text/ password element.

This is because Zend Framework render form label in "dt" tag and text/password form element in "dt","dd" tag and put entire form element in "dl" tag by default.

Code rendered was 



<form method="post" action="">
<dl>
<dt><label for="agencyName">User Name:</label></dt>
<dd>
<input type="text" name="agencyName" id="agencyName" value="">
</dd>
<dt><label for="advertiserName">Password</label></dt>
<dd>
<input type="text" name="advertiserName" id="advertiserName" value="">
</dd>
<dt>&nbsp;</dt>
<dd>
<input type="submit" name="submit" id="submit" value="Login">
</dd>
<dl>
</form>


This was not the layout I was looking for. I was looking for 
layout like the following. 

 

To create form as above one need to put label and individual form element in "td" tag, put that "td" tag in "tr" tag and put all these in "table" tag. E.g 



<form action="" method="post">
<table>
<tr>
<td><label for="username">User Name:</label></td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td><label for="password">Password</label></td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" id="submit" value="Login"></td>
</tr>
</table>
</form>

Zend form decorators can be used to create above form.

If you are beginner or have little experience working with zend, you may be facing difficulties in rendering Form using Zend_Form the way you want.

In this post I am providing indepth and comprehensive study of how to use Zend_Form_Decorators.

So let’s get started.

Although in the beginning you may find it difficult to use Zend_Form decorators, however once you get used to it and understand the basics, you will find these quite easy, helpful and interesting.

To create the login form in the figure 2. you will need the following code 



class forms_LoginForm extends Zend_Form
{

public function __construct($option=null)
{

parent::__construct($option);

$this->setMethod('post');

$username=$this->CreateElement('text','username')

->setLabel('User Name:');

$username->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$password=$this->CreateElement('text','password')

->setLabel('Password');

$password->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$submit=$this->CreateElement('submit','submit')

->setLabel('Login');

$submit->setDecorators(array(

'ViewHelper',
'Description',
'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'td',
'colspan'=>'2','align'=>'center')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$this->addElements(array(

$username,
$password,
$submit

));

$this->setDecorators(array(

'FormElements',
array(array('data'=>'HtmlTag'),array('tag'=>'table')),
'Form'

));

}
}



Explanation:

First we extend our form from Zend_From and define our constructor. It is necessary to call parent class constructor before defining anything in your own constructor-by doing so our form will inherit all the functionality of Zend_Form.

After calling parent constructor we set our form method by simply $this->setMethod(‘post’).

Next we create text element and set its label.

The lines after setting label of the form are important because these lines give new look to our form. The code is quite simple. We call setDecorators() method of the form to override the default decorators behavior of the form.
The code 



$username->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));



is very simple. We are skipping “ViewHelper”, “Description” and “Errors” for now. We will explain it some other time. We can define our decorators for these things as well if we need in future. However leave it as these are for now.

After “Errors” we define array which tell Zend to override the default decorators of 



<input name="”username”" type="”text”">

. By doing so zend will wrap "input" tag in .

Next array define tag for label and put label in td tag as 



<td><label ..></td>

.

Next array define tag for the row of the form. This wrap 



<label ..>and <input>


in tr tag. The above code will create 



<tr>

<td>User Name:</td>

<td><input type=”text” name=”username”></td>

</tr>



However defining decorators for the submit button we have change the code a lit bit.

As label is appearing on the button so we don’t need to define decorator for the label. By leaving decorator for label undefined, it means zend will use its default decorator for the label of the submit button.

And as we want to put button at the center of the row, so we have defined 



array(array('data'=>'HtmlTag'), array('tag' => 'td',
'colspan'=>'2','align'=>'center')),



This will create html as 



<td colspan=”2” align=”center”><input type=”submit” ….></td>



Next we add elements to form as 



$this->addElements(array(

$username,
$password,
$submit

));



At the end we define decorators for the form-to wrap form elements in the html tag.

I have already said that zend wrap entire element in "dl" tag.

As we have wrap element in the "tg" and "tr" tag properly. So we need to wrap these "td" and "tr"’ in the "table" tag. To do so we have defined 



$this->setDecorators(array(

'FormElements',
array(array('data'=>'HtmlTag'),array('tag'=>'table')),
'Form'

));



This code will wrap all "tr" in "table" tag.

Although this form is simple and contain only two fields however you can create very large form by following this procedure.

Next I going to create a form that may help lot of souls. First see the following form.


You can clearly see we have put all the form elements in the single row.

The html of the above form is 



<table>
<tr>
<td>
<label for="username">User Name:</label>
</td>
<td><input type=”text” name=”username”></td>
<td>
<label for="password">Password</label>
</td>
<td><input type=”password” name=”password”></td>
<td align="center">
<input type="submit" name="submit" id="submit" value="Login"></td>
</tr>

</table>



You can clearly see that we have wrapped the elements in tags and then wrap those "td" tags in single "tr" tag and then "table" . To create the above form we will make very little changes in our code above.

The new code would be 



class forms_LoginForm extends Zend_Form
{

public function __construct($option=null)
{

parent::__construct($option);

$this->setMethod('post');

$username=$this->CreateElement('text','username')

->setLabel('User Name:');

$username->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr', 'openOnly'=>true))

));

$password=$this->CreateElement('text','password')

->setLabel('Password');

$password->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),

));

$submit=$this->CreateElement('submit','submit')

->setLabel('Login');

$submit->setDecorators(array(

'ViewHelper',
'Description',
'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'td',
'colspan'=>'2','align'=>'center')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr', 'closeOnly'=>'true'))

));

$this->addElements(array(

$username,
$password,
$submit

));

$this->setDecorators(array(

'FormElements',
array(array('data'=>'HtmlTag'),array('tag'=>'table')),
'Form'

));

}
}


You can see we done very minor changes in our form.

In the first element “username” setDecorators() we have changed our array as 



$username->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr', 'openOnly'=>true))

));



The only changes are in the last line of the array. We have now set ‘openOnly’ => true for the “row”. It means that we are wrapping elements of username in , however we are putting but opening it only- tag would not be closed when Zend will render this element.

Next 



$password->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),

));


Here we have defined only two arrays -third one is missing. The reason is we are wrapping elements in the "td" tag putting nothing for the row.

At the final change are made in the submit element setDecorators() method call as 



$submit->setDecorators(array(

'ViewHelper',
'Description',
'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'td',
'colspan'=>'2','align'=>'center')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr', 'closeOnly'=>'true'))

));


Here also we have made changes in the last line-array(array(‘row’)…..). we have defined ‘closeOnly’ => ‘true’. This will close the tag opened in the first element setDecorators() section.

The rest of the code is same.
The rest of the code is same.

In almost all the websites where you find form will compulsory field indicate those fields either by placing text or image next to that field.

Zend_Form setDescription() can help you out and give you an easy way to achieve this goal. Look at the following form.


In the form above we have placed image next to our username field to tell the user that username is compulsory field.

To achieve this you will need to do very little changes in your previous form.

Code to create the above form is 



class forms_LoginForm extends Zend_Form
{

public function __construct($option=null)
{

parent::__construct($option);

$this->setMethod('post');

$email = $this->CreateElement('text','username')

->setLabel('User Name:')

->setDescription('path/to/image');

$email->setDecorators(array(

'ViewHelper',
array('Description',array('tag'=>'','escape'=>false)),
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$password=$this->CreateElement('text','password')

->setLabel('Password')
->setDescription('path/to/image');

$password->setDecorators(array(

'ViewHelper',
array('Description',array('tag'=>'','escape'=>false)),
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$submit=$this->CreateElement('submit','submit')

->setLabel('Login');

$submit->setDecorators(array(

'ViewHelper',
'Description',
'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'td',
'colspan'=>'2','align'=>'center')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$this->addElements(array(

$username,
$password,
$submit

));

$this->setDecorators(array(

'FormElements',

array(array('data'=>'HtmlTag'),array('tag'=>'table')),

'Form'

));

}
}


If you compare the first form and this form code, you will see we have done very minor changes. If you compare this for with the first one, you will easily find the changes. However I will define these change for the beginners.

First we have added setDescription() method to our email and password elements of the form. This will add image as a description, however by default Zend will render description at the next row of the email as well as password fields. To put these images will need to define decorators for it. The only changes we will need to do in the setDecorators() methods are
Array(‘Description’,array(‘tag’=>’’,’escape’=>false)) at the place of “Description”. Look at the following code. 



$email->setDecorators(array(

'ViewHelper',
array('Description',array('tag'=>'','escape'=>false)),
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));


you can clearly see these changes in line 3. we have defined decorators for the description of the form element.