'preRemove' multiple entries but not the last

'preRemove' multiple entries but not the last

btreebtree Posts: 99Questions: 14Answers: 11

Hi guys,

I display a N:M table where you are not allowed to delete the last entry for N (hive) because each hive needs min. one M (apiary).

My code works fine when you only select one row to delete.

When you select multiple rows to delete, lets say the last two rows -> preRemove gets called for each ID and the count returns for both 2 -> After the preRemove was called for each row the code removes them both at once.

preRemove call

        ->on( 'preRemove', function ( $editor, $id, $values) {
            countmoves( $editor->db(), $values['movedate']['hive_id']); //custom function to count how much hive moves left
        } )

safety function

function countmoves($db, $id){
    $result = $db->sql('SELECT COUNT(hive_id) as count FROM movedate WHERE hive_id = '.$id);
    $count = $result->fetch();
    if ($count['count'] == 1){
        $data['error'] = __('You cannot delete the last entry!');
        echo json_encode( $data );
        exit;
    }
}

Maybe anyone had a similar problem and can help me out? I would be grateful!

Cheers
Hannes

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,847Questions: 1Answers: 10,134 Site admin
    Answer ✓

    Is the issue that you have successfully prevented the row from being deleted on the server, but Editor visually shows the row being removed on the client-side?

    Only deleting some of the rows isn't an excepted action. Editor should perhaps handle that, and I will look into adding that ability, but another option might be to prevent submitted the last row in the first place.

    Allan

  • btreebtree Posts: 99Questions: 14Answers: 11
    edited October 2015

    Hi Allan,

    no, I was looking for a function like you explained.

    I made a kind of "workaround" but I dont know why it works?! :)

    Working Code:

    function countmoves($db, $id, $rowid){
        $result = $db->sql('SELECT COUNT(hive_id) as count FROM movedate WHERE hive_id = '.$id);
        $count = $result->fetch();
        if ($count['count'] <= 1){
            $data['error'] = __('You cannot delete the last entry!');
            echo json_encode( $data );
            exit;
        }
        $db->delete( 'movedate', array(
               'id'   => $rowid)
           );
    }
    

    I added the $db->delete..... this works like a buffer. The code now thinks the row is deleted and when it checks the second time for the ID the count returns 1 and it wont delete anything at all.

    I dont think you need to look into this, it's a rare condition someone would need this.

    Cheers
    Hannes

This discussion has been closed.