Search code examples
codeigniterfile-uploadgrocery-crud

grocery crud rename filename on upload


I need to rename the file on file upload and inserting to the database. I search for ways but i can't find the right code. I tried to use callback but it did not work.

Here's my code:

public function home()
{
    $crud = new grocery_CRUD();
    $crud->set_theme('datatables');
    $crud->set_table('blog_post');
    $crud->set_field_upload('post_image',UPLOAD_PATH);
    $crud->callback_before_upload(array($this,'_before_upload'))
    $crud->callback_before_insert(array($this,'rename_img_db'));
    $output = $crud->render();
    $this->_example_output($output);
}   
function rename_img_db($post_array) 
{
    if (!empty($post_array['post_image'])) {
        $ext = end(explode(".",$post_array['post_image']));
        $img_name = $post_array['post_image'] = mktime().".".$ext;
        $post_array['post_image'] = $img_name;
    }
    return $post_array;
}
function _before_upload($files_to_upload,$field_info)
{
    foreach($files_to_upload as $value) {
        $ext = pathinfo($value['name'], PATHINFO_EXTENSION);
        $rename = $value['name'];
    }
    $allowed_formats = array("jpg","gif","png","doc","docx","pdf");
    if(in_array($ext,$allowed_formats))
    {
        return true;
    }
    else
    {
        return 'Wrong file format'; 
    }

    if ($rename) {
        $ext1 = end(explode(".",$rename));
        $img_name = $rename = mktime().".".$ext1;
        $rename = $img_name;

        return $rename;
    }
} 

Solution

  • I noticed a tipo in your line: $crud->callback_before_upload(array($this,'_before_upload'))

    Moreover I had to do something similar and I used the callback_after_insert, then you can get the $primary_key variable and with that update the element, something like this:

    $crud->callback_after_insert(array($this, 'rename_img_db'));
    
    public function rename_img_db($post_array,$primary_key)
        {
    
            //Here goes the get and set querys with your $primary_key
    
        }