0 follower

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.

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),

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.

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 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.

3. 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:

protected function beforeSave()
        return true;
        return false;

Found a typo or you think this page needs improvement?
Edit it on github !