Drupal - Image Upload in a Custom Module

If you don't mind my saying you're doing this the hard way. Drupal has a managed_file element type that handles most of this logic for you:

function mymodule_custom_content_block_form($form, &$form_state) {
  $form['custom_content_block_image'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_content_block_image',
    '#title' => t('Block image'),
    '#size' => 40,
    '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    '#upload_location' => 'public://'
  ); 

  return $form; 
}

function mymodule_custom_content_block_form_submit($form, &$form_state) {
  if (isset($form_state['values']['custom_content_block_image'])) {
    $file = file_load($form_state['values']['custom_content_block_image']);

    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);
  }
}

With Clive answer my image got deleted after 6 hours. So if someone experienced the same problem that I got. Here is the solution (from Clive's answer with a little addition).

function mymodule_custom_content_block_form($form, &$form_state) {
  $form['custom_content_block_image'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_content_block_image',
    '#title' => t('Block image'),
    '#size' => 40,
    '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    '#upload_location' => 'public://'
  ); 

  return $form; 
}

function mymodule_custom_content_block_form_submit($form, &$form_state) {
  if (isset($form_state['values']['custom_content_block_image'])) {
    $file = file_load($form_state['values']['custom_content_block_image']);

    $file->status = FILE_STATUS_PERMANENT;

    $file_saved =file_save($file);
    // Record that the module is using the file. 
    file_usage_add($file_saved, 'mymodule_custom_content_block_form', 'custom_content_block_image', $file_saved->fid); 
  }
}

The solution is to add file_usage_add. From API documentation:

Note: New files are uploaded with a status of 0 and are treated as temporary files which are removed after 6 hours via cron. Your module is responsible for changing the $file objects status to FILE_STATUS_PERMANENT and saving the new status to the database. Something like the following within your submit handler should do the trick.

See: https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#managed_file

Tags:

Forms

Files

7