Zend Form: How do I make it bend to my will?

后端 未结 14 1523
你的背包
你的背包 2021-01-29 18:53

I\'ve read the manual many times, I\'ve scoured the posts offered by Google on the subject, I have even bought a couple of books that deal with ZF. Now, why am I still confused?

14条回答
  •  逝去的感伤
    2021-01-29 19:37

    Barrett Conrad's advice is what I would have suggested. Also, keep in mind that you don't need to use a form object to render your form.

    One thing you could do is create a form in your view script that has elements with the same name as a form class.

    Your HTML form:

    Your class:

    class LoginForm extends Zend_Form
    {
        public function init()
        {
            $username = $this->createElement('text','username');
            $username->setRequired(true);
            $this->addElement($username);
    
            $password = $this->createElement('password','password');
            $password->setRequired(true);
            $this->addElement($password);        
        }
    }
    

    Your form class reflects your HTML form, each element in your class has its own validators and requirements. Back in your action you can create an instance of your form class and validate your post/get vars against that form:

    $form = new LoginForm();
    if ($this->_request->isPost()) {
        if ($form->isValid($this->_request->getParams())) {
            // do whatever you need to do
        } else {
            $this->view->errors = $form->getMessages();
        }
    }
    

    You can display the the error messages at the top of your form in one group, using this method.

    This is a basic example, but it allows you to have total control over the presentation of your form without spending the time to learn to use decorators. Much of the strength of Zend_Form is in its validation and filtering properties, in my opinion. This gives you that strength. The main draw back to a solution like this is that your view script HTML form can become out-of-sync with your form class.

提交回复
热议问题