0

刚开始玩 CakePHP,所以如果这是一个简单的问题,请多多包涵。

我正在使用 CakePHP 2.4.0,我想在多个视图中重用一个特定的表单。因此,我将此表单添加到视图元素中,并在每个视图中包含此元素。

这是 element.ctp 文件:

<?php

echo $this->Form->create('Lead', array('type' => 'post',
                                       'url'  => array('controller' => 'Lead', 'action' => 'index'),
                                       'novalidate'   => true));

echo $this->Form->input('name', array('label' => 'Achternaam'));
echo $this->Form->input('email', array('label' => 'Email'));
echo $this->Form->input('phone', array('label' => 'Telefoon'));
echo $this->Form->submit('submit', array('name'  => 'submit'));    
?>

该元素通过以下方式包含在多个视图中:

这是 home.ctp(视图)文件:

<?php echo $this->element('element'); ?>

这是从表单接收 post 操作的 LeadController.php 文件:

<?php
class LeadController extends AppController{

    public function index(){
        $this->autoRender = false;
        if(!empty($_POST))
           $this->Lead->save($this->request->data);
        $this->redirect('/Pages/home');
    }
}
?>

这是包含所有验证检查的 Lead.php 文件。

class Lead extends AppModel{

public $useTable = 'Leads';

public $validate = array(
    'email' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'required' => true,
            'message' => 'need email'
        ),
        'validEmailRule' => array(
            'rule' => array('email'),
            'required' => true,
            'message' => 'invalid emial'
        )
    ),
    'name' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'required' => true,
            'message' => 'need name'
        )
    ),....

当视图元素中的表单完全有效时,表单中的数据将成功添加到数据库中。但是当表单无效时,错误不会返回到视图中。如果我在 LeadController 中将以下内容写入日志文件,则会显示它们。

$this->Lead->invalidFields();

如果我将 LeadController/index 中的代码添加到 PagesController/home 并更改表单提交 url,则错误会显示在每个表单元素的视图中。

当表单放置在单独的视图元素中并在多个页面中重用时,您需要做什么才能在每个表单元素的视图中显示表单的错误?

这可能与我使用重定向的事实有关,但我认为它们是比在会话中临时保存错误更好的方法。

4

1 回答 1

1

This has probably something to do with the fact that I use a redirect...

It's actually COMPLETELY to do with the fact that you use a redirect. By redirecting, you lose the validation errors.

There are as many ways to deal with this as your imagination can think of (and each has it's own merits depending on YOUR situation), but it is already widely asked/answered on the web:

CakePHP preserving validation errors after redirecting

http://bakery.cakephp.org/articles/binarycrafts/2010/01/20/persistentvalidation-keeping-your-validation-data-after-redirects-2

CakePHP: Keep validation data upon redirect

https://groups.google.com/forum/#!topic/cake-php/NsfckwSfY5c

于 2013-09-27T14:09:18.997 回答