Active record attribute defaults

What is the best approach to assign default values to an active record?




protected function afterConstruct() {

    $this->someAttribute = 'default value';

    parrent::afterConstruct();

}



In some old code i found:




public function attributeDefaults() {

	return array(

		'someAttribute' => 'default value',

	);

}



Thanks.

If it’s a static default value:


public $myattribute='defaultvalue';



If it’s dynamic, use the afterConstruct() approach.

Okay, but will “public $myattribute=‘defaultvalue’;” be overwritten by the DB value of that field (which it should be)?

No, why you think it should be? This default value in the model has precedence over the db value (not 100% sure, give it a try, please). But if you prefer the DB default, simply don’t add a default attribute.

And you can always assign the value you need after you create the model…

For example in actionCreate()




$model=new YourModel;

$model->attribute1=value1;

$model->attribute2=value2;

...



Hmm…

To be more conrete;

I have a parentclass called “Category” which is extended by “ProductCategory” and “ForumCategory”. Every type of category has it’s own unique identifier, because they use the same DB table.

When i do:




$cat = new ForumCategory;

$cat->save();



I don’t want to explicitly “$cat->type = ‘forumCategory’”. Instead the ForumCategory class should take care of this.

Thanks for your help.

Uhm. So what’s wrong with:




ForumCategory extends Category

{

    public $type='forumCategory';

...

}


ProductCategory extends Category

{

    public $type='productCategory';

...

}



if you need the values only when you’re saving, set them inside beforeSave()

or else set them inside init()

Okay, thanks.

I’ll stick with Mike’s solution.