In this example, we create a form with text boxes, select boxes, radio buttons, check boxes, text areas, buttons, and fieldsets. We also use validators, filters and decorators.
Components used in this example
- Zend_Form
- Zend_Form_Element_MultiCheckbox
- Zend_Form_Element_Password
- Zend_Form_Element_Radio
- Zend_Form_Element_Select
- Zend_Form_Element_Submit
- Zend_Form_Element_Text
- Zend_Form_Element_Textarea
- Zend_Validate_Abstract
- Zend_View
Implementation of the form to fill
- We define default values to show as a template.
class MyForm
{
// We define default values to show as a template.
private $_defaults = array(
'confirmation' => 'yourpassword',
'email' => 'your-address@mail.com',
'firstname' => 'Your first name here',
'gender' => 'male',
'lastname' => 'Your last name here',
'login' => 'yourlogin',
'more' => 'Enter more information about you here...',
'password' => 'yourpassword',
'profile' => array('house', 'car'),
'title' => 'mr',
);
Form processing- We create the form.
- If no parameters are passed, we do not validate the form.
- If one or more parameters are passed we try to validate the form.
- If the user clicked on the reset button, we reset the form.
- If the user requested to display the example, we populate the form with the default values.
- And we revalidate the form with the default values. The example is expected to be valid!
- If the form is not valid, we display the error messages.
- If we catch an exception, we return the error message.
public function process()
{
$data = array();
try {
// We create the form.
$form = new MyCustomForm;
$form
->setMethod('post')
->setElementFilters(array('StringTrim'))
->setIdentity()
->setCredentials()
->setAction();
if (empty($_POST)) {
// If no parameters are passed, we do not validate the form.
$result = 'Please fill the form and submit!';
} else {
// If one or more parameters are passed we try to validate the form.
$isValid = $form->isValid($_POST);
if ($isReset = $form->reset->getValue()) {
// If the user clicked on the reset button, we reset the form.
$form->reset();
$result = 'The form has been reset!';
} else if ($form->example->getValue()) {
// If the user requested to display the example,
// we populate the form with the default values.
$form->populate($this->_defaults);
// And we revalidate the form with the default values.
// The example is expected to be valid!
$form->isValid($form->getValues());
$result = 'The form was filled with an example!';
} else if ($isValid) {
$result = 'Your form is valid!';
} else {
// If the form is not valid, we display the error messages.
$result = 'Your form has errors!';
$form->addDecorator('FormErrors', array('placement' => 'append'));
}
$isReset or $data = array(
'VALUES' => $form->getValues(),
'MESSAGES' => $form->getMessages());
}
} catch (Exception $e) {
// If we catch an exception, we return the error message.
$result = $e->getMessage();
}
return array($form, $result, $data);
}
}
No comments:
Post a Comment