I understand that I can set initial (default) values in a CActiveRecord like this:
class SimpleObject extends CActiveRecord
{
public $direction = 'left';
...
So, assigning values to properties which are named like one of the attributes sets the default value for this attribute. Fine.
However, this does not work if I need dynamically calculated values, for example the following does not work:
class SimpleObject extends CActiveRecord
{
public $user = Yii::app()->getUser()->getName();
...
It results in a syntax error. Now how should one set such a default value?
The init() method
First possibility: init() method. The CActiveRecord provides an (empty) init() method which can be overridden just for the purpose of populating your model with default values. This works:
class SimpleObject extends CActiveRecord
{
public function init()
{
$this->user = Yii::app()->getUser()->getName();
}
...
Is this "the real way"? I am asking because I discovered 2 other promising facts:
The CDefaultValueValidator
the documentation says:
Isn’t this exactly what I want? However, I could not make it work. I tried this:
class SimpleObject extends CActiveRecord
{
public function rules()
{
return array(
array('user', 'default', 'value'=>Yii::app()->getUser()->getName()),
);
}
...
But the input form (_form.php) in the “create” scenario of CRUD doesn’t show the default value, it was empty. Have I done something wrong?
The property CActiveRecordMetaData->attributeDefaults
As far as I have understood, this meta data is just filled automatically by reading the database metadata and cannot be modified manually in a useful way. So this is not the right place for setting dynamic default values. Am I right?
To sum up, these are my questions:
[list=1]
[*]How to use the CDefaultValuesValidator properly and which purpose does it serve exactly?
[*]Am I right that CActiveRecordMetaData->attributeDefaults is of no interest with respect to setting dynamic default values?
[/list]