I have a large form with a select field tied to an ajax call. When an option is selected a large chunk of the form is rebuilt and a number of fields re-populate.

All the fields pre-populate correctly except for the managed file field.

The managed file field appears to load the image correctly (the thumbnail appears), but on submitting the form, the field empties. It hasn't actually loaded the file.

(And because the managed file field is required it then throws a "managed file field is required error")

How should you correctly pre-populate a managed file on an ajax call?

Example Code (what I have so far)

The field_one_int pre-populates correctly works, field_two_managed_file is the problem.

function mymodule_form_alter(&$form, &$form_state, $form_id) {

   if($form_state['my_module_prepopulate'] == TRUE) {
      $form['field_one_int'][LANGUAGE_NONE]['#default_value'] = $form_state['values']['field_one_int'][LANGUAGE_NONE][0]['nid'];
        = $form_state['information']->field_two_managed_file[LANGUAGE_NONE][0]['fid'];
      $form['field_two_managed_file'][LANGUAGE_NONE][0]['#default_value']['display'] = TRUE;

   $form['ajax_field']['und']['#ajax'] = array (
      'callback' => 'module_ajax_function',
      'wrapper' => 'ajax-wrapper',
      'effect' => 'fade',

function module_ajax_function ($form, &$form_state) {

  $form_state['my_module_prepopulate'] = TRUE;


  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);


Other things ideas I've tried

I tried adding more information to mimic the array that exists in #default_value in a managed image file when a node is being edited. I loaded the file as an object converted it to array however this also doesn't work.

$ajax_logo = file_load($form_state['ajax_node']->field_company_logo[LANGUAGE_NONE][0]['fid']);
$form['field_company_logo'][LANGUAGE_NONE][0]['#default_value'] = get_object_vars($ajax_logo);

File object loaded

fid (String, 4 characters ) 2933
uid (String, 1 characters ) 1
filename (String, 12 characters ) photo1.jpg
uri (String, 39 characters ) public://photos/photo1.jpg
filemime (String, 10 characters ) image/jpeg
filesize (String, 5 characters ) 19700
status (String, 1 characters ) 1
timestamp (String, 10 characters ) 1421110296
alt (String, 0 characters )
title (String, 0 characters )
width (String, 3 characters ) 230
height (String, 3 characters ) 230


Your Answer

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

Browse other questions tagged or ask your own question.