【发布时间】:2014-01-18 22:01:01
【问题描述】:
如何在我的 CakePHP 应用程序中保存用户而不要求他们每次都更改密码?
我有代码可以检查两个密码字段并应用一些验证规则,这对于注册和在“编辑”视图中更改密码非常有用。但是,如果编辑视图中的密码字段为空,我如何跳过验证规则并保存密码?显然,我不想跳过这个注册要求。
register.ctp 和 edit.ctp:
echo $form->create('User');
echo $form->input('username');
echo $form->input('pwd');
echo $form->input('pwd_repeat');
echo $form->end('Submit');
User.ctp 验证规则:
'pwd' => array(
'length' => array(
'rule' => array('between', 8, 40),
'message' => 'Your password must be between 8 and 40 characters.',
),
),
'pwd_repeat' => array(
'length' => array(
'rule' => array('between', 8, 40),
'message' => 'Your password must be between 8 and 40 characters.',
),
'compare' => array(
'rule' => array('validate_passwords'),
'message' => 'The passwords you entered do not match.',
),
),
以及保存前的User.ctp逻辑:
public function validate_passwords() { //password match check
return $this->data[$this->alias]['pwd'] === $this->data[$this->alias]['pwd_repeat'];
}
public function beforeSave($options = array()) { //set alias to real thing and hash password
$this->data['User']['password'] = $this->data[$this->alias]['pwd'];
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
【问题讨论】:
-
最好为表单中的密码字段使用不同的名称 - 请参阅 working-with-passwords-in-cakephp
-
不是吗?我以为我正在使用 pwd 和 pwd_repeat ......虽然回想起来我浪费时间将 pwd 转换为密码然后对其进行哈希处理,而我可以将 pwd 哈希为密码。
-
对。只是为了让它工作而错过了
!empty()部分。您应该始终提及您正在使用的确切 cakephp 版本。从代码来看,它看起来像 1.2。从 1.3 开始,它是 $this->Form.