I've put together a simple FormAPI form including a file field.
The user should be able to upload a file and save the form, then come back later having the option to "undo" the upload - making the previously set file field blank again.
What is the best way to allow the user to clear the field?
Note: I'm looking for a way to empty / delete the myfile
variable. The actual file does not necessarily need to be deleted from the filesystem, although this would be a bonus.
function mymodule_form($form, &$form_state) {
$form['myfile'] = array(
'#name' => 'files[myfile]',
'#type' => 'file',
'#title' => t('Select a file to upload'),
'#field_prefix' => variable_get('myfile'), //show the filename if saved previously
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save changes'),
);
$form['#validate'][] = 'mymodule_validate';
$form['#submit'][] = 'system_settings_form_submit';
$form['#theme'] = 'system_settings_form';
return $form;
}
function mymodule_validate(&$form, &$form_state) {
if ($tmp_file = file_save_upload('myfile')) {
$destination = 'public://' . uniqid() . '_' . $tmp_file->filename;
if ( $file = file_copy($tmp_file, $destination, FILE_EXISTS_RENAME) ) {
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
$form_state['values']['myfile'] = file_create_url($file->uri);
} else {
form_set_error('myfile', t("Failed to upload."));
}
}
}