set model attribute before execute any actions in model

I want a model attribute to be changed before any validation or whatever by the model, not by the controller

let me explain my self better


class Domains extends Model{

	public $domainExtension;//this will generate the .com or .net or something in the model

	public function getDomainExtensions(){

    	return array(

        	'.com'=>'.com',

        	'.net'=>'.net',

 			//...

 		);

	}

}

in the database there’s a field called ‘domain’ that is domain+domainExtension before validate, save or other functions

something like




$this->domain='http://www.'.$this->domain.$this->domainExtension;



how is a good way to do it ? init method ? some kind of validation ?

I didn’t get the problem, anyway I can advice you to use or beforeValidate or beforeSave:




public function beforeSave()

{

  //set your value here

  return parent::beforeSave();

}



don’t forget to call return parent::beforeSave(); or the model will not be saved.

Yea, i thought of that but this way i wont be able to use CUrlValidator, what im doing right now is something like:




function rules(){

  	return array(

        	//other rules

      	array('domain','validateDomain'),

 	);

  }


	function validateDomain(){

    	$valid=new CUrlValidator;

    	$this->domain="http://www.".$this->domain.$this->domainExtension;

    	if(!$valid->validateValue($this->domain)){

        	$this->addError('domain',$this->domain);

    	}

	}



but i dont like this solution to be used everytime i do something like this, since i cant guarantee it will be always validated

This is exactly as I would do. Changing data in beforeValidate is not fair, because in case of error the user will be propted with data different from what he typed, and that is bad.

You can do validation like that and change the value in the beforeSave.

Thanks zaccaria

changed the function to




  function rules(){

      return array(

          //other rules

          array('domain','validateDomain'),

      );

  }


function validateDomain(){

    	$valid=new CUrlValidator;

    	if(!$valid->validateValue("http://www.".$this->domain.$this->domainExtension)){

        	$this->addError('domain',$this->domain);

 	}

}



and changed beforeSave to this:




function beforeSave(){

    	$this->domain=$this->domain.$this->domainExtension;

    	if($this->isNewRecord){

        	$this->user_id=user_id();

        	$this->status=self::DOMAIN_WAITING;

        	$this->expires=0;

    	}

    	return parent::beforeSave();

}