0

setRequired(TRUE)と他のバリデーターを含むテキストボックスと、IndexControllerの単純な送信ボタンを含む単純なZendフォームがあります。

私の質問は、別のコントローラーが私の投稿フォームを処理して検証することは可能ですか?

Login.php

<?php

class Application_Form_Login extends Zend_Form
{

    public function init()
    {
        $username = $this->createElement('text', 'username');
        $username->setLabel('Username:');
        $username->setRequired(TRUE);
        $username->addValidator(new Zend_Validate_StringLength(array('min' => 3, 'max' => 10)));
        $username->addFilters(array(
                new Zend_Filter_StringTrim(),
                new Zend_Filter_StringToLower()
                )
        );
        $this->addElement($username);

        // create submit button
        $this->addElement('submit', 'login',
                array('required'    => false,
                'ignore'    => true,
                'label'     => 'Login'));
    }}

IndexController.php

<?php

class AttendantController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $loginForm = new Application_Form_Login();
        $loginForm->setAction('/Auth/process');
        $loginForm->setMethod('post');
        $this->view->loginForm = $loginForm;
    }
}

AuthController.php

class AuthController extends Zend_Controller_Action
{
    public function processAction()
    {
        // How to validate the form posted here in this action function?
        // I have this simple code but I'm stacked here validating the form

        // Get the request
        $request = $this->getRequest();
        // Create a login form
        $loginForm = new Application_Form_Login();
        // Checks the request if it is a POST action
        if($request->isPost()) {
            $loginForm->populate($request->getPost());
            // This is where I don't know how validate the posted form
            if($loginForm->isValid($_POST)) {
                // codes here
            }
        }
    }
}
4

2 に答える 2

0

あなたはかなり近いです。プロセスアクションでは、ログインフォームの新しいインスタンス(実行中)を作成し、isValid()検証するためにそのフォームのメソッドにPOSTデータを渡します。それで:

public function processAction()
{
    $request = $this->getRequest();

    $loginForm = new Application_Form_Login();
    if($request->isPost()) {
        if($loginForm->isValid($request->getPost)) {
            // codes here
        } else {
            // assign the login form back to the view so errors can be displayed
            $this->view->loginForm = $loginForm;
        }
    }
}

通常、同じアクション内でフォームを表示および処理し、送信が成功したときにリダイレクトする方が簡単です。これはPost/Redirect/Getパターンです-http://en.wikipedia.org/wiki/Post/Redirect/Getを参照してください。これにより、2つの異なるアクションで同じフォームのインスタンスを作成する必要がなくなり、エラーが発生した場合にフォームを再表示しやすくなります。

于 2012-11-28T10:28:13.043 に答える
0

使っていますか ' ?

$loginForm->setAction(/Auth/process);に変更 $loginForm->setAction('/auth/process');

processActionから削除できます$login->populate($request->getPost());

于 2012-11-28T10:28:29.907 に答える