I am working with Drupal 7. When I use the following code, nothing shows up in the form; when I change managed_file with file, everything is fine.

$form['mfile'] = array (
  '#type' => 'managed_file',
  '#title' => t('File to upload'),
  '#size' => 22,'#upload_location' => 'public://vm-files',

Do you know why this happens?

2 Answers 2


You have to set the #default_value (as you would nearly any FAPI element) if you want the current set value to show up on the form when you visit the page. I have code such as the following in my module:

  for($i=1,$z=MAX_FRONTPAGE_IMAGES;$i<=$z;$i++) {
  $form["frontpage_image_fid_$i"] = array(
    '#type'            => 'managed_file',
    '#upload_location' => 'public://site_theme_assets/',
    '#default_value'   => variable_get("frontpage_image_fid_$i", ''),
    '#title'           => t("Random Image #$i for Frontpage"),
    '#description'     => t('This image will appear on the frontpage of the  site and have line1 and line2 on top of it.'),

The only gotcha I have when trying to use managed_file is that after save, on edit I get an error about the File status. That's because you should notify the file_usage table that your module owns/uses the file upon upload, eg:

/** callback for fapi admin settings page form that uses managed_file elements */
function foundation_frontpage_admin_submit($form, &$form_state) {
  for($i=1,$z=MAX_FRONTPAGE_IMAGES;$i<=$z;$i++) {
    if ($form_state['values']["frontpage_image_fid_$i"]) {
      $f = $form_state['values']["frontpage_image_fid_$i"];
      // Load the file via file.fid
      $file = file_load($f);
      // Change status to permanent.
      $file->status = FILE_STATUS_PERMANENT;
      // Save.

      // I was receiving an error on Edit of a filled out form/file upload.
      // Managed file: the file used in the field may not be referenced
      // The solution is file_usage_add() to this module as commented here.
      // http://drupal.stackexchange.com/a/4819/3279
      file_usage_add($file, 'foundation', 'variable:frontpage_image_fid_', $i, 1);

      variable_set("frontpage_image_fid_$i", $f);
    } else {
      variable_set("frontpage_image_fid_$i", NULL);
  drupal_set_message('Changes saved for frontpage.');

You must enable the File module, which is the one defining the managed_file form element. (See file_element_info().)

The module is a dependency for the Standard profile that comes with Drupal (see standard.info), which means it is enabled for that installation profile, but the Minimal profile doesn't enable it (see minimal.info), and there could be other installation profiles that don't enable it. If that is the case, using managed_file as form element doesn't make appear a form element.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.