Change Case Image Based on Case Type

Change Case Image Based on Case Type


In Microsoft Dynamics 365, enhancing the user interface and user experience can often involve customizing forms and entities. One such customization is dynamically updating the entity images based on certain conditions. In this blog post, we'll walk through the process of updating case entity images dynamically based on the "Case Type" using JavaScript and FetchXML.


Prerequisites

Before diving into the code, ensure you have the following:

  • Basic knowledge of JavaScript and Dynamics 365.
  • Access to a Dynamics 365 instance with appropriate permissions.
  • Web resources (images) uploaded to Dynamics 365.

Step 1: Setting Up the Web Resources

First, ensure that the images you want to use are uploaded as web resources in Dynamics 365. For this example, let's assume we have three images named aqc_bmw.png, aqc_chatgpt.png, and aqc_starbucks.png.


Step 2: Writing the JavaScript Code

We will create a JavaScript web resource that includes functions to:

  1. Retrieve the appropriate web resource based on the case type.
  2. Update the case entity's image.

var CaseImageUpdater = {

   
    OnAttributeChange_updateCaseImage: function (executionContext) {
        var formContext = executionContext.getFormContext();
        var caseId = formContext.data.entity.getId();
        var caseTypeCode = formContext.getAttribute("aqc_casetype").getValue();

        switch (caseTypeCode) {
            case 11:
                this.UpdateCaseImage(caseId, "bmw");
                break;
            case 22:
                this.UpdateCaseImage(caseId, "chatgpt");
                break;
            case 33:
                this.UpdateCaseImage(caseId, "starbucks");
                break;
            default:
                console.error("Unhandled case type code: " + caseTypeCode);
                break;
        }
    },

    UpdateCaseImage: function (caseId, webResourceName) {
        this.GetImageWebResource(caseId, webResourceName, this.UpdateCaseRecord);
    },

    GetImageWebResource: function (caseId, imageName, successCallback) {
        var fetchXml = [
            "<fetch top='1'>",
            "  <entity name='webresource'>",
            "    <attribute name='name'/>",
            "    <attribute name='content'/>",
            "    <filter>",
            "      <condition attribute='displayname' operator='eq' value='", imageName , "'/>",
            "    </filter>",
            "  </entity>",
            "</fetch>"
        ].join("");

        console.log("Fetching Web Resource with FetchXML: " + fetchXml);

        Xrm.WebApi.retrieveMultipleRecords("webresource", "?fetchXml=" + encodeURIComponent(fetchXml)).then(
            function success(result) {
                if (result.entities.length > 0) {
                    console.log("Web Resource found: ", result.entities[0]);
                    successCallback(caseId, result.entities[0]);
                } else {
                    var errorMsg1 = "GetImageWebResource Error: cannot retrieve image with name = " + imageName + ".";
                    Xrm.Navigation.openAlertDialog({ text: errorMsg1 });
                    console.error(errorMsg1);
                }
            },
            function error(error) {
                var errorMsg1 = "GetImageWebResource Error: " + error.message;
                Xrm.Navigation.openAlertDialog({ text: errorMsg1 });
                console.error(errorMsg1);
            }
        );
    },

    UpdateCaseRecord: function (caseId, webResource) {
        if (!webResource || !webResource.content) {
            console.error("WebResource not found or content is empty.");
            Xrm.Navigation.openAlertDialog({ text: "WebResource not found or content is empty." });
            return;
        }

        var caseIncident = {
            "entityimage": webResource.content // Base64 content of the web resource
        };

        var oDataURI = Xrm.Utility.getGlobalContext().getClientUrl() +
            "/api/data/v9.0/incidents(" + caseId.replace("{", "").replace("}", "") + ")";

        console.log("Updating Case Record with URI: " + oDataURI);

        var req = new XMLHttpRequest();
        req.open("PATCH", encodeURI(oDataURI), true);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 204 || this.status === 1223) {
                    console.log("Case image updated successfully.");
                } else {
                    var errorMsg2 = "UpdateCaseRecord Error: Cannot update case record with ID = " + caseId + ".";
                    Xrm.Navigation.openAlertDialog({ text: errorMsg2 });
                    console.error(errorMsg2);
                }
            }
        };
        req.send(JSON.stringify(caseIncident));
    }
};

// Wrapper function to call OnAttributeChange_updateCaseImage
function onFormLoad(executionContext) {
    CaseImageUpdater.OnAttributeChange_updateCaseImage(executionContext);
}

0 Comments

Thanks for commenting. Your comment will be live soon after approval.