在我的应用程序中,我有一个带有用户名(电子邮件)和密码的用户表,没有关于用户名的验证规则,但当我尝试创建用户名表中已存在的用户名时,它会自动将我从应用程序中注销而不会出现任何错误。 用户控制器:
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController {
public $components = array('Recaptcha.Recaptcha');
public $helpers = array('Recaptcha.Recaptcha');
var $uses = array('User', 'Student');
function isAuthorized() {
$userType = $this->Auth->user('type'); ///loggen-in $userType=1
switch ($userType) {
case 1:
if (in_array($this->action, array('admin_add'))) {
return true;
} else {
return false;
}
case 2:
if (in_array($this->action, array('admin_dashboard'))) {
return true;
} else {
return false;
}
}
}
public function admin_add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'), 'success');
$this->redirect(array('controller' => 'users', 'action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'error');
}
}
$this->layout = 'admin_default';
}
}
用户模型:
App::uses('AppModel', 'Model');
class User extends AppModel {
public $validate = array(
'password' => array(
'min' => array(
'rule' => array('minLength', 3),
'message' => 'Password must be at least 3 characters.'
),
'required' => array(
'rule' => 'notEmpty',
'message' => 'Please enter a password.'
),
),
'cpassword' => array(
'required' => 'notEmpty',
'match' => array(
'rule' => 'validatePasswdConfirm',
'message' => 'Passwords do not match'
)
)
);
function validatePasswdConfirm($data) {
if ($this->data['User']['password'] !== $this->data['User']['cpassword']) {
return false;
}
return true;
}
}
用户视图:
<?php
echo $this->Form->create('User', array('action' => 'admin_add',
'id' => 'form-register',
'class' => 'form-horizontal form-bordered'
));
echo $this->Form->input('username', array(
'id' => 'user-name',
'class' => 'form-control input-lg',
'placeholder' => 'Email',
'label' => false
));
echo $this->Form->input('password', array(
'id' => 'user-password',
'class' => 'form-control input-lg',
'placeholder' => 'Password',
'label' => false
));
echo $this->Form->input('cpassword', array(
'id' => 'user-cpassword',
'class' => 'form-control input-lg',
'placeholder' => 'confirm Password',
'label' => false,
'type' => 'password'
));
echo $this->Form->end();
?>
问题是什么?我该如何解决这个问题?
答案 0 :(得分:0)
我建议另外一种方法,在你的模型上添加这个功能:
function UsernameExists($username){
$count = $this->Event->find("count", array("conditions" => array("username" => $username)));
if ($count == 0) {
return false;
} else {
return true;
}
}
并在您的控制器中保存功能:
public function save($post){
if($this->User->UsernameExists($username)){
//show an error message that you cannot add because the username exists
} else {
$this->User->save($data);
}
}