manu manu - 1 month ago 16
PHP Question

Grocery CRUD: callback functions does not work

I have tried several times but it seems that none of the callback functions work with my code.

Here is the method that I am calling grocery crud

public function show_courses()
{
$crud = new grocery_CRUD();

$crud->set_table('course');
$crud->set_theme('datatables');
$crud->fields('course_id','course_name','course_cordinator');

$crud->callback_after_insert(array($this, '_myfunc'));

$output = $crud->render();

$this->output($output);
}


and here is the callback function:

function _myfunc($post_array,$primary_key)
{
$q = array(
"notice" => $primary_key
);

$this->db->insert('notice', $q);

return true;
}


please help me to find what is wrong with my code.

Answer

If you are using PHP version >= 5.3 then it is much better to use anonymous functions instead. It is much better as it always works, you don't have to search to find the function, it is much more readable and you don't have to use just a fake name to call it (for example _myfunc). So in your case you will have something like:

public function show_courses()
{
    $crud = new grocery_CRUD();

    $crud->set_table('course');
    $crud->set_theme('datatables');
    $crud->fields('course_id','course_name','course_cordinator');

    $crud->callback_after_insert(function ($post_array,$primary_key) {
            $this->db->insert('notice', array(
                "notice" => $primary_key
            ));

            return true;
    });

    $output = $crud->render();

    $this->output($output);        
}

Just for the reference all the callbacks are using the method: call_user_func of PHP. So if the function at the array($this, '_myfunct') doesn't exist, then PHP doesn't throw any errors. That's why it is always better to use anonymous functions instead. At least you know that this method will always run.