Customizing Comment Model
For the
1. Customizing
We first customize the validation rules generated by the
In the above, we specify that the
2. Customizing
We then customize 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.
1. Customizing rules() Method
We first customize the validation rules generated by the Gii tool. The following rules are used for comments: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 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.
2. 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.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 inattributeLabels(), an algorithm will be used to generate an appropriate label. For example, a labelCreate Timewill be generated for attributescreate_timeorcreateTime.
3. Customizing Saving Process
Because we want to record the creation time of a comment, we override thebeforeSave() method of Comment like we do for the Post model:protected function beforeSave() { if(parent::beforeSave()) { if($this->isNewRecord) $this->create_time=time(); return true; } else return false; }
0 comments:
Post a Comment