In this section, we implement the comment display and creation features.
In order to enhance the user interactivity, we would like to prompt users the possible errors each time he finishes entering one field. This is known client-side input validation. We will show how this can be done in Yii seamlessly and extremely easy. Note that this requires Yii version 1.1.1 or later.
Instead of displaying and creating comments on individual pages, we use the post detail page (generated by the view
action of PostController
). Below the post content display, we display first a list of comments belonging to that post and then a comment creation form.
In order to display comments on the post detail page, we modify the view script /wwwroot/blog/protected/views/post/view.php
as follows,
...post view here... <div id="comments"> if($model->commentCount>=1): <h3> echo $model->commentCount . 'comment(s)'; </h3> $this->renderPartial('_comments',array( 'post'=>$model, 'comments'=>$model->comments, )); endif; </div>
In the above, we call renderPartial()
to render a partial view named _comments
to display the list of comments belonging to the current post. Note that in the view we use the expression $model->comments
to retrieve the comments for the post. This is valid because we have declared a comments
relation in the Post
class. Evaluating this expression would trigger an implicit JOIN database query to bring back the proper comments. This feature is known as lazy relational query.
The partial view _comments
is not very interesting. It mainly goes through every comment and displays the detail of it. Interested readers may refer to /wwwroot/yii/demos/blog/protected/views/post/_comments.php
.
To handle comment creation, we first modify the actionView()
method of PostController
as follows,
public function actionView()
{
$post=$this->loadModel();
$comment=$this->newComment($post);
$this->render('view',array(
'model'=>$post,
'comment'=>$comment,
));
}
protected function newComment($post)
{
$comment=new Comment;
if(isset($_POST['Comment']))
{
$comment->attributes=$_POST['Comment'];
if($post->addComment($comment))
{
if($comment->status==Comment::STATUS_PENDING)
Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');
$this->refresh();
}
}
return $comment;
}
And then we modify the Post
model class by adding the method addComment()
as follows,
public function addComment($comment)
{
if(Yii::app()->params['commentNeedApproval'])
$comment->status=Comment::STATUS_PENDING;
else
$comment->status=Comment::STATUS_APPROVED;
$comment->post_id=$this->id;
return $comment->save();
}
In the above, we call the newComment()
method before we render view
. In the newComment()
method, we generate a Comment
instance and check if the comment form is submitted. If so, we try to add the comment for the post by calling $post->addComment($comment)
. If it goes through, we refresh the post detail page, which will display the newly created comment unless approval is required. In the case where the comment first requires approval prior to display, we will show a flash message to indicate to the user that the comment will be displayed once approved. A flash message is usually a confirmation message displayed to end users. If the user clicks on the refresh button of his browser, the message will disappear.
We also need to modify /wwwroot/blog/protected/views/post/view.php
furthermore,
...... <div id="comments"> ...... <h3>Leave a Comment</h3> if(Yii::app()->user->hasFlash('commentSubmitted')): <div class="flash-success"> echo Yii::app()->user->getFlash('commentSubmitted'); </div> else: $this->renderPartial('/comment/_form',array( 'model'=>$comment, )); endif; </div><!-- comments -->
In the above code, we display the flash message if it is available. If not, we display the comment input form by rendering the partial view /wwwroot/blog/protected/views/comment/_form.php
.
In order to improve user experience, we can use Ajax-based form field validation so that the user is provided with validation feedback as they fill out the form, before having to submit the entire form to the server. To support Ajax-based validation on the comment form, we need to make some minor changes to both the comment form view /wwwroot/blog/protected/views/comment/_form.php
and the newComment()
method.
In the _form.php
file, we mainly need to set CActiveForm::enableAjaxValidation to be true when we create the CActiveForm widget:
<div class="form"> $form=$this->beginWidget('CActiveForm', array( 'id'=>'comment-form', 'enableAjaxValidation'=>true, )); ...... $this->endWidget(); </div><!-- form -->
And in the newComment()
method, we insert a piece of code to respond to the AJAX validation requests. The code checks if there is a POST
variable named ajax
. If so, it displays the validation results by calling CActiveForm::validate.
protected function newComment($post)
{
$comment=new Comment;
if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
{
echo CActiveForm::validate($comment);
Yii::app()->end();
}
if(isset($_POST['Comment']))
{
$comment->attributes=$_POST['Comment'];
if($post->addComment($comment))
{
if($comment->status==Comment::STATUS_PENDING)
Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');
$this->refresh();
}
}
return $comment;
}
Found a typo or you think this page needs improvement?
Edit it on github !
follow up ...
hit submit by mistake ... (how do I edit my comments by the way ?)
so :
$url=$this->getController()->createUrl($this->captchaAction); CHtml::image($url,$alt,$this->imageOptions);
are the important lines. The first one creates an action for the current controller which will look like this (default urls with get parameters) : index.php?r=post/captcha
this url will be used to point to the captcha action CCaptchaAction which will actually render the image with the help of the gd library (see renderImage method of the CCaptchaAction class).
But for all this to work you need to have this url point to the right action and this is done in the actions array of the PostController (see Action section in tne Controller page of the guide):
/** * Declares class-based actions. */ public function actions() { return array( // captcha action renders the CAPTCHA image // this is used by the contact page 'captcha'=>array( 'class'=>'CCaptchaAction', 'backColor'=>0xF5F5F5, ), ); }
hope this helps someone who like me was trying to follow the tutorial without looking at the completed demo code.
verifyCode variabein Comment Model
Hi,
Since I spent 15 mn trying to figure out why the application was returning a :
Property "Comment.verifyCode" is not defined.
when trying to setup the new Comment form
I thought I'd share that I think there must exist in th emodel a variable for each Validation Rule that has been set up in thi same model. That is for validation rules for fields that ar not a db field.
Example :
for this rule to exist without any errors being returned :
array('verifyCode', 'captcha', 'on' => 'insert', 'allowEmpty'=>!Yii::app()->user->isGuest)
the following line must be added in the Comment model
public $verifyCode;
Maybe it was explaned somawhere but if this is the case I missed the info :)
hope htat helps someone
Thanks
is a rule that
addComment
addComment is in the post model
public function addComment($comment) { if(Yii::app()->params['commentNeedApproval']) $comment->status=Comment::STATUS_PENDING; else $comment->status=Comment::STATUS_APPROVED; $comment->post_id=$this->id; return $comment->save(); }
what 'commentNeedApproval' is doing
It took me a while to figure out what was going on in the line referring to 'commentNeedApproval' so I figured I'd share the answer.
You have to add an app parameter in the config file main.php:
return array( ... // application-level parameters that can be accessed // using Yii::app()->params['paramName'] 'params'=>array( ... 'commentNeedApproval'=>true, ),
Works like a charm!
Signup or Login in order to comment.