Custom module 'managed_file' variable info keeps disappearing I have a custom module which allows a 'managed_file' upload in the settings/config page. This works fine and displays as expected after uploading (with the filename linked, and a "Remove" submit button) but the value of the field keeps disappearing after some time. What am I missing?

Here's the code from the custom module:

  $form['custom_managed_jpg'] = array(
    '#type' =&gt; 'managed_file',
    '#name' =&gt; 'custom_managed_jpg',
    '#title' =&gt; 'Custom Image (JPG)',
    '#default_value' =&gt; variable_get('custom_managed_jpg', ''),
    '#upload_location' =&gt; 'public://custom_directory/',
    '#upload_validators' =&gt; array(
      'file_validate_extensions' =&gt; array('jpg'),
    ),
    '#description' =&gt; t('This is a custom image (jpg format).'),
  );


It appears to be a problem with the file_load function. The variable is indeed saved, as I get a file ID when I dpm() the variable_get('custom_managed_jpg') (a number -- the fid). However, when I dpm() the result of file_load($fid) it is empty.

The strangest part is that this works as expected to start with, and the file will even remain between page loads and cache clears, but then after a few hours it just disappears as described above without any warning.

UPDATE:

It seems that the reason file_load doesn't return anything is that the directory (public://custom_directory/) is empty. At some point these files are being deleted from the directory but I have no idea why.

UPDATE2:

When I watch the file_managed table, I can see a new file added after uploading. The one difference between files uploaded here and those already in the table is that the status field is set to 0 instead of 1. I am guessing that could be part of the problem? How/where do I set the status to 1 programmatically?
Scott's code is right (and is nearly identical to what I had) but the final step I was missing is in the form's submit handler, where I needed to grab the file that was uploaded and mark it as permanent, and add a file usage to tell Drupal the file was in use. By default Drupal treats uploaded files as temporary and they are deleted from the database and filesystem after 6 hours (when cron runs).

Here's the submit handler code.

function MODULE_admin_settings_submit($form, &amp;$form_state) {
  global $user;
  if (isset($form_state['values']['custom_managed_jpg']) &amp;&amp; $form_state['values']['custom_managed_jpg']!="") {
    // Load the file via file.fid.
    $file = file_load($form_state['values']['custom_managed_jpg']);
    // Change status to permanent.
    $file-&gt;status = FILE_STATUS_PERMANENT;
    file_save($file);
    // Record that the module (in this example, "custom module") is using the file. 
    file_usage_add($file, 'custom_module', 'custom_managed_jpg', $user-&gt;uid); 
  } 
}