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.

Automatically refresh the web page every 5 seconds, with PHP

Redict the web page with PHP

you can easily redirect to the different web page using simple php script.By using PHP header() function you can easily redirect to new page without having new extra clicks.

the following PHP script redirect the user to bugphp.com

1 <?php
2 header( 'Location: http://www.bugphp.com/' ) ;
3 ?>

make sure,it will not work if you sent any data to the browser before this function.if you write echo or print or any HTML statements or functions before the redirection you will get an error,to avoid this use PHP output buffering as follows

1 <?php
2 ob_start();
3 echo 'header test';
4 header( 'Location: http://www.bugphp.com/' ) ;
5 ob_flush();
6 ?>

Automatically refresh the web page every 5 seconds, with PHP

1 <?php
2 $url=$_SERVER['REQUEST_URI'];
3 header("Refresh: 5; URL=\"" . $url . "\""); // redirect in 5 seconds
4 ?>

how to make Alphabet Navigation Menu with PHP?

In this post we are going to discuses about alphabet navigation.before that do you know generating alphabets in a loop.if don’t know look at below example once

1 <?php
2
3 for ($i=65; $i<=90; $i++) {
4 echo chr($i);// chr returns specific character
5 //out put :ABCDEFGHIJKLMNOPQRSTUVWXYZ
6 }
7 ?>

In the above example chr() function returns specific character & chr() also accepts negative numbers as an ascii code[char(-100)]

You can make above output with range() function,look the example :

1 <?php foreach(range('A','Z') as $i) {
2 echo $i; }
3 ?>

output:ABCDEFGHIJKLMNOPQRSTUVWXYZ

now you can easily understand below alphabet navigation menu

1 <?php
2 $LetterList = range('A','Z');
3 foreach ($LetterList as $litter) {
4 echo '<a href="http://example.com/letter.php?letter=' . $litter. '">' .$litter. '</a>'.' ';
5 }
6 ?>

Outpup : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

you can make above output in another way

1 <?php
2 $LetterList = array_merge(array('0-9'),range('A','Z'));
3 foreach ($LetterList as $value) {
4 echo '<a href="http://example.com/letter.php?letter=' . $value . '">' .$value . '</a>'.' ';
5 }
6 ?>

out put:A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The description of the functions used in this tutorial are as follows

chr() this function return a spesific character

range() this function crate an array containing range of elements

foreach()foreach is used to loop over all elements of an array

array_merge() this function merges one or more arrays