afterFind, findAll and scenarios

I have an afterFind() function in my model, I only wanted it to be run when updating the record so I did this:


public function afterFind()

{

	if($this->scenario=='update')

	{

		// my code

	}

}

However it seems that the code is also being run on a normal findAll query. I echoed out $model->scenario in my view and it is outputting ‘update’ - I definitely have not set this in my controller, so it seems like it is just defaulting to ‘update’.

Is this the intended behaviour, or have I overlooked something?

There are two default scenarios: "update" and "insert". The latter is automatically set when you create a new model. "update" scenario is set for models retrieved from a database. It frees you from defining these scenarios manually every time you create a model or retrieve models from a database.

Now you see that the scenario will always be "update" in afterFind() method. Also I doubt you need this method, because it is automatically called when a record is retrieved from a database, before you can set any scenario. What kind of task do you want to solve?

I see. Thanks for clarifying this. Basically I am using afterFind to populate a set of checkboxes whose values are retrieved from a relational table:


foreach($this->rel_genres as $genre) // $this->rel_genres is the relation

{

	$genres[]=$genre->value;

}

			

if(!empty($genres))

{

	$this->genres=$genres; // $this->genres is the checkboxlist attribute

}

I could probably do this in the controller but I thought it would be more convenient to do it in the model. Any thoughts on this?

BUMP

I’m having the similar problem - I need to populate relational fields only for create and update scenarios, that way lazy loading of relational records occurs for every action and it is unwanted…

Is possible to set default scenario to other than "update"?

I found a way!

in model:




public $notUseAfrefind=false;

..

public function afterFind()

	{

		if (!$this->notUseAfrefind){	

			//code

		}

		parent::afterFind();

	}




in lazzyload:




$items=ModelClass::model()->with('relation')->findAll(Array( 'select'=>'*, t.id as notUseAfrefind'));



In controller


AuthHistory::model()->scenario='admin_list'; 

AuthHistory::model()->findAll(); 

in afterFind(), you can check


self::model()->scenario

(instead of $this->scenario)