Reputation: 345
I'm trying to implement a commenting system on my web project, I'm extremely new to Yii. I want the user to be able to submit a comment, which in turn updates the database, and re-renders ALL the posts' comments (NB: I do not want the whole page refresh).
I'm trying to achieve this using CHtml::ajaxSubmitButton
, but I can't seem to get it to even make the call. I have no idea how to check if the call is even being made.
My current code is as follows:
_questionComment
- this is partially rendered within the 'Browse' view
<div class="form">
<?php
$form = $this -> beginWidget('CActiveForm', array(
'id' => 'question-answer-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
$response = new QuestionAnswerForm;
?>
<div class="row">
<?php
echo $form->labelEx($response, 'link');
echo $form->textField($response, 'link');
echo $form->error($response, 'link');
?>
</div>
<div class="row">
<?php
echo $form->labelEx($response, 'description');
echo $form->textField($response, 'description');
echo $form->error($response, 'description');
?>
</div>
<div class="row buttons">
<?php echo CHtml::ajaxSubmitButton('Reply', 'comment', array(
'update'=>'#comments',
'type'=>'POST',
)); ?>
</div>
<?php $this->endWidget(); ?>
</div>
QuestionController/actionComment()
- should handle the ajax request
public function actionComment()
{
if(Yii::app()->request->isAjaxRequest)
{
//current user has posted a response
if(isset($_POST['QuestionAnswerForm']))
{
$response = new QuestionAnswerForm;
$response->attributes = $_POST['QuestionAnswerForm'];
//answer form has passed inspection
if($response->validate())
{
//save new answer to database
$newAnswer = new QuestionAnswer;
$newAnswer->link = $response->link;
$newAnswer->description = $response->description;
$newAnswer->question_id = Yii::app()->getRequest()->getQuery('id');
$newAnswer->user_id = Yii::app()->user->getId();
//adds a timestamp using a default timezone 'GMT'
$newAnswer->timestamp = Timestamp::getCurrentTimeStamp();
$newAnswer->save();
}
}
}
}
browse
- This is where the comments are rendered. After the user submits their comment, I want the browse page to partially render all the comments again. I tried to achieve this using the 'update' parameter in the ajaxSubmitButton.
<?php
/*
* @var $this QuestionController
* @var $question Question
* @var $answers QuestionAnswer
*/
echo "<h1>" . $question['name'] . "</h1>";
echo "<h3>" . $question['description'] . "</h3>"
?>
<? $this->renderPartial('_renderComments', array('answers'=>$answers)); ?>
<? $this->renderPartial('_questionComment'); ?>
Upvotes: 0
Views: 7506
Reputation: 346
please check the below link.hope this will help you.
http://www.yiiframework.com/wiki/49/update-content-in-ajax-with-renderpartial/
Upvotes: 3