In case you've missed it, you are looking at an older version of the website. Checkout our latest version, we promise you will love it 😍

Tutorial - Using Callbacks

grocery CRUD simply uses the call_user_func of PHP. So when you have for example:

 
$crud->callback_before_insert(array($this,'my_callback'));
 

this simply means that you insert as a callback the function "my_callback" from your controller. So it is the same thing like this:

$this->my_callback();

So you can use whatever callback you like, for example:

 
$this->load->model('Customers');
$crud->callback_before_insert(array($this->Customers,'getCustomersCallback'));
 

This equals with :

$this->Customers->getCustomersCallback()

or if you have PHP version greater or equal to 5.3 you can also use anonymous functions like for example:

$crud->callback_before_insert(function($post_array){
    $post_array['user_id'] = $this->session->userdata('user_id');
    return $post_array;
});
or you can simply use a static method inside a class for example:
$crud->callback_column('buyPrice', 'Examples::valueToEuro');
which equals with:
Examples::valueToEuro()

The most common way to use it is like this:

$crud->callback_before_insert(array($this,'_my_callback'));
This will simply call the :
$this->_my_callback();
Note: It is suggested to use the underscore (_) before the callback name. This is because if you add the underscore at a function in your Controller it is not accessible from the URL. The private and protected method are not accessible from the $this so be careful to not use callbacks as protected or private methods.

So how it works anyway?

All the callbacks are well documented with an example of usage at the API and functions section of the website. Each callback takes different parameter so you have to check the example first from the API.

Let's see an example of callback_before_update method.

$crud->callback_before_update(array($this,'encrypt_password_callback'));
and
function encrypt_password_callback($post_array, $primary_key) {
    $this->load->library('encrypt');
 
    //Encrypt password only if is not empty. Else don't change the password to an empty field
    if(!empty($post_array['password']))
    {
        $key = 'super-secret-key';
        $post_array['password'] = $this->encrypt->encode($post_array['password'], $key);
    }
    else
    {
        unset($post_array['password']);
    }
 
  return $post_array;
}
This simply means that before the update we will call the
$this->encrypt_password_callback($post_array, $primary_key);
where $this is the Controllers $this and $post_array, $primary_key are automatically inserted from the grocery CRUD library