Home > Backend Development > PHP Tutorial > 2 ways to implement model adding default value in Yii

2 ways to implement model adding default value in Yii

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-29 09:07:32
Original
1021 people have browsed it

The example in this article describes how Yii implements the method of adding default values ​​to the model. 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 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'),
  );
}

Copy after login

2. Set in the beforeSave() method:

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

Copy after login

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

I hope this article will help you design PHP programs based on the Yii framework.

The above introduces two ways to add default values ​​to the model in Yii, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
Statement of this Website
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
Latest Issues
Switch user
From 1970-01-01 08:00:00
0
0
0
User login
From 1970-01-01 08:00:00
0
0
0
Delete user to get id
From 1970-01-01 08:00:00
0
0
0
Translate: Laravel: Get Sanctum token by user ID
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template