callback_before_insert

void callback_before_insert(mixed $callback )
Quick Description: This callback runs before the auto insert of the crud.

This callback runs before the auto insert of the crud. The callback takes as a 1st parameter the post array. The return value is not required. Although if you return a value must be an array like a post array. With this opportunity you can add or unset some post variables.

Example:

public function users(){
$crud = new grocery_CRUD();
$crud->set_table('db_user');
$crud->set_subject('User');
$crud->required_fields('user_name');
 
$crud->columns('user_name','email','real_name','active', 'groups');
$crud->fields('user_name','email','password','real_name','active', 'groups');
$crud->change_field_type('password', 'password');
 
$crud->callback_before_insert(array($this,'encrypt_password_callback'));
 
$output = $crud->render();
$this->_example_output($output);
}
 
function encrypt_password_callback($post_array) {
$this->load->library('encrypt');
$key = 'super-secret-key';
$post_array['password'] = $this->encrypt->encode($post_array['password'], $key);
 
return $post_array;
}        
 

Note: Be careful when there are fields that are not included at the fields method then you cannot just add more fields at the callback_before_insert. For example at the current example if we have something like that:

function encrypt_password_callback($post_array) {
$this->load->library('encrypt');
$key = 'super-secret-key';
$post_array['password'] = $this->encrypt->encode($post_array['password'], $key);
 
$post_array['insert_date'] = date('Y-d-m');
$post_array['updated_date'] = date('Y-d-m');
 
return $post_array;
}

it will NOT work as for security reasons grocery CRUD doesn't recognize the insert_date and the update_date field. To make it recognized you have to add it at the fields method (fields, add_fields or edit_fields). So for the current example we will have:

$crud->fields('insert_date','updated_date','user_name','email','password','real_name','active', 'groups');

And of course after this we have to remove the fields from the form so we can transform these two fields to invisible fields. You can simply do that in the current example like this:

$crud->change_field_type('insert_date','invisible');
$crud->change_field_type('updated_date','invisible');
 

For more about "invisible" fields you can read the invisible field type