[SalesForce] Check if static resource exists in custom formula fields

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! 🙁

Best Answer

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">
    (function(document, window, undefined) {
        function showError(event) {
            var target = event.target || event.srcElement, error = document.createTextNode("Image not found");
        function onload() {
            var image = document.createElement("img");
            img.addEventListener("error", showError, true);
            img.src = "/resource/ProductImages/{!Product2.ProductCode}.jpg";
        window.addEventListener("load", onload, true);
    })(document, window);

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.