forked from yiisoft/yii
-
Notifications
You must be signed in to change notification settings - Fork 0
/
comment.model.txt
74 lines (57 loc) · 2.15 KB
/
comment.model.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
Customizing Comment Model
=========================
For the `Comment` model, we mainly need to customize the `rules()` and `attributeLabels()` methods. The `attributeLabels()` method returns a mapping between attribute names and attribute labels. We do not need to touch `relations()` since the code generated by the `Gii` tool is good enough.
Customizing `rules()` Method
----------------------------
We first customize the validation rules generated by the `Gii` tool. The following rules are used for comments:
~~~
[php]
public function rules()
{
return array(
array('content, author, email', 'required'),
array('author, email, url', 'length', 'max'=>128),
array('email','email'),
array('url','url'),
);
}
~~~
In the above, we specify that the `author`, `email` and `content` attributes are required; the length of `author`, `email` and `url` cannot exceed 128; the `email` attribute must be a valid email address; and the `url` attribute must be a valid URL.
Customizing `attributeLabels()` Method
--------------------------------------
We then customize the `attributeLabels()` method to declare the label display for each model attribute. This method returns an array consisting of name-label pairs. When we call [CHtml::activeLabel()] to display an attribute label.
~~~
[php]
public function attributeLabels()
{
return array(
'id' => 'Id',
'content' => 'Comment',
'status' => 'Status',
'create_time' => 'Create Time',
'author' => 'Name',
'email' => 'Email',
'url' => 'Website',
'post_id' => 'Post',
);
}
~~~
> Tip: If the label for an attribute is not declared in `attributeLabels()`, an algorithm will be used to generate an appropriate label. For example, a label `Create Time` will be generated for attributes `create_time` or `createTime`.
Customizing Saving Process
--------------------------
Because we want to record the creation time of a comment, we override the `beforeSave()` method of `Comment` like we do for the `Post` model:
~~~
[php]
protected function beforeSave()
{
if(parent::beforeSave())
{
if($this->isNewRecord)
$this->create_time=time();
return true;
}
else
return false;
}
~~~
<div class="revision">$Id$</div>