To retrieve quote data (e.g., contact email) when creating an email from a quote in Dynamics 365, you can use JavaScript to pre-fill fields in the email form based on the data from the related quote. Here's a JavaScript code to achieve this:
Steps to Implement
1. Identify the Fields:
Ensure the quote has a field for the contact (e.g., contact or contactid) and custom fields with the required data.
Identify the relationship between the quote and the email (Regarding field typically links them).
2. JavaScript to Retrieve Data:
Use a JavaScript web resource to fetch data from the quote and populate the email form
3. Trigger the Script:
Attach the JavaScript to the OnLoad event of the Email form or a custom button in the ribbon.
JavaScript Code Example
function populateEmailFromQuote(executionContext) {
var formContext = executionContext.getFormContext();
var regardingId = formContext.getAttribute("regardingobjectid").getValue();
// Check if the regarding object is a quote
if (regardingId && regardingId[0].entityType === "quote") {
var quoteId = regardingId[0].id.replace(/[{}]/g, ""); // Remove curly braces
// Retrieve Quote Data via Web API
Xrm.WebApi.retrieveRecord("quote", quoteId, "?$select=contactid,_customfield1,_customfield2").then(
function (quote) {
// Set the 'To' email address with the contact email
if (quote["_contactid_value"]) {
Xrm.WebApi.retrieveRecord("contact", quote["_contactid_value"], "?$select=emailaddress1").then(
function (contact) {
if (contact.emailaddress1) {
var to = [{
entityType: "contact",
id: contact.contactid,
name: contact.fullname
}];
formContext.getAttribute("to").setValue(to);
}
},
function (error) {
console.error("Error retrieving contact: " + error.message);
}
);
}
// Set custom field values in the email body or subject
var emailBody = `Custom Field 1: ${quote._customfield1}\nCustom Field 2: ${quote._customfield2}`;
formContext.getAttribute("description").setValue(emailBody);
},
function (error) {
console.error("Error retrieving quote: " + error.message);
}
);
}
}
Explanation of the Code
1. Retrieve Quote Data:
The retrieveRecord method fetches the quote's contact and custom field values.
2. Retrieve Contact Email:
Once the contactid is retrieved from the quote, the script queries the contact to fetch its email address (emailaddress1).
3. Set the Email Fields:
The "To" field is set using the contact entity.
The email body or subject is updated with values from the quote's custom fields.