我正在創建一個表單,以便用戶可以更改其密碼。此表單位於我的設置控制器中,但我將數據保存到我的用戶表中。使用CakePHP觸發模型驗證
我有以下形式
settings/index.ctp
echo $this->Form->create('settings');
echo $this->Form->input('current_password');
echo $this->Form->input('password');
echo $this->Form->input('repass', array('type'=>'password', 'label'=>'Re-Enter Password'));
echo $this->Form->end(__('Submit'));
這裏是我的設置模式
function equalToField($array, $field) {
print_r($array); //check to see if it was even being triggered...it's not!
return strcmp($this->data[$this->alias][key($array)], $this->data[$this->alias][$field]) == 0;
}
public function beforeSave() {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
public $validate = array(
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'message' => 'A password with a minimum length of 8 characters is required'
)
),
'repass' => array(
'required' => array(
'rule' => array('equalToField', 'password'),
'message' => 'Passwords do not match'
)
)
);
而在我SettingsController的代碼,將其保存
$password = Security::hash($this->request->data['settings']['current_password'], NULL, true);
$this->loadmodel('User');
$options = array('conditions' => array('User.' . $this->User->primaryKey => AuthComponent::user('id')));
$user = $this->User->find('first', $options);
if($user['User']['password'] == $password){ //current password match
$this->User->id = AuthComponent::user('id');
$this->User->saveField('password',Security::hash($this->request->data['settings']['password'], NULL, true));
}
else{
$this->Session->setFlash('Current password is incorrect');
}
我在做什麼錯誤的驗證不會觸發?如果可能的話,我寧願保留在我的SettingsController中。此外,在任何人提到它之前,我計劃將當前的密碼匹配成驗證標準之一......只要我能夠正常工作。
更新 - 我決定做一些挖掘周圍
在/lib/Model/Model.php我去驗證功能和打印的驗證對象,這裏是我的發現
([validate] => Array (
[password] => Array (
[required] => Array (
[rule] => Array (
[0] => minLength
[1] => 8)
[message] => A password with a minimum length of 8 characters is required))
[repass] => Array (
[required] => Array (
[rule] => Array (
[0] => equalToField
[1] => password)
[message] => Passwords do not match
)))
[useTable] => settings
[id] =>
[data] => Array (
[Setting] => Array (
[settings] => Array (
[current_password] => current_pass
[password] => testpass1
[repass] => testpass2
)))
我不知道這是我想要的,但它使用設置表爲此,我正在保存到用戶表。我將這個值更改爲用戶(通過手動設置該函數中的值),但它沒有改變任何東西。
當我使用下面的建議,它拉從沒有的usermodel設置
$this->User->set($this->request->data);
if($this->User->Validates() == true){
這也可能有所幫助:http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/ – mark
不知道爲什麼我沒有發現,現在我'米糊塗,你在那裏做什麼?你爲什麼使用'User'模型來保存屬於'Setting'模型的東西? – ndm
@ndm它被保存在users表中,而不是設置表中。我正在從SettingsController /模型 – user1443519