Yii Method for adding default values to model (two methods) _ php instance

Source: Internet
Author: User
This article describes how to add default values to the model of yii, and describes how to set the following two implementation methods in the rules () method and the beforeSave () method, for more information about how to add default values to a model in yii, see the following example. We will share this with you for your reference. The details are as follows:

Yii model inherits from CActiveRecord

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

You can use either of the following 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;}

Note that the beforeSave () method must return true, otherwise it will not be saved.

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.