How to know which file to delete in a submit function?
Ok I solved this but it will be different for each type of form.  The form I was adding this managed_file upload to is actually the image effect form. (image_effect_form(), I had to do some form_altering to add my submit function.) My goal was to add a new image effect that allows placing a source file onto the destination image.

What I finally did was compare the $form_state variables in the submit function for the following actions:


uploading a file when none was previously there
removing a file and submitting no file
removing a file and uploading a new file


For this particular form I came up with the following variables:

$new_fid = $form_state['values']['data']['myformfile'];
$old_fid = $form_state['image_effect']['data']['myformfile'];


Once I got what the new FID is and what the old FID was It was trivial to put together some logic that deletes the file at the appropriate place. The problem is that this isn't universal logic that works for every type of form that has a managed_file in it. There didn't seem to be a standard way to get what the old file FID was. I found it for this specific form but for the next time I do a managed_file I'll have to examine $form_state again and find out if/where the old file FID is stored.

My code for the submit function is below. I also added some logic for the file_usage table.

$source_file_new_fid = $form_state['values']['data']['source_file'];
$source_file_old_fid = $form_state['image_effect']['data']['source_file'];

if ($source_file_new_fid != 0) {
  $source_file = file_load($source_file_new_fid);
  $source_file-&gt;status = FILE_STATUS_PERMANENT;
  file_save($source_file);
  file_usage_add($source_file, 'imagemerge', 'image_style', $form_state['image_style']['isid']);
}

if ($source_file_old_fid != 0) {
  $del_file = file_load($source_file_old_fid);
  file_usage_delete($del_file, 'imagemerge', 'image_style', $form_state['image_style']['isid']);
  file_delete($del_file);
}