如何使用 CakePHP 的模型验证消息而不是控制器的 setFlash 消息?

发布于 2024-10-26 02:10:33 字数 1874 浏览 2 评论 0原文

描述

我网站的每个页面上都有一个简单的表单 - 一个输入和一个提交按钮。重点是用户输入他/她的电子邮件地址并点击提交。

如果数据是电子邮件地址,它就可以工作 - 但如果它不是有效的电子邮件地址,它会提交表单,页面重新加载(或其他),并且出现闪存消息,而不是我的模型更具体的“不是有效的电子邮件”错误。

问题

那么,如何使用模型的验证消息而不是控制器的通用消息?

表单:

echo $this->Form->create('Email', array('class'=>'form1', 'url'=>'/emails/add', 'inputDefaults'=>array('label'=>false))); 
echo $this->Form->input('Email.email');
echo $this->Form->end('SIGN-UP');

电子邮件控制器“添加”功能(或方法?):

function add() {
    if (!empty($this->data)) {
        $this->Email->create();
        if ($this->Email->save($this->data)) {
            $this->Session->setFlash(__('The email address has been saved', true));
            $this->redirect($this->referer());
        } else {
            $this->Session->setFlash(__('The email address could not be saved. Please, try again.', true));
            $this->set('error', 'custom error here');
            $this->redirect($this->referer());
        }
    }
}

以及电子邮件模型:

class Email extends AppModel {
var $name = 'Email';

var $validate = array(
    'email'     => array(
        'is_valid'  => array( //named whatever we want
            'rule'      => 'notEmpty',
                'rule'      => array('email', true),
                'message'   => 'Please supply a valid email address.',
                'last'      => true //causes it to not check the next rule if this one fails
        ),
        'is_unique'     => array( //named whatever we want
            'rule'          => 'isUnique',
            'message'       => 'That email address is already in our database.'
        )
    ),
);
}

Description

I have a simple form on every page of my site - a single input and a submit button. The point is just for the user to enter his/her email address and hit submit.

It works if the data is an email address - but if it's not a valid email address, it submits the form, the page reloads (or whatever), and the flash message comes up instead of my model's more specific "not a valid email" error.

Question:

So, how do I use the model's validation message instead of the controller's generic one?

The form:

echo $this->Form->create('Email', array('class'=>'form1', 'url'=>'/emails/add', 'inputDefaults'=>array('label'=>false))); 
echo $this->Form->input('Email.email');
echo $this->Form->end('SIGN-UP');

The email controller "add" function (or method?):

function add() {
    if (!empty($this->data)) {
        $this->Email->create();
        if ($this->Email->save($this->data)) {
            $this->Session->setFlash(__('The email address has been saved', true));
            $this->redirect($this->referer());
        } else {
            $this->Session->setFlash(__('The email address could not be saved. Please, try again.', true));
            $this->set('error', 'custom error here');
            $this->redirect($this->referer());
        }
    }
}

And the email model:

class Email extends AppModel {
var $name = 'Email';

var $validate = array(
    'email'     => array(
        'is_valid'  => array( //named whatever we want
            'rule'      => 'notEmpty',
                'rule'      => array('email', true),
                'message'   => 'Please supply a valid email address.',
                'last'      => true //causes it to not check the next rule if this one fails
        ),
        'is_unique'     => array( //named whatever we want
            'rule'          => 'isUnique',
            'message'       => 'That email address is already in our database.'
        )
    ),
);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷荒 2024-11-02 02:10:33

Dave

CakePHP 会为您完成此操作,您已正确设置验证,如果保存失败,则错误是重定向。这会丢失发布数据,从而丢失验证

消息

if ($this->Email->save($this->data)) {
  $this->Session->setFlash(__('The email address has been saved', true));
  $this->redirect($this->referer());
} else {
   $this->Session->setFlash(__('There were problems saving, please see the messages below.', true));                    
}

Dave

CakePHP does this for you, you have set the validation correctly, the error is the REDIRECT if your save fails. This loses the post data and hence the validation messages

Simply

if ($this->Email->save($this->data)) {
  $this->Session->setFlash(__('The email address has been saved', true));
  $this->redirect($this->referer());
} else {
   $this->Session->setFlash(__('There were problems saving, please see the messages below.', true));                    
}
迷爱 2024-11-02 02:10:33

通常,您会使用 $form 帮助程序的错误选项。请参阅手册中有关此内容的部分

但是,如果您想使用验证消息填充 flash 消息,则可以使用模型方法 invalidFields()。这是一个示例:

if (!$this->User->save($this->data)) {
    $validationErrors = $this->User->invalidFields();
    $this->Session->setFlash($validationErrors['email']); // named key of the rule
    $this->redirect('/somewhere');
}

它的作用是获取模型中写入失败的验证规则的消息。虽然 invalidFields() 返回一个数组,但您可以操作其中的值以生成更好的错误消息,例如连接不同的错误消息。

顺便说一句,我注意到上面的代码中有一些不好的地方。您将模型类命名为“Email”,并且有一个核心 CakePHP 类已命名为 Email(这是著名的 Email 组件),因此我建议您以不同的方式命名整个 MVC。

Normally, you would use the $form helper's error options. See the section of the manual on this.

However, if you want to populate the flash message with the validation message, you can use the model method invalidFields(). Here is an example:

if (!$this->User->save($this->data)) {
    $validationErrors = $this->User->invalidFields();
    $this->Session->setFlash($validationErrors['email']); // named key of the rule
    $this->redirect('/somewhere');
}

What this does is to get the messages written in model for the validation rules that failed. While invalidFields() returns an array, you can manipulate the values within it to produce a better error message, like for example, concatenating the different error messages.

Btw, I noticed something bad in your code above. You are naming your model class as 'Email' and there is a core CakePHP class already named Email (which is the famous Email component), so I suggest you name the whole MVC for that differently.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文