将带有post方法的表单传递给另一个控制器

时间:2012-11-28 10:12:22

标签: zend-framework zend-form posts

我有一个简单的Zend表单,其中包含带有setRequired(TRUE)的文本框和其他验证器以及IndexController中的简单提交按钮。

我的问题是,是否有可能另一个控制器会处理并验证我的帖子?

的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
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

你非常接近。在流程操作中,您将创建登录表单的新实例(您正在执行此操作),并将POST数据传递给该表单的isValid()方法以进行验证。所以:

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;
        }
    }
}

通常,在同一操作中显示和处理表单更容易,并在提交成功时重定向。这是发布/重定向/获取模式 - 请参阅http://en.wikipedia.org/wiki/Post/Redirect/Get。这样您就不必在两个不同的操作中创建相同表单的实例,并且在出错时更容易重新显示表单。

答案 1 :(得分:0)

你在用'?

$loginForm->setAction(/Auth/process);更改为$loginForm->setAction('/auth/process');

来自processAction的

您可以删除$login->populate($request->getPost());