user4869699
user4869699

Reputation:

Insert Automatically datetime in yii

I am new in Yii Framework.I want to insert date in database when new record entered.here is my model rules

public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('user_id, question, creation_Datetime, creator_id', 'required'),
            array('user_id, creator_id', 'numerical', 'integerOnly'=>true),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, user_id, question, creation_Datetime, creator_id', 'safe', 'on'=>'search'),
        );
    }

Please Help

Upvotes: 0

Views: 1333

Answers (3)

Manoj Dhiman
Manoj Dhiman

Reputation: 5166

you can use refrence

public function beforeSave() {
    if ($this->isNewRecord)
        $this->created = new CDbExpression('NOW()');
    else
        $this->modified = new CDbExpression('NOW()');

    return parent::beforeSave();
}

or

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    return array(
        array('title','length','max'=>255),
        array('title, created, modified', 'required'),
        array('modified','default',
              'value'=>new CDbExpression('NOW()'),
              'setOnEmpty'=>false,'on'=>'update'),
        array('created,modified','default',
              'value'=>new CDbExpression('NOW()'),
              'setOnEmpty'=>false,'on'=>'insert')
    );
}

Upvotes: 1

gvgvgvijayan
gvgvgvijayan

Reputation: 2506

In Question comments @chris pointed it to Yii 2 but by seeing the array format it clear that you're using either Yii 1.0 or Yii 1.1

So here I write two solutions.

Yii 1.1

public function behaviors(){
   return array(
      'CTimestampbehavior' => array(
         'class' => 'zii.behaviors.CTimestampbehavior',
         'createAttribute' => 'creation_Datetime',
      )
   );
}

Yii 1.0

Since yii 1.0 don't have CTimestampbehavior class. You can use this way in your model:

public function beforeSave() {
  if($this->isNewRecord) {
    $this->creation_Datetime = new CDbExpression('NOW()');
  }
}

Upvotes: 1

Gintoki
Gintoki

Reputation: 142

In MySQL you can use now(), to enter the current date.

Upvotes: -1

Related Questions