2

I have a custom formula field that shows an image using static resources. The resource to use is build using a field of the record:

IMAGE('/resource/ImagesProducts/'+ ProductCode +'.jpg' , 'MyImage' )

In this way I show the correct image of a product. But I haven't an image for each product. So I need to check in the formula that the resource

'/resource/ImagesProducts/'+ ProductCode +'.jpg'

exists. If true I want to show the image, otherwise I want to show a text such as 'No image found'.

Is there a way to achieve this? I've tried to use the IF formula, but I couldn't find a way to build the logical test. I've also checked the URLFOR function but it cannot be used in the formula fields! :(

1 Answer 1

2

You can't detect if a resource is available in a formula field. You would necessarily need client-side detection (Visualforce). You can embed Visualforce pages inside a page layout, so this wouldn't necessarily be very complex:

<apex:page standardController="Product2">
    <script>
    (function(document, window, undefined) {
        function showError(event) {
            var target = event.target || event.srcElement, error = document.createTextNode("Image not found");
            target.parentNode.appendChild(error);
            target.parentNode.remove(target);
        }
        function onload() {
            var image = document.createElement("img");
            img.addEventListener("error", showError, true);
            img.src = "/resource/ProductImages/{!Product2.ProductCode}.jpg";
            document.body.appendChild(img);
        }
        window.addEventListener("load", onload, true);
    })(document, window);
    </script>
</apex:page>

Here, we try to load the image, and on failure, we show an error in its place. Note this code does depend on addEventListener, which is supported by every browser supported by their appropriate vendors (e.g. not IE8). If you care for IE8 support, add code to detect window.attachEvent and modify appropriately.

2
  • Ok, thanks for the very detail response and for the code example. I hoped that it was possible to do this through formula field because I wanted to show that image in a listview. This means that I must build a custom visualforce listview to show the image or the text if the image isn't available.
    – lastYorsh
    May 26, 2014 at 16:05
  • Unfortunately so. You can either accept the "broken-image" icon, or use Visualforce, but you can't detect the presence of the file directly. IMHO, you'd be better off writing a custom image uploader (vs. static resources) and store the attachment/document ID on the product.
    – sfdcfox
    May 26, 2014 at 17:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .