Using mapped variable inside CActiveRecord?

Here’s what happens in the code.

Controller finds the required object using findByPk($id).

I simply require this object to call init() and set some default values, so that I can use them inside my view.

The problem is, init() does get called, but the values aren’t being set.

Inside this model’s table, I have column named ‘birthdate’. Contains the birthdate as type ‘date’ (yyyy-mm-dd).

In my view, I intend to show this birthdate in words. So inside init(), I want to separate the year, month and day and store them as separate attributes (so that I can use them around anywhere later).

Here’s how the init() looks then,

public function init()




		$this->year = substr($this->birthdate, 0, 4);

		$this->month = substr($this->birthdate, 5, 2);

		$this->date = substr($this->birthdate, 8, 2);



But this doesn’t happen as intended. The condition !is_null($this->birthdate returns false. So even if I do have a value like ‘2005-05-04’ in the birthdate column of my database, $this->birthdate returns null when I use it inside CActiveRecord.

What could be the reason for this?

When findByPk is used, init() is indeed invoked. So why do I get all empty/null values inside my mapped variables? Is init() being invoked before any values are loaded into the mapped variables?

better to use function afterFind() (you may need define additional vars : year,month ,day ); or define a method let’t say:

public function resolveBirthDay(){ 

 // return an array:  array('year'=>substr($this->birthdate, 0, 4),'month'...)



The reason this doesn’t work is because you’re putting it in the wrong function. Init() is similar to the regular __construct(), and it gets called before it gets any data from the database.

What you want to do is use afterFind(), as yiqing95 suggested.