Home  >  Article  >  Backend Development  >  Yii implements two methods to add default values ​​to the model

Yii implements two methods to add default values ​​to the model

不言
不言Original
2018-05-03 16:01:051367browse

This article mainly introduces the method of adding default values ​​​​in Yii's implementation model. It analyzes two implementation techniques in the rules() method and the beforeSave() method based on examples. Friends in need can refer to it

The example of this article describes the method of adding default value to model in yii. Share it with everyone for your reference, the details are as follows:

yii model inherits from CActiveRecord

Some fields may not appear in the form, but need to be added in the program Add . Such as order number, timestamp, user_id of operation, etc.

The following two methods:

1. Set in the rules() method:

public function rules()
{
  // NOTE: you should only define rules for those attributes that
  // will receive user inputs.
  return array(
    array('start, end', 'required'),
    array('user_id', 'numerical', 'integerOnly'=>true),
    array('timestamp','default','value'=>date('Y-m-d H:i:s')),
    // The following rule is used by search().
    // Please remove those attributes that should not be searched.
    array('id, start, end, user_id, timestamp', 'safe', 'on'=>'search'),
  );
}

2. Set in the beforeSave() method:

function beforeSave()
{
  $this->user_id = Yii::app()->user->id;
  return true;
}

It should be noted that beforeSave() The method needs to return true, otherwise will not be saved.

Related recommendations:

Detailed explanation of properties in Yii

Related introduction to using memcache in YII

The above is the detailed content of Yii implements two methods to add default values ​​to the model. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn