1

I'm trying to create a form using the Form API with the following behavior:

For a custom slider module, users can choose to upload an image which is saved as a managed file. This works fine. They also have the option to populate the slide content (slide title,link and image) from an existing node of a custom type. The node is selected from an auto-populated select field which on change calls an ajax function to auto-populate the title and subtitle fields. If the selected node has an image attached to it, a checkbox is displayed allowing the user to use the already uploaded image associated with node as the slider image as well. The problem I have is that I can't get the manged_file field to accept the nodes file id (fid) and re-render as managed_file with a default_value before returning it from the callback.

Here's my callback:

function load_image_callback($form,&$form_state) {
    // Load node from the selected value
    $node = node_load($form_state['values']['slide_nid'];

    // Set the managed_file default value to the nodes main image file
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#default_value'] = $node->field_main_image[$node->language][0]['fid'];

    // Return the updated slide image wrapper to replace the existing one
    return $form_state['complete form']['slide']['slide_image'];
}
1
  • if you've solved your question, you should post is as the answer and accept it so that it doesn't show as an unanswered question still Commented Feb 27, 2014 at 5:46

1 Answer 1

2

So after digging through Drupal core code I arrived at this solution:

In my ajax callback I load the actual file, set some managed file settings in the managed_file array, and then physically call the file_managed_file_process() function to setup the managed file display field array elements.

function load_image_callback($form,&$form_state) {
    // Load node from the selected value
    $node = node_load($form_state['values']['slide_nid'];
    $file = file_load($node->field_main_image[$node->language][0]['fid']);

    // Set the managed_file default value to the nodes main image file
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#value'] = array('fid' => $file->fid);
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#file'] = $file;

    // Process the managed file field with the set element
    $form_state['complete form']['slide']['slide_image']['slide_fid'] = file_managed_file_process($form_state['complete form']['slide']['slide_image']['slide_fid'], $form_state, $form);

    // Return the updated slide image wrapper to replace the existing one
    return $form_state['complete form']['slide']['slide_image'];
}

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.