I started studying the Zend_Form component and understand most aspects of it. I know how to add form elements and set configuration options for them, how to apply form decorators, how to add validators and filters... But today i got stuck on the processing of those forms.
There's one particular thing that just baffles me. I'll illustrate it with an example which i kept as simple as possible.
First we create the form as a separate class. Nothing special here, just a username and password field and a submit button. We'll also add a label and some filters and validators to them.
class Login_Form extends Zend_Form
{
public function init()
{
$this->setaction('/user/login')
->setMethod('post');
$username = new Zend_Form_Element_Text('username');
$username->setLabel('Username:')
->setRequired(true)
->addFilter('StringToLower')
->addValidator('NotEmpty');
$password = new Zend_Form_Element_Password('password');
$password->setLabel('Password:')
->setRequired(true);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setValue('Submit');
$this->addElements(array(
$username,
$password,
$submit
));
return $this;
}
}
Next we'll create a 'user' action controller with a 'login' action method. Here, i want to check if the form got submitted (if not it should be displayed) and validate it. Notice the two identical lines of code. Although the $form object did not change in the mean time, the first produces no output, the second does.
class UserController extends Zend_Controller_Action
{
public function loginAction()
{
$form = new Login_Form;
// Check if form got submitted
if ($this->getRequest()->isPost())
{
// This does not produce output
echo 'Username: ' . $form->getValue('username');
if ($form->isValid($_POST))
{
// This does produce output (same line of code as above)
echo 'Username: ' . $form->getValue('username');
}
else
{
echo $form;
}
}
else
{
echo $form;
}
}
}
If i would just want the unfiltered values, I could get them from the request object with $this->getRequest()->getPost(). I want the filtered values though (the filters are defined in the Login_Form class) so I should get them from the form object with getValues(). I find it awfully strange that the $form object changes after calling isValid() on it (which just returns a boolean and does not alter the $form object). Any help with this would be very much appreciated!