Permalink
Browse files

add update action + events for upd/delete close #4

- added update button and action
- added events for update and delete
- documentation update
  • Loading branch information...
1 parent 303285e commit 929699dcbdb1dcd9fe97cc85e93dceea79ae1313 @cebe cebe committed Dec 22, 2011
Showing with 175 additions and 43 deletions.
  1. +2 −0 CHANGELOG.md
  2. +29 −1 CommentModule.php
  3. +16 −5 README.md
  4. +18 −2 behaviors/CommentableBehavior.php
  5. +37 −11 controllers/CommentController.php
  6. +34 −10 models/Comment.php
  7. +24 −12 views/comment/_form.php
  8. +15 −2 views/comment/_view.php
View
2 CHANGELOG.md
@@ -2,6 +2,8 @@
### 0.6.0 (to be released)
- added getCommentCount() to CommentableBehavior (cebe)
+- added delete button and action (cebe)
+- added update button and action (cebe)
### 0.5.0 (2011-12-19)
View
30 CommentModule.php
@@ -17,7 +17,7 @@ class CommentModule extends CWebModule
* 'modelclass' is a class name of the commentable AR
* this AR class must have the {@see CommentableBehavior} attached to it
*/
- public $commentableModels = array('task');
+ public $commentableModels = array();
/**
* @var string name of the user model class to use for comments
@@ -82,4 +82,32 @@ public function onNewComment($comment, $model)
$event->commentedModel = $model;
$this->raiseEvent('onNewComment', $event);
}
+
+ /**
+ * This event is raised after a comment has been updated
+ *
+ * @param $comment
+ * @param $model currently not available see {@link https://github.com/yiiext/comment-module/issues/10}
+ */
+ public function onUpdateComment($comment/*, $model*/)
+ {
+ $event = new CommentEvent();
+ $event->comment = $comment;
+ //$event->commentedModel = $model;
+ $this->raiseEvent('onUpdateComment', $event);
+ }
+
+ /**
+ * This event is raised after a comment got deleted
+ *
+ * @param $comment
+ * @param $model currently not available see {@link https://github.com/yiiext/comment-module/issues/10}
+ */
+ public function onDeleteComment($comment/*, $model*/)
+ {
+ $event = new CommentEvent();
+ $event->comment = $comment;
+ //$event->commentedModel = $model;
+ $this->raiseEvent('onDeleteComment', $event);
+ }
}
View
21 README.md
@@ -4,9 +4,10 @@ Comment module
makes every entity of your application commentable.
Features:
-* Ajax creation of comment
+* Create, Update, Delete comments with ajax
* Gravatar support
* define multiple models that can be commented
+* Events raised on new, update, delete
* more coming soon...
If there is something missing here, or you think one step should be described more detailed,
@@ -151,14 +152,24 @@ See [CModule::behaviors](http://www.yiiframework.com/doc/api/1.1/CModule#behavio
This event is raised when a new comment has been saved.
The following attributes are available on the `$event` given as the first parameter to the event handler:
-* `$event->comment` is the currently added comment.
+* `$event->comment` is the ActiveRecord instance of the currently added comment.
* `$event->commentedModel` is the model the comment was added to.
Possible use cases:
* Send an E-Mail-Notification
-Events coming soon:
+### onUpdateComment
+
+This event is raised when a user edited a comment.
+The following attributes are available on the `$event` given as the first parameter to the event handler:
+
+* `$event->comment` is the ActiveRecord instance of the updated comment.
+
+### onDeleteComment
+
+This event is raised when a user deleted a comment.
+The following attributes are available on the `$event` given as the first parameter to the event handler:
+
+* `$event->comment` is the ActiveRecord instance of the deleted comment.
-### onCommentEdited
-### onCommentDelete
View
20 behaviors/CommentableBehavior.php
@@ -42,6 +42,8 @@
* }
* </pre>
*
+ * @property CommentModule $module
+ *
* @author Carsten Brandt <mail@cebe.cc>
* @package yiiext.modules.comment
*/
@@ -101,8 +103,22 @@ public function getCommentInstance()
*/
public function getComments()
{
- return Yii::createComponent($this->module->commentModelClass)
- ->findAll($this->getCommentCriteria());
+ $comments = Yii::createComponent($this->module->commentModelClass)
+ ->findAll($this->getCommentCriteria());
+ // get model type
+ $type = get_class($this->owner);
+ foreach($this->module->commentableModels as $scope => $model) {
+ if ($type == $model) {
+ $type = $scope;
+ break;
+ }
+ }
+ foreach($comments as $comment) {
+ /** @var Comment $comment */
+ $comment->setType($type);
+ $comment->setKey($this->owner->primaryKey);
+ }
+ return $comments;
}
/**
View
48 controllers/CommentController.php
@@ -105,21 +105,46 @@ public function actionCreate()
*/
public function actionUpdate($id)
{
- $model=$this->loadModel($id);
+ $comment=$this->loadModel($id);
- // Uncomment the following line if AJAX validation is needed
- // $this->performAjaxValidation($model);
-
- if(isset($_POST[$cClass=get_class($model)]))
+ if(isset($_POST[$cClass=get_class($comment)]))
{
- $model->attributes=$_POST[$cClass];
- if($model->save())
- $this->redirect(array('view','id'=>$model->id));
+ $comment->attributes = $_POST[$cClass];
+
+ if ($comment->save())
+ {
+ if(Yii::app()->request->isAjaxRequest) {
+ // refresh model to replace CDbExpression for timestamp attribute
+ $comment->refresh();
+
+ // render updated comment
+ $this->renderPartial('_view',array(
+ 'data'=>$comment,
+ ));
+ Yii::app()->end();
+ } else {
+ $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('view','id'=>$comment->id));
+ }
+ }
}
- $this->render('update',array(
- 'model'=>$model,
- ));
+ if(Yii::app()->request->isAjaxRequest)
+ {
+ $output = $this->renderPartial('_form',array(
+ 'comment'=>$comment,
+ 'ajaxId'=>time(),
+ ), true);
+ // render javascript functions
+ Yii::app()->clientScript->renderBodyEnd($output);
+ echo $output;
+ Yii::app()->end();
+ }
+ else
+ {
+ $this->render('update',array(
+ 'model'=>$comment,
+ ));
+ }
}
/**
@@ -170,6 +195,7 @@ public function actionDelete($id)
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
+ * @return Comment
*/
public function loadModel($id)
{
View
44 models/Comment.php
@@ -24,6 +24,7 @@ class Comment extends CActiveRecord
{
private $_type;
private $_key;
+ private $_new = false;
/**
* @var string set the commentableModels scope from CommentModule
@@ -102,8 +103,8 @@ public function rules()
{
return array(
array('message', 'safe'),
- array('type', 'validateType'),
- array('key', 'validateKey'),
+ array('type', 'validateType', 'on'=>'create'),
+ array('key', 'validateKey', 'on'=>'create'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, message, userId', 'safe', 'on'=>'search'),
@@ -138,18 +139,41 @@ public function relations()
);
}
+ protected function beforeSave()
+ {
+ $this->_new = $this->isNewRecord;
+ return parent::beforeSave();
+ }
+
protected function afterSave()
{
- $commentedModel = CActiveRecord::model($this->module->commentableModels[$this->type]);
- $this->getDbConnection()->createCommand(
- "INSERT INTO ".$commentedModel->mapTable."(".$commentedModel->mapCommentColumn.", ".$commentedModel->mapRelatedColumn.")
- VALUES (:id, :key);"
- )->execute(array(':id' => $this->id, ':key' => $this->key));
+ if ($this->_new) {
+ $commentedModel = CActiveRecord::model($this->module->commentableModels[$this->type]);
+ // if comment is new, connect it with commended model
+ $this->getDbConnection()->createCommand(
+ "INSERT INTO ".$commentedModel->mapTable."(".$commentedModel->mapCommentColumn.", ".$commentedModel->mapRelatedColumn.")
+ VALUES (:id, :key);"
+ )->execute(array(':id' => $this->id, ':key' => $this->key));
+
+ parent::afterSave();
- parent::afterSave();
+ // raise new comment event
+ $this->module->onNewComment($this, $commentedModel->findByPk($this->key));
+ } else {
+ parent::afterSave();
+ }
+ // raise update comment event
+ $this->module->onUpdateComment($this/*, $commentedModel->findByPk($this->key)*/);
+ }
- // raise new comment event
- $this->module->onNewComment($this, $commentedModel->findByPk($this->key));
+ protected function afterDelete()
+ {
+ parent::afterDelete();
+ // raise update comment event
+ $this->module->onDeleteComment(
+ $this/*,
+ CActiveRecord::model($this->module->commentableModels[$this->type])->findByPk($this->key)*/
+ );
}
/**
View
36 views/comment/_form.php
@@ -1,44 +1,56 @@
<?php if (Yii::app()->user->isGuest) {
-?><div class="comment-not-loggedin">
+?><div class="ext-comment-not-loggedin">
Sorry, you have to login to leave a comment.
</div><?php } else { ?>
-<div id="comment-form-ajax" class="form">
+<div id="ext-comment-form-<?php echo $comment->isNewRecord ? 'new' : 'edit-'.$comment->id; ?>" class="form">
<?php $form = $this->beginWidget('CActiveForm', array(
- 'id'=>'comment-form',
+ 'id'=>'ext-comment-form',
'action'=>array('/comment/comment/create'),
'enableAjaxValidation'=>false
)); ?>
- <?php echo $form->error($comment,'userId'); ?>
+ <?php /** @var CActiveForm $form */
+ echo $form->errorSummary($comment); ?>
<div class="row">
<?php echo $form->labelEx($comment,'message'); ?>
<?php echo $form->textArea($comment,'message',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($comment,'message'); ?>
</div>
- <?php echo $form->hiddenField($comment, 'type'); ?>
- <?php echo $form->hiddenField($comment, 'key'); ?>
-
<div class="row buttons">
<?php if ($comment->isNewRecord) {
+
+ echo $form->hiddenField($comment, 'type');
+ echo $form->hiddenField($comment, 'key');
+
/* echo CHtml::hiddenField('returnUrl', $this->createUrl(''));}
echo CHtml::submitButton('Save'); */
echo CHtml::ajaxSubmitButton('Submit',
array('/comment/comment/create'),
array(
- 'replace'=>'#comment-form-ajax',
+ 'replace'=>'#ext-comment-form-new',
'error'=>"function(){
$('#Comment_message').css('border-color', 'red');
$('#Comment_message').css('background-color', '#fcc');
}"
),
- array('id'=>'submit-comment' . (isset($ajaxId) ? $ajaxId : ''))
+ array('id'=>'ext-comment-submit' . (isset($ajaxId) ? $ajaxId : ''))
);
- } else {
- echo CHtml::submitButton('Save');
- }
+ } else {
+ echo CHtml::ajaxSubmitButton('Update',
+ array('/comment/comment/update', 'id'=>$comment->id),
+ array(
+ 'replace'=>'#ext-comment-form-edit-'.$comment->id,
+ 'error'=>"function(){
+ $('#Comment_message').css('border-color', 'red');
+ $('#Comment_message').css('background-color', '#fcc');
+ }"
+ ),
+ array('id'=>'ext-comment-submit' . (isset($ajaxId) ? $ajaxId : ''))
+ );
+ }
?>
</div>
View
17 views/comment/_view.php
@@ -31,7 +31,8 @@
}
");
?>
-<div class="ext-comment">
+<div class="ext-comment" id="ext-comment-<?php echo $data->id; ?>">
+
<span class="ext-comment-head">
<span class="ext-comment-name"><?php echo CHtml::encode($data->userName); ?></span>
wrote on
@@ -41,7 +42,9 @@
); ?>
</span>:
</span>
+
<hr />
+
<?php $this->widget('comment.extensions.gravatar.yii-gravatar.YiiGravatar', array(
'email'=>$data->userEmail,
'size'=>80,
@@ -54,17 +57,27 @@
'title'=>CHtml::encode($data->userName)
)
)); ?>
+
<span class="ext-comment-options">
<?php if (!Yii::app()->user->isGuest && (Yii::app()->user->id == $data->userId)) {
echo CHtml::ajaxLink('delete', array('/comment/comment/delete', 'id'=>$data->id), array(
- 'success'=>'function(){ $("#delete-comment-'.$data->id.'").parent().parent().remove(); }',
+ 'success'=>'function(){ $("#ext-comment-'.$data->id.'").remove(); }',
'type'=>'POST',
), array(
'id'=>'delete-comment-'.$data->id,
'confirm'=>'Are you sure you want to delete this item?',
));
+ echo " | ";
+ echo CHtml::ajaxLink('edit', array('/comment/comment/update', 'id'=>$data->id), array(
+ 'replace'=>'#ext-comment-'.$data->id,
+ 'type'=>'GET',
+ ), array(
+ 'id'=>'ext-comment-edit-'.$data->id,
+ ));
} ?>
</span>
+
<p><?php echo nl2br(CHtml::encode($data->message)); ?></p>
+
<br style="clear: both;"/>
</div>

0 comments on commit 929699d

Please sign in to comment.