Display uploaded image - Drupal 7 Form API

valen picture valen · Sep 25, 2013 · Viewed 8.8k times · Source

Here is my form field for users to upload their company logo:

$form['company_logo'] = array(
  '#type' => 'managed_file',
  '#title' => t('Company Logo'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#upload_location' => 'public://uploads/',
  '#default_value' => $row['companyLogo'],
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    'file_validate_size' => array(1024*1024*1024),
  ),

What I would like to do is have their logo displayed after they click "upload".

I'm surprised this isn't a simple option built in to the form API...how can one go about doing this?

Answer

D34dman picture D34dman · Sep 26, 2013

Declare a theme function

/**
 * Implements mymodule_thumb_upload theme callback.
 */
function theme_mymodule_thumb_upload($variables) {

    $element = $variables['element'];

    if (isset($element['#file']->uri)) {
        $output = '<div id="edit-logo-ajax-wrapper"><div class="form-item form-type-managed-file form-item-logo"><span class="file">';
        $output .= '<img height="50px" src="' . image_style_url('thumbnail', $element['#file']->uri) . '" />';
        $output .= '</span><input type="submit" id="edit-' . $element['#name'] . '-remove-button" name="' . $element['#name'] . '_remove_button" value="Remove" class="form-submit ajax-processed">';
        $output .= '<input type="hidden" name="' . $element['#name'] . '[fid]" value="' . $element['#file']->fid . '"></div></div>';
        return $output;
    }
}

Tell drupal that this theme function could be used to render an element.

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mymodule_thumb_upload' => array(
      'render element' => 'element',
    )
  );
}

Use '#theme' => 'mymodule_thumb_upload', to make managed file call a custom theme function for the element.

<?php
$form['company_logo'] = array(
  '#type' => 'managed_file',
  '#title' => t('Company Logo'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#upload_location' => 'public://uploads/',
  '#default_value' => $row['companyLogo'],
  '#theme' => 'mymodule_thumb_upload',
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    'file_validate_size' => array(1024*1024*1024),
  ),