adinugro
(Adinugro)
November 9, 2009, 3:45am
1
Hi,
I was wondering how could we add a default values for a Model. For example, my model has a transaction date which is by default is today. At the moment, I can add this in the view like this:
<?php echo CHtml::activeTextField($form,‘transDate’,array(‘value’=>date(“d-m-Y”),‘class’=>‘transDateStyle’)); ?>
It works, but I prefer the today’s date is supplied from the Model/Controller. In Java, we can have a default constructor for the model and assign the default value there. Can we do the similar way in Yii/PHP?
Many thanks,
Daniel.
jayrulez
(Waprave)
November 9, 2009, 4:05am
2
Hi,
I was wondering how could we add a default values for a Model. For example, my model has a transaction date which is by default is today. At the moment, I can add this in the view like this:
<?php echo CHtml::activeTextField($form,‘transDate’,array(‘value’=>date(“d-m-Y”),‘class’=>‘transDateStyle’)); ?>
It works, but I prefer the today’s date is supplied from the Model/Controller. In Java, we can have a default constructor for the model and assign the default value there. Can we do the similar way in Yii/PHP?
Many thanks,
Daniel.
you can use a behaviour in your model like
public function behaviors()
{
return array(
'CTimestampBehavior' => array(
'class' => 'zii.behaviors.CTimestampBehavior',
'createAttribute' => 'field_from_table',//by default field is create_time
)
);
}
if you are using 1.1,
or you can do it in beforeValidate/afterValidate/beforeSave methods in your model class. eg:
public function beforeValidate()
{
if($this->isNewRecord)
{
$this->field_from_table = ("d-m-Y");
}
return parent::beforeValidate();
}
adinugro
(Adinugro)
November 9, 2009, 5:54am
3
jayrulez:
you can use a behaviour in your model like
public function behaviors()
{
return array(
'CTimestampBehavior' => array(
'class' => 'zii.behaviors.CTimestampBehavior',
'createAttribute' => 'field_from_table',//by default field is create_time
)
);
}
if you are using 1.1,
or you can do it in beforeValidate/afterValidate/beforeSave methods in your model class. eg:
public function beforeValidate()
{
if($this->isNewRecord)
{
$this->field_from_table = ("d-m-Y");
}
return parent::beforeValidate();
}
Hi, jayrulez
Thank you for your prompt help. I am using Yii 1.08. I could not use beforeValidate/afterValidate/beforeSave since I need the value from the beginning when the form is displayed for the first time.
Thanks,
Daniel
marlinf
(Marlinf)
November 9, 2009, 7:32am
4
In the constructor or the init() method would be a good place.
function init()
{
if($this->isNewRecord) {
// set defaults
}
}
adinugro
(Adinugro)
November 9, 2009, 7:41am
5
Thanks. one more question, where should I put the init() function, model or controller?
Regards,
Daniel
rickgrana
(Ricardo Grana)
November 10, 2009, 5:04pm
7
You can use afterConstruct method, too.