Managed file: the file used in the field may not be referenced I am having some issues with the managed_file type. Whenever I try to edit and save a form that has a managed_file element in it an error occurs: The file  used in the Picture field may not be referenced.

This is the code I'm using:

function foo_form ($form, &amp;$form_state, $foo) {  
  ...     
  $form['file'] = array(
    '#type' =&gt; 'managed_file',
    '#title' =&gt; t('Picture'),
    '#default_value' =&gt; (isset($foo-&gt;file-&gt;fid) ? $banner-&gt;foo-&gt;fid : ''),
    '#upload_location' =&gt; variable_get('foo_upload_location'),
  );

  if (isset($foo-&gt;file)) {
    $form['current_file'] = array(
      '#type' =&gt; 'hidden',
      '#value' =&gt; $foo-&gt;file-&gt;fid,
    );
  }
  ...
  $form['submit'] = array(
    '#type' =&gt; 'submit',
    '#value' =&gt; t('Save'),
  );
  return $form;
 }

function foo_form_submit ($form, &amp;$form_state) {
  $foo = (object)$form_state['values'];

  $current_file_set = isset($form_state['values']['current_file']);

  if ($form_state['values']['file'] != 0 &amp;&amp; !$current_file_set) {
    // Load the file uploaded in the form.
    $file = file_load($form_state['values']['file']);

    $file-&gt;status = FILE_STATUS_PERMANENT;

    file_save($file);

    $foo-&gt;file = $file-&gt;fid;
  } else if ($form_state['values']['file'] != 0 &amp;&amp; $current_file_set) {

    // If we are uploading a different picture, delete the old one and save the
    // new one. If not, don't do anything.
    if ($form_state['values']['current_file'] != $form_state['values']['file']) {
      file_delete(file_load($form_state['values']['current_file']));
      // Load the file uploaded in the form.
      $file = file_load($form_state['values']['file']);

      $file-&gt;status = FILE_STATUS_PERMANENT;

      file_save($file);

      $foo-&gt;file = $file-&gt;fid;
    }
  } else {
    file_delete(file_load($form_state['values']['current_file']));
    $foo-&gt;file = null;
  }

  ...
}


I traced the error back to the file_managed_file_validate function in modules/file/file.module but don't know anything about the file references.
The solution is to add a call to file_usage_add after the file is saved. This call adds a reference to the file in the database. The file_managed_file_validate function will spot the reference and won't trigger the error.

file_usage_add($file, 'foo', 'foo', $foo-&gt;id);


This isn't documented in the Form API under the managed_file example.

This issue is being discussed on the Drupal documentation issues: link