Consider the following bit of code in my custom module... It allows a user to upload an image, saves the fid as a variable, and in a custom submit function, it makes sure that the file in the file_managed table is saved permanently.
This all works great, but when my users are uploading a file, then saving, then removing that old file and uploading another and saving, all of these files are left in the file_managed table, with a status of 1.
function MYMODULE_admin() {
$form = array();
$form['style']['business_logo_fid'] = array(
'#title' => t('Business Logo'),
'#type' => 'managed_file',
'#description' => t('Upload a logo for your business in one of the following formats: jpg png jpeg.'),
'#default_value' => variable_get('business_logo_fid', ''),
'#upload_validators' => array(
'file_validate_extensions' => array('jpg png jpeg'),
),
'#upload_location' => 'public://',
);
$form = system_settings_form($form);
$form['#submit'][] = 'after_save_ui';
return $form;
}
function after_save_ui($form, &$form_state) {
$business_logo_fid = variable_get('business_logo_fid');
if ($business_logo_fid) {
$business_logo = file_load($business_logo_fid);
$business_logo->status = FILE_STATUS_PERMANENT;
file_save($business_logo);
}
}
How do i mark these old images as unused after a new one has been saved in its place? Is there something I can do to get the fid from the old file and mark its status as 0 before the new one gets saved? or is this something that Drupal handles already for me?