Soft delete solution

Soft delete solution

RagnarGrootKoerkampRagnarGrootKoerkamp Posts: 48Questions: 14Answers: 1

I saw some posts regarding soft deletes, i.e. not removing a row but instead setting 'deleted' to true.
Here's my solution for this:

First, change the _trigger method in Editor.php so that it will return false when any of the callbacks return false:

    $ret = true;
    for ( $i=0, $ien=count($events) ; $i<$ien ; $i++ ) {
        $val = call_user_func_array( $events[$i], $args );
        if($val === false)
            $ret = false;
    }
    return $ret;

Next, change the call to the trigger('preRemove', ...) function to

    if($this->_trigger( 'preRemove', $id, $rowData )){
        $ids[] = $id;
    }

This will result in an empty $ids array when you soft-delete all rows, so you should replace the exception 'No ids submitted for the delete' to a simple return statement.

Now, you can set the deleted field in the preRemove callback as follows:

$editor->on('preRemove', function($editor,$id,$values){
    $editor->db()
        ->raw()
        ->bind(':id',$id)
        ->exec('UPDATE users SET deleted=1 WHERE userid=:id');
    
    // don't remove this row from the table
    return false;
});

Replies

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    edited June 2016

    Very clever - thanks for sharing this!

    Cancellable events are something that is coming in Editor 1.6 and this looks like a great use for it.

    Regards,
    Allan

This discussion has been closed.