3

I am using hook_form_alter() to add a file upload field to the taxonomy term form. The form itself and the submit are working well. From the submit callback i save the uploaded file using file_save_upload(). This also works well, the is saved in sites/default/files and in the files database. I have noticed that when Drupal CRON is executed the files i saved are deleted, but the other files (from CCK for example) remains in the table. Files are also deleted from the sites/default/files directory.

Here is my code :

/**
 * Implementation of hook_form_alter()
 */
function community_form_alter($form, $form_state, $form_id) {
  switch($form_id) {
    case 'taxonomy_form_term':
      // get the current image if any
      $image = variable_get('community_term_image_'.$form['tid']['#value'], '');
      // load file
      if($image) $image = field_file_load($image);
      $form['identification']['image_preview'] = array(
        '#type' => 'markup',
        '#value' => $image ? theme_imagecache('community-section-title', $image['filepath']) : '',
      );
      $form['identification']['image'] = array(
        '#title' => t('Category image'),
        '#type' => 'file',
      );
      $form['#attributes'] = array('enctype' => "multipart/form-data");
      $form['#submit'][] = 'community_term_form_image_submit';
    break;
  }
}

function community_term_form_image_submit($form, &$form_state) {
  $dir = variable_get('file_directory_path', 'files');
  $save = file_save_upload('image', array(), $dir);
  if($save->fid) {
    // If the term currently contains a picture, we remove it prior to saving
    // the new one
    $current_image = variable_get('community_term_image_'.$form_state['values']['tid'], '');
    if($current_image) {
      $current_image = field_file_load($current_image);
      db_query('DELETE FROM {files} WHERE fid = %d', $current_image['fid']);
      file_delete($current_image['filepath']);
    }
    variable_set('community_term_image_'.$form_state['values']['tid'], $save->fid);
  }
}
3

file_save_upload():

The source file is validated as a proper upload and handled as such. The file will be added to the files table as a temporary file. Temporary files are periodically cleaned. To make the file permanent file call file_set_status() to change its status.

You need to use file_set_status() to change the status of the file.

  $save = file_save_upload('image', array(), $dir);
  if($save->fid) {
    file_set_status($save,FILE_STATUS_PERMANENT);
    ...
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.