Default values for Model

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();

}

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

In the constructor or the init() method would be a good place.




function init()

{

  if($this->isNewRecord) {

    // set defaults

  }

}



Thanks. one more question, where should I put the init() function, model or controller?

Regards,

Daniel

Model.

You can use afterConstruct method, too.