2011-11-01 42 views
0

我試圖通過用戶激活頁面CakePHP 2更改註冊用戶的狀態。激活頁面包含一個散列字符串,它位於該用戶表:加載模型記錄,編輯並從控制器保存

id username email   password     active key 
1  bill  [email protected] 4u2iu4hk24(hashed str) 0   2ol3p(hashed str) 

激活過程適用於像這樣的網址:

http://url.com/users/activate/2ol3pth3i89txc2zd6tg3 

所有我做的是讓散列鍵,搜索與此key註冊用戶,加載它,刪除散列鍵,並將active狀態更改爲1。 我做這個Controller方法步驟:

public function activate ($code = false) { 
    if (!empty ($code)) { 
     $this->User->findByActivationKey($code); // magic find instead of $this->User->find('contidions', array('User.activation_key' => $code)); 
     if (!empty($user)) { 
      $this->User->set(array (
       'activation_key' => '0', 
       'active' => 1 
      )); 
      if ($this->User->save()) { 
       $this->render('activation_successful'); 
      } else { 
       // here is always where I get with this code 
       $this->render('activation_fail'); 
      } 
     } else { 
      $this->render('activation_fail'); 
     } 
    } 
} 

諸事罰款,但$this->User->save()將無法​​正常工作。

使用debug($this->User->invalidFields());將返回該錯誤:

app/Controller/UsersController.php (line 64) 
Array 
(
[password] => Array 
    (
     [0] => Password must contain <span5</span> chars min and <span>20</span> chars max message. 
     [1] => Password must contain <span5</span> chars min and <span>20</span> chars max message. 
    ) 

) 

顯然,誤差是模型,但爲什麼提到password

<?php 
App::uses('AuthComponent', 'Controller/Component'); 
class User extends AppModel { 
    public $name = 'User'; 
    var $validate = array (
     'username' => array (
      'MustBeCompiled' => array (
       'rule' => 'notEmpty', 
       'message' => 'Error message' 
      ) 
     ), 
     'password' => array (
      'not_empty' => array (
       'rule' => 'notEmpty', 
       'message' => 'Password cannot be empty message.' 
      ), 
      'between' => array (
       'rule' => array ('between', 5, 20), 
       'message' => 'Password must contain <span5</span> chars min and <span>20</span> chars max message.' 
      ) 
     ), 
     'email' => array (
      'valid_email' => array (
       'rule' => 'email', 
       'message' => 'Mail invalid message.' 
      ), 
      'existing_email' => array (
       'rule' => 'isUnique', 
       'message' => 'Mail in use message.' 
      ) 
     ) 
    ); 

    function beforeSave ($options = array()) { 
     // the way to hash the password 
     if (!empty ($this->data[$this->alias]['password'])) { 
      $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']); 
      return true; 
     } 
    } 
} 
?> 

也許問題可能是beforeSave()? 我哪裏錯了?

回答

0

你沒有將ID傳遞給模型,我想你有驗證規則,所以它不會保存記錄。在save()之後調試($ this-> User-> invalidFields())。

所有這些都應該在模型中完成,例如User :: verify($ code),如果找不到用戶/標記則會拋出異常。記住:微小的控制器,胖的模型。模型也更容易測試。

+0

謝謝,我會盡快檢查! – vitto

+0

如果你向我展示一個實用的例子或者其他的東西,那麼這將是非常寶貴的,因爲我不熟悉MVC,所以我不確定如何在控制器中實現'User :: verity($ code)'。 – vitto

+0

'debug($ this-> User-> invalidFields())'返回一個空數組,我只是從'$ this-> User-> save()'方法中獲得'false'。 – vitto