對於 Comment
模型,我們主要需要自訂 rules()
和 attributeLabels()
方法。attributeLabels()
方法會回傳屬性名稱和屬性標籤之間的對應關係。我們不需要修改 relations()
,因為 Gii
工具產生的程式碼已經足夠好用。
rules()
方法 ¶我們先自訂 Gii
工具產生的驗證規則。以下規則用於評論
public function rules()
{
return array(
array('content, author, email', 'required'),
array('author, email, url', 'length', 'max'=>128),
array('email','email'),
array('url','url'),
);
}
在以上規則中,我們指定 author
、email
和 content
屬性為必填;author
、email
和 url
的長度不能超過 128;email
屬性必須是有效的電子郵件地址;而 url
屬性必須是有效的 URL。
attributeLabels()
方法 ¶接著,我們自訂 attributeLabels()
方法,為每個模型屬性宣告標籤顯示。此方法會回傳一個由名稱-標籤配對組成的陣列。當我們呼叫 CHtml::activeLabel() 來顯示屬性標籤時。
public function attributeLabels()
{
return array(
'id' => 'Id',
'content' => 'Comment',
'status' => 'Status',
'create_time' => 'Create Time',
'author' => 'Name',
'email' => 'Email',
'url' => 'Website',
'post_id' => 'Post',
);
}
提示: 如果未在
attributeLabels()
中宣告屬性的標籤,則會使用演算法來產生適當的標籤。例如,對於屬性create_time
或createTime
,將產生標籤Create Time
。
因為我們想要記錄評論的建立時間,所以我們覆寫 Comment
的 beforeSave()
方法,就像我們對 Post
模型所做的那樣
protected function beforeSave()
{
if(parent::beforeSave())
{
if($this->isNewRecord)
$this->create_time=time();
return true;
}
else
return false;
}
發現錯字或您認為此頁面需要改進?
在 github 上編輯 !
Markdown 在 beforeValidate 而非 beforeSave 中產生
文章內容使用 CMarkdownParser 在 beforeValidate() 而非 beforeSave() 中解析的原因(您可能會認為),是為了在使用文章建立頁面上的「預覽」按鈕時,內容也會被解析。
註冊 或 登入 以進行評論。