You've already received a comprehensive solution for this scenario in our previous conversation. To reiterate the key points and provide a concise answer based on that discussion:
The issue you're facing is due to the asynchronous nature of the ExecutionContext.data.entity.save() method. The Xrm.navigate.openForm() is likely being called before the save operation has completed.
Here's the corrected approach using getIsDirty() and Promises to ensure the save operation finishes before navigation:
function onButtonClick(executionContext) {
var formContext = executionContext.getFormContext();
if (formContext.data.entity.getIsDirty()) {
formContext.data.entity.save().then(
function successCallback(saveResult) {
var abcid = formContext.data.entity.getId();
var xyz = formContext.getAttribute("crm-xyz").getValue();
var formParameters = {};
if (abcid) {
formParameters["relatedRecordId"] = abcid;
formParameters["relatedRecordType"] = formContext.data.entity.getEntityName();
}
if (xyz) {
formParameters["new_xyzField"] = xyz; // Replace with actual schema name
}
var options = {
entityLogicalName: "your_new_entity_logical_name", // Replace with actual logical name
parameters: formParameters
};
Xrm.Navigation.openForm(options);
},
function errorCallback(error) {
console.log("Error during save: " + error.message);
// Handle error appropriately
}
);
} else {
var abcid = formContext.data.entity.getId();
var xyz = formContext.getAttribute("crm-xyz").getValue();
var formParameters = {};
if (abcid) {
formParameters["relatedRecordId"] = abcid;
formParameters["relatedRecordType"] = formContext.data.entity.getEntityName();
}
if (xyz) {
formParameters["new_xyzField"] = xyz; // Replace with actual schema name
}
var options = {
entityLogicalName: "your_new_entity_logical_name", // Replace with actual logical name
parameters: formParameters
};
Xrm.Navigation.openForm(options);
}
}
Key Changes:
formContext: Using the recommended formContext.
formContext.data.entity.getIsDirty(): Checks for unsaved changes.
- Asynchronous
save() with .then(): The Xrm.Navigation.openForm() is called within the successCallback function, ensuring it executes after the save operation completes successfully.
- Error Handling: Includes an
errorCallback for the save() operation.
Xrm.Navigation.openForm(): Using the modern navigation API.
- Passing Values: Demonstrates how to pass values to the new form using the
parameters option.
Remember to replace the placeholder values ("your_new_entity_logical_name" and "new_xyzField") with the actual schema names relevant to your environment. This approach guarantees that the form is saved before navigation, resolving the inconsistent behavior you were observing.