Skip to navigation

How to Fix Image Preview in Joomla! Subforms

Written by and published on

When you use the media field in a Joomla! subform, the image preview stops working. Until it’s fixed in the core, here’s how you can fix it on a component level.

First, add an onchange event to the field:

<field name="my_image" type="media" onchange="updatePreview(this);" label="COM_MY_COMPONENT_LABEL_IMAGE" preview="true" />

Then add somewhere this small piece of JavaScript:

// "source" is the field element whose value is the image file
function updatePreview( source ) {
  if ( source.value !== "" ) {
    var preview = document.getElementById( source.id.replace( "_file", "_preview_img" ) );
    var previewEmpty = document.getElementById( source.id.replace( "_file", "_preview_empty" ) );
    if ( preview && previewEmpty ) {
      previewEmpty.style.display = "none";
      preview.src = source.value;
      preview.style.display = null;
    }
  }
}

And that’s it. The “clear image” button works ok, so we need to take action only when an image is selected.

Comments

Commenting has been disabled until I get a proper spam protection working. =(

External Links

Back to beginning