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);
}
}