Adding a theme attribute to managed_file field, remove button reloads the page in drupal 7 form

1.4k views Asked by At

I am using Drupal 7 for a form. In the form I have a managed_file field. When I add theme attribute to the managed_file field, the remove button reloads the page on removing the image. The upload works fine. Prior adding the theme attribute the remove button was working fine as well. Here is my managed_file field.

$form['profile_image'] = array(
    '#title' => t('Profile Image'),
    '#type' => 'managed_file',
    '#default_value' => profile_image['user']->field_profile_image['und']['0']['fid'],
    '#upload_location' => 'public://',
    '#theme' => 'module_upload_thumb_style',
);

Here is the theme function that I am using to style the uploaded image instead of showing just the name of the image.

function theme_module_upload_thumb_style($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 style="margin-left:20px;" type="submit" id="edit-' . $element['#name'] . '-remove-button" name="' . $element['#name'] . '_remove_button" value="Remove" class="btn btn-primary ajax-processed">';
        $output .= '<input type="hidden" name="' . $element['#name'] . '[fid]" value="' . $element['#file']->fid . '"></div></div>';
        return $output;
    }
}

When commenting the theme attribute in the form field, the remove button removes the image without refreshing the page. But on adding the theme attribute, the functionality remains the same but with page reload

1

There are 1 answers

0
AkiShankar On

After digging some more into the issue, I found a relevant solution to the problem. After updating the theme function to as below, the remove button works like a charm. Here is the updated function:

function theme_module_upload_thumb_style($variables) {
    $element = $variables['element'];
    $attributes = array();
    if (isset($element['#id'])) {
        $attributes['id'] = $element['#id'];
    }
    if (!empty($element['#attributes']['class'])) {
        $attributes['class'] = (array) $element['#attributes']['class'];
    }
    $attributes['class'][] = 'form-managed-file';
    $output = '';
    $output .= '<div' . drupal_attributes($attributes) . '>';
    if (isset($element['#file']->uri)) {
        $output .= '<img src="' . image_style_url('thumbnail', $element['#file']->uri) . '" />';
    }
    $output .= drupal_render_children($element);
    $output .= '</div>';
    return $output;
}