callbackDelete

callbackDelete(callable $callback)

The basic usage of callbackDelete is when you want to skip the delete functionality. If the callbackDelete is called then that means that the actual default delete functionality of Grocery CRUD Enterprise will not triggered.

Warning! Please be aware that you should also add a callback into the callbackDeleteMultiple in order to make sure that the callback is always triggered. For more also check: callbackDeleteMultiple documentation

The callbackDelete is getting as a parameter a callback. This callback has as parameter the below:

For example:

$crud->callbackDelete(function ($stateParameters) {
    // Your code will run here
    return $stateParameters;
});

Example

Below you can see a full example. At the below example we are skipping completely the delete functionality and instead we are updating the row by adding at the title the word "[DELETED]"

$crud->setTable('employees');
$crud->setSubject('Employee', 'Employees');
$crud->setRelation('officeCode','offices','city');
$crud->displayAs('officeCode','City');

// Unsetting the multiple delete for this example. If we need it we also need to
// consider to add a $crud->callbackDeleteMultiple callback
$crud->unsetDeleteMultiple();

$crud->callbackDelete(function ($stateParameters) use ($callbackDeleteModel) {
    $callbackDeleteModel->deleteEmployee($stateParameters->primaryKeyValue);

    return $stateParameters;
});

$output = $crud->render();

Try to remove one row at the below example to see exactly the functionality of the above example:

$callbackDeleteModel is using Grocery CRUD Custom Model but you are not limited on that. On callbacks you can use any custom libraries.

For reference the code for CallbackDelete class can be found below:

<?php
namespace App\Models;
use GroceryCrud\Core\Exceptions\Exception;
use GroceryCrud\Core\Model;
use Laminas\Db\Sql\Sql;

class CallbackDelete extends Model {
    public function deleteEmployee($employeeNumber) {
        // Validating our data
        if (!is_numeric($employeeNumber)) {
            throw new Exception("Wrong input");
        }

        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from('employees');
        $select->where(['employeeNumber = ?' => $employeeNumber]);

        $employee = $this->getRowFromSelect($select, $sql);

        // More validations
        if (!empty($employee) && is_array($employee) && count($employee) === 1) {
            $employeeLastName = $employee[0]['lastName'];

            if (!strstr($employeeLastName, '[DELETED] ')) {
                $update = $sql->update('employees');
                $update->where(['employeeNumber = ?' => $employeeNumber]);

                $update->set(['lastName' => '[DELETED] ' . $employeeLastName]);

                $statement = $sql->prepareStatementForSqlObject($update);
                return $statement->execute();
            }
        }

        return false;
    }
}