yii实现model添加默认值的方法(2种方法),yiimodel_PHP教程

WBOY
Release: 2016-07-12 09:01:26
Original
1082 people have browsed it

yii实现model添加默认值的方法(2种方法),yiimodel

本文实例讲述了yii实现model添加默认值的方法。分享给大家供大家参考,具体如下:

yii model 继承自CActiveRecord

有些字段可能不会出现在表单中,而需要在程序中加入。如订单编号,时间戳,操作的user_id等等。

以下二种方法:

1、在rules()方法中设定:

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、在beforeSave()方法中设定:

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

Copy after login

需要注意的是,beforeSave()方法需要return true,否则不会保存

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

您可能感兴趣的文章:

  • Yii基于数组和对象的Model查询技巧实例详解
  • Yii中Model(模型)的创建及使用方法
  • PHP YII框架开发小技巧之模型(models)中rules自定义验证规则
  • Yii不依赖Model的表单生成器用法实例

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1089200.htmlTechArticleyii实现model添加默认值的方法(2种方法),yiimodel 本文实例讲述了yii实现model添加默认值的方法。分享给大家供大家参考,具体如下: yii mod...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!