防止使用 PRG 提交多个表单



我需要删除"确认重新提交"对话框以防止多个表单提交,并且还需要在用户刷新页面时清除ZF2自动呈现的表单验证错误。

我已经阅读了 ZF2 关于 PRG 插件的文档,但是当我仍然想显示表单错误时,我不确定如何实现它。

这是我当前的代码:

public function loginAction()
{
    $sm                 = $this->getServiceLocator();
    $forms              = $this->getForms();
    $viewModel          = new ViewModel();
    $viewModel->setTemplate('customer/customer/view-login-reg-form.phtml');
    $this->layout()->setVariable('title', 'Welcome!');
    $viewModel->setVariables($forms);
    $request            = $this->getRequest();
    if($request->isPost()) {
        $postData       = $request->getPost();
        $forms['formLogin']->setData($postData);
        $forms['formLogin']->setInputFilter($sm->get('CustomerFormFilterLoginFilter')->getInputFilter());
        if ($forms['formLogin']->isValid()) {
            $data       = $forms['formLogin']->getData();
            $customer   = $this->getCustomerTable()->getCustomer($data['login-email'], $data['login-password']);
            if (empty($customer)) {
                $viewModel->setVariable('errorMessage', 'Account does not exist');
                return $viewModel;
            }
            $LoginService = $sm->get('CustomerServiceLoginService');
            $LoginService->initLogin($customer);
            $this->handleRedirect();
        }
    }
    return $viewModel;
}

你可以这样写你的方法:

public function loginAction()
{
    $prg = $this->prg();
    if ($prg instanceof Response) {
        return $prg;
    }
    // here, $prg is false if multiple submissions 
    if ($prg === false) {
        // your code for init $prg or redirect to other action
    }
    // here, $prg contains post and get parameters as an array
    // You must distinguish whether this is an entry to display the form 
    // or the return to process the data returned by the submit
    // because $request is no longer available. Example :
    $forms              = $this->getForms();
    if (array_key_exists('submit', $prg) {
        $forms['formLogin']->setData($prg);
        $forms['formLogin']->setInputFilter($sm->get('CustomerFormFilterLoginFilter')->getInputFilter());
        if ($forms['formLogin']->isValid()) {
            $data       = $forms['formLogin']->getData();
            $customer   = $this->getCustomerTable()->getCustomer($data['login-email'], $data['login-password']);
            if (empty($customer)) {
                $viewModel->setVariable('errorMessage', 'Account does not exist');
                return $viewModel;
            }
            $LoginService = $sm->get('CustomerServiceLoginService');
            $LoginService->initLogin($customer);
            $this->handleRedirect();
        }
    }
    $viewModel          = new ViewModel();
    $viewModel->setTemplate('customer/customer/view-login-reg-form.phtml');
    $this->layout()->setVariable('title', 'Welcome!');
    $viewModel->setVariables($forms);
    return $viewModel;
}

最新更新