Variable Is Null In Rules()

I have a strange problem. A variable declared in my model is always NULL, when I try to access it in the function Rules(). Elsewhere it has the correct value.

I defined a variable in my model like this




class User extends CActiveRecord

{

    public $password2;



Then in the controller I fill the model:




$model->attributes=$_POST['User'];

$model->password2=$_POST['User']['password2'];



I have defined a validation-rule with a function to check i the entered password matches the one in the database.




public function rules() {

    return array(

        array('password2', 'comparePassword', 'password' => $this->password2, 'hash' => $this->password, 'on' => 'updatePassword'),

...

 

public function comparePassword($attribute, $params) {

    if (!CPasswordHelper::verifyPassword($params['password'], $params['hash'])) {

        $this->addError($attribute, 'Incorrect password');

    }

}



But $params[‘password’] is always NULL. So I tried




public function rules() {

    var_dump($this->password2);



the result was NULL.

Is this a bug of Yii or is it not possible to access variables of the model in the Rules()-function? Or did I a programing mistake?

you cannot use attributes in rules() function. Rules must not depend on any attribute value. this is by design. rules() can be accessed by framework BEFORE any values are assigned and you can get errors like you described.