gpt4 book ai didi

php - 我如何使用 CakePHP 的模型验证消息而不是 Controller 的 setFlash 消息?

转载 作者:可可西里 更新时间:2023-11-01 00:51:57 25 4
gpt4 key购买 nike

描述

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

如果数据是电子邮件地址,它会起作用 - 但如果它不是有效的电子邮件地址,它会提交表单,重新加载页面(或其他任何内容),然后出现闪存消息而不是我的模型更具体的“not a有效的电子邮件”错误。

问题:

那么,我该如何使用模型的验证消息而不是 Controller 的通用验证消息呢?

形式:

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');

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

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.'
)
),
);
}

最佳答案

戴夫

CakePHP 会为您做这件事,您已经正确设置了验证,如果保存失败,则错误是 REDIRECT。这会丢失发布数据,从而丢失验证消息

简单

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

关于php - 我如何使用 CakePHP 的模型验证消息而不是 Controller 的 setFlash 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5411255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com