Ajii删除yii

How can I put a ajax delete button for delete the comment by the posted user?
_form

 echo '<div><h3><b><u>Comments</u></b></h3></div>';

 $commentList = Comments::model()->findAllByAttributes(array('offereventid'=>$id));
     foreach($commentList as $Listdata2)
     {   
        $usercomment = $Listdata2['comment']; 
        $usercommentid = $Listdata2['id'];          
        $usercomtname = $Listdata2['name'];         
        $usercommentmail = $Listdata2['email'];      
        echo '<div><span class="name1">'.$usercomtname.':</span> '.'<span class ="email1">'.'['.$usercommentmail.']'.'</span>'.'</div>';            
        echo '<div class = "cmnts" >'.'"'.$usercomment.'"'.'['.$usercommentid.']'.'</div>';
        // echo CHtml::ajaxSubmitButton('Delete ', array('delete', 'id'=>$usercommentid)); 

        echo '<hr>';    
     } 

please help me with it. I tried lot of methods but when i tried any user can delete the comment of any user.

I got the solution for the problem

echo CHtml::ajaxButton(
   'Delete',
   CHtml::normalizeUrl(array(
       'Comments/del/id/' . $usercommentid, 
       'render' => true
   )),
   array(
       'dataType' => 'json',
       'type' => 'post',
       'success' => 'function(data) {
            $("#name_"+data).hide();
        }',

   ),
   array('id' => $usercommentid, 'class' => 'btn btn-success')
);

The current user is given by Yii::app()->user->id.

The easiest approach will be to match the logged0in id with the user id of the comment. However I see from your code that you are storing the email and not the id.

You should therefore either

  • a) create and store the user id in the comments table
  • b) Change the UserIdentity to add the user email

I suggest (a) as the least painful option for you.

if (Yii::app()->user->id == $Listdata2['user_id']) {
    echo CHtml::ajaxSubmitButton('Delete ', array('delete', 'id' => $idComment));
}

You should then create a controller action (I have left out obvious error checks)

function actionDelete($id = null) {

   // Load the comment object
   $commentModel = Comment::model()->findByPK($id);eck if the user has 
   // TODO: Do error check here

   // Check if the user has access to do this.
    if (Yii::app()->user->id !== $commentModel->user_id) {
       // TODO: Nice error here.
       echo "This is not your comment. You cannot delete it";
    } else {
        $commentModel->delete();
        // TODO: Error checks here
    }
}