Requirement
A very common requirement I see many times where CE developer need to auto populate party list or other field on the email form at the time of create. This post will provide sample code which for the same.
Details
Let’s say we are working on the quote entity and when we will create email from quote entity using timeline it will look like below:
You can see in above by default Potential customer is added under 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 a 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 quote id from the regarding field. Further we can use retrieve method and bring required information using 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"];
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 above method onload of the form it will set invoice contact under to like below:
Summary
We saw how can use web api retrieve call to auto populate field on email form before it is sent.
Hope it will help someone !!
Keep learning and Keep Sharing !!