Friday, 12 August 2016

How to populate email record details from email template using JavaScript in Dynamics CRM

Recently, I had the requirement to open the email form on the click of a custom button on the opportunity form. The email form that opened needed to be pre-populated with the subject and body from an email template. There were some other values in the email record that needed to be populated from the opportunity record from which the email form was being opened. There was the option to make the SOAP request InstantiateTemplateRequest. 
However, as I had to embed the current opportunity record URL in the email message body (it cannot be added in the email template), along with some other values from the opportunity record in the email body, so I could not use the SOAP request. 

I decided to use JavaScript to populate the values in the email body (using my own placeholders).

Here is the email template:

Subject: This email with regards to the opportunity %OPPORTUNITY_TITLE%
Body:
Please click %OPPORTUNITY_URL% to view the opportunity.
Thanks,
Alpha business team


Here is the logic on click of the custom button on the opportunity form that opens the email form by reading the values from the above email template, replacing the placeholder values and opening the email form.

// get the email template details for the email template (Template): Body, Description, Subject, Title
    var type = "Template";
    var options = "$select=Body,Description,Subject,Title&$filter=Title eq '" + EmailTemplateTitle + "'";
    SDK.REST.retrieveMultipleRecords(type, options, function(successResponse) {
        if (successResponse != null && successResponse.length > 0) {
            var emailTemplateResponse = successResponse[0];
            if (emailTemplateResponse) {
                var emailBody = emailTemplateResponse.Body;
                var emailDesc = emailTemplateResponse.Description;
                var emailSubject = emailTemplateResponse.Subject;
                var emailTitle = emailTemplateResponse.Title;                      

                // populate the deal ID in the subject
                emailSubject = common.getCDataValue(emailSubject);              
                var dealReferenceAttr = Xrm.Page.getAttribute("new_dealnumber");
                if (dealReferenceAttr) {
                    var dealReferenceValue = dealReferenceAttr.getValue();
                    if (dealReferenceValue) {
                        emailSubject = emailSubject.replace("%OPPORTUNITY_TITLE%", dealReferenceValue);
                    } else {
                        emailSubject = emailSubject.replace("%OPPORTUNITY_TITLE%", "");
                    }
                }
             
                // populate the values in the deal body
                emailBody = common.getCDataValue(emailBody);                            
                var presentDealRecordId = Xrm.Page.data.entity.getId();
                var dealRecordUrl = "";
                if (presentDealRecordId) {
                    // remove the preceeding and trailing {} from the record ID
                    presentDealRecordId = presentDealRecordId.replace("{", "");
                    presentDealRecordId = presentDealRecordId.replace("}", "");
                    // returns value in this format: http(s)://server/org
                    var baseUrl = Xrm.Page.context.getClientUrl();
                    dealRecordUrl = baseUrl + "/main.aspx?etn=opportunity&pagetype=entityrecord&id=%7b" + presentDealRecordId + "%7d";
                    console.log("Deal record URL: " + dealRecordUrl);
                }
                emailBody = emailBody.replace("%OPPORTUNITY_URL%", "<a href =\"" + dealRecordUrl + "\"> Click here</a>");

                // populate the email record
                var parameters = {};
                console.log("The email subject is: " + emailSubject);
                parameters["subject"] = emailSubject;
                console.log("The email body is: " + emailBody);
                sessionStorage.setItem("dealEmailBody", emailBody);

                var dealLeaderAttr = Xrm.Page.getAttribute("ownerid");
                if (dealLeaderAttr) {
                    var dealLeader = dealLeaderAttr.getValue();
                    if (dealLeader) {
                        parameters["parameter_dealleaderid"] = dealLeader[0].id;
                        parameters["parameter_dealleadername"] = dealLeader[0].name;
                        parameters["parameter_dealleadertype"] = dealLeader[0].entityType;
                    }
                }
             
                parameters["parameter_regardingid"] = presentDealRecordId;
                parameters["parameter_regardingname"] = Xrm.Page.getAttribute("name").getValue();
                parameters["parameter_regardingtype"] = "opportunity";

                // open the email entity form
                Xrm.Utility.openEntityForm("email", null, parameters);
            }
        } else {
            console.log("No response received");
        }
        }, SDK.REST.errorCallback,
        function() { console.log("Retrieve Multiple call completed"); },
        );




I have highlighted the interesting parts in the code above. The first highlight indicates where you put the title of the email template to fetch the details.
The second is the portion where we extract the email subject/body from the XML (like) manner in which it is stored in the email template. The method definition is below where I get the value from within the CDATA section in the XML.

common.getCDataValue = function(text) {
    if (text) {
        var cDataStr = "CDATA[";
        var cDataStart = text.indexOf(cDataStr);
        if (cDataStart >= 0) {
            var cDataValue = text.substring(cDataStart + cDataStr.length);
            if (cDataValue) {
                var indexOfClosingBracket = cDataValue.indexOf("]]");
                if (indexOfClosingBracket >= 0) {
                    cDataValue = cDataValue.substring(0, indexOfClosingBracket);
                    return cDataValue;
                }
            }
        }
    }

    return null;
}



The third part shows storing the email body in HTML session storage. This is how the value is transmitted to the main email form. The other way to store as a form parameter has not been used as the email body can be rather large.

The fourth item shows how the values are stored in parameters to be passed to the email form (which has these parameters defined)

The below shows snippet from a method bound on the load of the email form that gathers the values from the parameters/sessionStorage and populates them in the email form:

// Get the Value of the Regarding through the Customer Parameters
            var param = Xrm.Page.context.getQueryStringParameters();
var dealLeaderId = param["parameter_dealleaderid"];
                var dealLeaderType = param["parameter_dealleadertype"];
                var dealLeaderName = param["parameter_dealleadername"];
                if (dealLeaderId && dealLeaderType && dealLeaderName) {
                    Xrm.Page.getAttribute("to").setValue([{ id: dealLeaderId, name: dealLeaderName, entityType: dealLeaderType }]);
                }

var dealNotificationEmailMessage = sessionStorage.getItem("dealEmailBody");
                if (dealNotificationEmailMessage) {
                    Xrm.Page.getAttribute("description").setValue(dealNotificationEmailMessage);
}


Hence, you get the email form popped out with all the relevant details from the email template and opportunity form!


Let me know your thoughts by commenting below. Happy Dynamics!!

No comments:

Post a Comment