Zend Form provide very useful functionalities, like
- Easy way to create html forms and its elements.
- Built-in validation
- Built-in error messages
And so on.
Here I will give you some basic examples and provide you better approach for using Zend Forms.
Let us first see some examples of how and where we can create our Zend form.
The first place I mention would definitely be Controller/Action.
If you have
class IndexController extends Zend_Controller_Action
The require statement is compulsory if you don’t have
In your bootstrap.
The easiest way to create your zend form would be to place the following code into your indexAction method.
$form = new Zend_Form();
The above statement will create instance of the Zend_Form.
Once you create zend form instance, you will have access to all the functionality Zend Form is providing- we have mentioned some in the beginning, you can now call Zend_Form functions with $this.
Next step should be to add elements to your form.
Zend provide different ways to create and add elements to your form. E.g.
First create the element as
$username= new Zend_Form_Element_Text(“username”);
And set its label as
$submit = new Zend_Form_Element_Submit(“submit”);
You can create as many form element as you like and add it to your form.
Once your form is created, assign it to your view template as
The only thing you would need to do now is to display your form in your view-view/scripts/index/index.phtml, file as
This will display form as
You can create Zend Form as
$form = new Zend_Form();
“label” => “Username:”
“label” => “Submit”
This code will create similar form as above.
Athough you can create Zend form in your controller/actions, however this is not good approach to be used. The best approach would be to create separate directory for your foms and create separate php file for each form. I would recommend the following directory structure
If you have login form, create Login.php in “forms” directory and place the following code
class forms_Login extends Zend_Form
public function __construct(options=array())
$this->setAction(“your action here”); // this define form action attribute.
$this->setMethod(‘post/get’);// set method attribute.
// the code bellow will create element
$username = $this->CreateElement(‘text’,’username’);
// now add elements to the form as
The above code is very simple to explain. We are creating our class extending it from Zend_Form-it is necessary to prefix your form name with the directory name(forms_Login). By doing so we are inheriting all the functionality of the Zend_Form.
Next we are defining our constructor. It is necessary to call parent constructor before defining anything.
Another approach can be to override Zend_Form init() method and put the above code in that function.
Now once you create your form, next step is to create its instance in your controller/action and assign it to the view as
$form = new Login();