Yiii method to add default values to yii model (2 methods)
This article mainly introduces the method of adding default values to Yii model. Combined with examples, it analyzes two implementation techniques in the rules() method and sets up two implementation techniques in the beforeSave() method, which may be helpful to everyone.
This article describes the method of adding default values to Yii's model. Share it for your reference, as follows:
yii model inherits from CActiveRecord
Some fields may not appear in the form and need to be added in the program. 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 thatThe beforeSave() method needs to return true, otherwise it will not be saved.
I hope that this article will be helpful to everyone's PHP programming based on the Yii framework.