2

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.

John Skoumbourdis
  • 3,041
  • 28
  • 34
manu
  • 107
  • 3
  • 10
  • Hello @manu, it seems that your code is correct. What version of PHP are you using? Please make sure that _myfunc is at the same controller as show_courses first. – John Skoumbourdis May 11 '14 at 17:01
  • Thanx for the quick reply web johny :) I checked that. But When I use anonymous functions(like below), the problem got solved eventhough I dont know the resaon. $crud->callback_before_insert(function($post_array){ $post_array['user_id'] = $this->session->userdata('user_id'); return $post_array; }); – manu May 11 '14 at 18:18
  • I've added an answer. If you believe that this answer it is solving your issue then please accept it as the correct answer so you can help other people too. If you have another issue (for example with ````$crud->callback_before_insert```` ), you will need to add another question in stackoverflow. – John Skoumbourdis May 12 '14 at 04:40

1 Answers1

2

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.

John Skoumbourdis
  • 3,041
  • 28
  • 34