Auto Populate Email Fields using JavaScript

Requirement

A very common requirement I see many times is where CE developers need to auto-populate a party list or another field on the email form at the time of creation. This post will provide a sample code for the same.

Details

Let’s say we are working on the quote entity and when we will create an email from the quote entity using the timeline, it will look like the below.

Quote entity

You can see in above by default Potential customer is added under the To partly list (Party-list is a special type of lookup where we can select multiple entities) so now let’s say in the Quote entity we have another field called Invoice Contact and when we are creating email for the quote we want to set that contact under To field. For this we need to get data from the quote entity and we can get the quote id from the regarding field. Further, we can use the retrieve method and bring the required information using the below code.

function SetToOnLoad(executionContext) {
    // Set form context
    var formContext = executionContext.getFormContext();

    // Get the Regarding field (regardingobjectid)
    var regardingField = formContext.getAttribute("regardingobjectid").getValue();

    // Run this code only for the quote
    if (regardingField && regardingField[0].entityType === "quote") {
        var quoteId = regardingField[0].id.replace(/[{}]/g, ""); // Remove {}

        // Retrieve the Quote record, we can add fields what we need
        Xrm.WebApi.retrieveRecord("quote", quoteId, "?$select=_him_invoicecontact_value").then(
            function (quote) {
                // Check if the invoice contact exists on the quote
                if (quote._him_invoicecontact_value) {
                    var contactId = quote._him_invoicecontact_value;
                    var contactName = quote["_him_invoicecontact_value@OData.Community.Display.V1.FormattedValue"];

                    // Set the "to" field with the retrieved contact
                    formContext.getAttribute("to").setValue([
                        {
                            id: contactId,
                            name: contactName,
                            entityType: "contact",
                        }
                    ]);
                } else {
                    console.log("No invoice contact associated with this quote.");
                }
            },
            function (error) {
                console.error("Error retrieving quote record: " + error.message);
            }
        );
    } else {
        console.log("Regarding is not a quote or is missing.");
    }
}

After calling the above method onload of the form, it will set invoice contact under to like below.

EmailTo

Summary

We saw how can use web api retrieve calls to auto-populate fields on the email form before it is sent.

Hope it will help someone!

Keep learning and Keep Sharing!

HIMBAP
We are expert in Microsoft Power Platform.