Set model attributes with validation rules

Dear Experts,

I am building my Account model with testing framework.

However, I found that I cannot set attributes for the model if I do not specify my required field inside setAttributes method.

My test case looks like this




<?php 

class AccountTest extends CDbTestCase

{

	

    public $fixtures=array(

        'accounts'=>'Account',

    );

    

    protected $attr=array(

		'email'=>'cato.yeung@gmail.com',

		'password'=>'password',

		'password_confirmation'=>'password',

		'role'=>'admin',

	);

	

	public function testCreateNewInstanceGivenValidAttributes(){

		$valid_user = new Account;

		$valid_user->setAttributes($this->attr);

		$this->assertTrue($valid_user->save());

	}

}

?>



Here is my model:




<?php


/**

 * This is the model class for table "tbl_account".

 *

 * The followings are the available columns in table 'tbl_account':

 * @property integer $id

 * @property string $email

 * @property string $encrypted_password

 * @property string $salt

 * @property string $role

 * @property string $created_at

 * @property string $updated_at

 */

class Account extends CActiveRecord

{

	

	public $password;

	public $password_confirmation;

	/**

	 * Returns the static model of the specified AR class.

	 * @return Account the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'tbl_account';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('email', 'required'),

			array('email', 'length', 'max'=>50),

			array('email', 'email'),

			array('email', 'unique', 'caseSensitive'=>true),

			

			array('password', 'required'),

			array('password', 'length', 'min'=>6, 'max'=>50),

			

			array('password_confirmation', 'compare', 'compareAttribute'=>'password'),

			

			array('salt', 'required'),

			

			array('role', 'required'),

			array('role', 'length', 'max'=><img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />,

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, email, password, salt, role', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id' => 'ID',

			'email' => 'Email',

			'password' => 'Password',

			'salt' => 'Salt',

			'role' => 'Role',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('id',$this->id);

		$criteria->compare('email',$this->email,true);

		$criteria->compare('password',$this->password,true);

		$criteria->compare('salt',$this->salt,true);

		$criteria->compare('role',$this->role,true);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}

	

	public function beforeSave(){

		if ($this->isNewRecord){

			$this->role = 'admin';

			$this->encryptPassword($this->password);

	        $this->created_at = new CDbExpression('NOW()');

	        $this->updated_at = new CDbExpression('NOW()');

		}

	    else

	        $this->updated_at = new CDbExpression('NOW()');

	 

	    return parent::beforeSave();

	}

	

	public function validatePassword($submitted_password)

    {

    	return $this->encrypted_password === $this->encrypt($submitted_password);

        //return $this->hashPassword($password, $this->salt)===$this->password;

    }

 

    public function hashPassword($password,$salt)

    {

        //return md5($salt.$password);

    }

    

    // private functions

    

    private function encryptPassword($password){

    	$this->salt = 'salt';

    	$this->encrypted_password = $this->encrypt($password);

    }

    

    private function encrypt($password){

    	return $password;

    }

    

    /*

    private function encryptPassword($password){

    	$this->salt = $this->makeSalt($password);

    	$this->encrypted_password = $this->encrypt($password);

    }

    

    private function encrypt($string){

    	return $this->secureHash($this->salt . $string);

    }

    

    private function makeSalt($password){

    	return $this->secureHash(gmdate('M d Y H:i:s') . $password);

    }

    

    private function secureHash($string){

    	return hash('sha256', $string);

    }

    */

}



The test has failed. But I found that if I put salt in $attr, the test passes.

How can I specify salt only before saving the model?

Regards,

Cato

Remove validation rules for “salt” attribute. It’s a generated value that doesn’t need to be validated.

Alternatively you can generate salt and encrypted password in beforeValidate() method of your model instead of beforeSave().

Also, validation on save can be disabled for testing purposes:




$myModel->save(false);



Your request sound very close to this one to me and Antonio Ramirez has posted some nice snippet, maybe you should have a look at this.