How to add addition attribute to ActiveRecord?

I want to add additional attribute to ActiveRecord which is not present in database, but I want it only for validation.

Examples of use:

  • We have a form for adding user and there should be password2 which should be validated by rule: [tt]array('password2', 'compare', 'compareAttribute'=>'password')[/tt].
  • We want to add captcha to form which inserts a record to db.
  1. How should I modify the model?

  2. Should I use activeLabel and activePasswordField for "validating only" field like 'password2' ?

  3. When should perform e.g. md5 hashing? maybe onBeforeSave?

I found the way to do this but it doesn't seem to be very elegant…



class User extends CActiveRecord


{


	protected function afterConstruct()


	{


		$this->setAttribute('password2', '');


	}	


	


	public function hasAttribute($name)


	{


		if($name == 'password2') return true;


		return parent::hasAttribute($name);


	}


and in Controler:



		$user=new User;


		if(isset($_POST['User']))


		{


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


			$user->setAttribute('password2', $_POST['User']['password2']);


			


			if($user->save())


				$this->redirect(array('list','id'=>$user->id));


		}


Maybe there is simpler way to do this?

1). You can just declare a 'password2' property in the AR class and specify in the rules() to validate against this property.

2). Yes, you can do that.

3). beforeSave() is a good place to do password hashing.

Thank you. I was trying so but I was setting it by:



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


or


$user->setAttribute('password2',$_POST['User']['password2']);


So it wasn't working.

I just figured out that it must be set explicitly in such a way:



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


The first approach doesn't work because for safety concern, only attributes listed in safeAttributes() can be massively assigned. You may override this method to add 'password2' to make the first approach work.

I just checked in a fix that will make your second approach work. Thanks for finding this out.

I just ran into this as well, thank you for the fast fix.

<goes to look at minor release timeframe>