我的“用户”型号代码
class User extends AppModel{
public $validate = array(
'username' => array(
'username_shoud_be_unique' => array(
'rule' => 'isUnique',
'message' => 'Username is already taken'
),
'username_cannot_be_empty' => array(
'rule' => 'notEmpty',
'message' => 'Usename field cannot be Empty'
)
),
'password' => array(
'rule' => 'notEmpty',
'message' => 'Password field cannot be Empty'
),
'confirm_password' => array(
'confirm_password_cannot_be_empty' => array(
'rule' => 'notEmpty',
'message' => 'Confirm Password Field cannot be Empty'
),
'confirm_password_must_match_password' => array(
'rule' => array('checkPassword'),
'message' => 'Password and Confirm Password Field value should match'
)
),
'email' => array(
'email_should_be_unique' => array(
'rule' => 'isUnique',
'message' => 'This email is already registered'
),
'email_cannot_be_empty' => array(
'rule' => 'notEmpty',
'message' => 'Email cannot be Empty'
)
)
);
public function checkPassword(){
if(!($this->data['User']['password'] === $this->data['User']['confirm_password'])){
$this->invalidate('password','Password and Confirm Password Field value should match');
return false;
}
return true;
}
}
我的“UsersController.php”是
class UsersController extends AppController{
public $helper = array('Html','Form','Session');
public $components = array('Session');
public function index(){
if($this->request->is('post')){
$this->User->create();
$this->request->data['User']['ip'] = $this->request->clientIp();
$this->request->data['User']['username_clean'] = strtolower($this->request->data['User']['username']);
$this->request->data['User']['confirmcode'] = md5(md5($this->generateRandomString())."com.ultimate-videochat");
if($this->User->save($this->request->data)){
$this->Session->setFlash(__('User created Successfully'));
} else{
$this->Session->setFlash(__('Unable to create User'));
}
}
}
//This function is only for internal use. It's not an action.
private function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
}
我的index.ctp是http://pastebin.com/DiFHLNV8
问题在于,当用户因数据验证失败而无法保存时,例如当用户输入已存在的用户名时,会抛出一条消息“无法创建用户”。如果由于“连接失败”或其他一些技术原因等其他原因无法创建用户,我该如何获取该消息。对于验证失败,字段上的红色标记就足够了。
答案 0 :(得分:1)
您的布局中必须有一个声明echo $this->Session->flash();
才能显示Flash消息。所以删除它或包装在如下的条件下:
if (empty($this->validationErrors)) {
echo $this->Session->flash();
}
以便在验证错误时不显示flash消息。
答案 1 :(得分:0)
您可以简单地阻止控制器本身的闪光信息设置。
虽然我不相信这是好事。显示Flash消息以及表单错误有什么问题?那更有用:)!
无论如何,如果您仍然认为您想在验证错误案例中隐藏它,请转到:
if($this->User->save($this->request->data)) {
$this->Session->setFlash(__('User created Successfully'));
} else {
if (empty($this->User->validationErrors)) {
$this->Session->setFlash(__('Unable to create User'));
}
}