Issue With Flash Message And Controller Refresh

I’m creating blog similar to one from 1.1 version and I have trouble with flash message not showing in this situation.

These are controller methods for showing post and adding comments:




    /**

     * Display single post.

     */

    public function actionView($url)

    {

	$model = $this->findModel($url);

	$comment = $this->newComment($model);

		

        return $this->render('view', [

	    'model' => $model,

	    'comment' => $comment,

        ]);

    }


    /**

     * Creates new comment and adds it to the database.

     * @return Comment

     */ 

    protected function newComment($model)

    {

        $comment = new Comment;

		

	if($comment->load(Yii::$app->request->post()) && $model->addComment($comment)) {

	    if($comment->status == Comment::STATUS_PENDING) {

		Yii::$app->session->setFlash('commentPosted', 'Comment is pending.');

	        return $this->refresh();

            } else {

		Yii::$app->session->setFlash('commentPosted', 'Comment is published.');

	        return $this->refresh();

	    }

	}

		

     return $comment;

     }



In view file I have this:




<?php if (Yii::$app->session->hasFlash('commentPosted')): ?>

        <div class="alert alert-success">

            <?php echo Yii::$app->session->getFlash('commentPosted');?>

        </div>

<?php else: ?>

	<h3>Leave a Comment</h3>

	<?php echo $this->render('_commentForm', [

		'comment'=>$comment,

	 ]); ?>

<?php endif; ?>



That code works as expected but doesn’t show flash message and renders comment form again.

But when I move logic from newComment method into actionView method flash messages are working.

This is working:




    /**

     * Display single post.

     */

    public function actionView($url)

    {

	$model = $this->findModel($url);

	$comment = new Comment;

		

        if($comment->load(Yii::$app->request->post()) && $model->addComment($comment)) {

	    if($comment->status == Comment::STATUS_PENDING) {

	        Yii::$app->session->setFlash('commentPosted', 'Comment is pending.');

		return $this->refresh();

	    } else {

	        Yii::$app->session->setFlash('commentPosted', 'Comment is published.');

		return $this->refresh();

	    }

		

        }

		

        return $this->render('view', [

	    'model' => $model,

	    'comment' => $comment,

	]);

    }



Not sure if it’s a bug or I’m missing something.