web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

getisdirty

(2) ShareShare
ReportReport
Posted on by 5,514
Hi currently I have a button where on click of it a new form is opening .
Before opening a new form ..current form details should save and after navigating few values should be copied in new form ..
 
 
ExecutionContext.data.entity.save();
Const abcid= executionContext.data.entity.getId();
Const xyz= executionContext.getAttribute("crm-xyz").get value();
Xrm.navigate.open form();
 
How can I add getIsDirty() in this above code as now form is sometimes behaving weirdly(stays in same page or sometimes it ask to save again)
 
Note: requirement is to save a form and open new form..
Categories:
I have the same question (0)
  • sandeepc Profile Picture
    5,514 on at
    AAny suggestions will be marked as verified
  • Suggested answer
    Daivat Vartak (v-9davar) Profile Picture
    7,835 Super User 2025 Season 2 on at
    Hello sandeepc,
     

    You're right, the behavior you're experiencing (staying on the same page or asking to save again) likely occurs because the Xrm.navigate.openForm() is being called before the save operation initiated by ExecutionContext.data.entity.save() has actually completed. The save() method is asynchronous.

    Here's how you can correctly incorporate getIsDirty() and ensure the form is saved before navigating, along with copying values to the new form:

    function onButtonClick(executionContext) {
        var formContext = executionContext.getFormContext();
        // Check if the form has unsaved changes
        if (formContext.data.entity.getIsDirty()) {
            // Save the form and then navigate
            formContext.data.entity.save().then(
                function successCallback(saveResult) {
                    // Form saved successfully, now navigate and pass values
                    var abcid = formContext.data.entity.getId();
                    var xyz = formContext.getAttribute("crm-xyz").getValue();
                    var formParameters = {};
                    if (abcid) {
                        formParameters["relatedRecordId"] = abcid; // Example: Passing the current record ID
                        formParameters["relatedRecordType"] = formContext.data.entity.getEntityName(); // Example: Passing the current entity logical name
                    }
                    if (xyz) {
                        formParameters["new_xyzField"] = xyz; // Example: Passing the value of 'crm-xyz' to a field in the new form
                    }
                    var options = {
                        entityLogicalName: "your_new_entity_logical_name", // Replace with the logical name of the entity for the new form
                        // Optional: Specify form parameters to pre-populate fields in the new form
                        parameters: formParameters
                    };
                    Xrm.Navigation.openForm(options);
                },
                function errorCallback(error) {
                    console.log("Error during save: " + error.message);
                    // Optionally display an error message to the user
                }
            );
        } else {
            // Form is not dirty, navigate immediately
            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;
            }
            var options = {
                entityLogicalName: "your_new_entity_logical_name", // Replace with the logical name of the entity for the new form
                parameters: formParameters
            };
            Xrm.Navigation.openForm(options);
        }
    }

     

    Explanation of Changes:

    1. formContext: We get the formContext object, which is the recommended way to interact with the form in modern Dynamics 365.

    2. formContext.data.entity.getIsDirty(): This method checks if there are any unsaved changes on the current form.

    3. Conditional Save:

      • If getIsDirty() is true:

        • We call formContext.data.entity.save(). This returns a Promise.

        • We use .then() to execute code after the save operation has completed successfully.

          • successCallback: Inside this function, we get the abcid and xyz values and then use Xrm.Navigation.openForm() to open the new form.

          • Passing Values: We use the parameters option of Xrm.Navigation.openForm() to pass values to the new form.

            • relatedRecordId: An example of passing the ID of the current record.

            • relatedRecordType: An example of passing the logical name of the current entity.

            • new_xyzField: Replace "new_xyzField" with the actual schema name of the field in your new form where you want to copy the value of xyz. 
             

        • We also include an .catch() (or the second argument to .then(), errorCallback) to handle potential errors during the save operation. 

      • If getIsDirty() is false:

        • We directly proceed to get the values and open the new form using Xrm.Navigation.openForm().

        •  
          

    4.  

    Important Considerations:

    • Xrm.Navigation.openForm(): Make sure you are using Xrm.Navigation.openForm() (with a capital 'N') for modern Dynamics 365 development. Xrm.navigate.openForm() is the older syntax.

    • your_new_entity_logical_name: Replace this placeholder with the actual logical name of the entity for the form you want to open. You can find this in the entity customization settings.

    • new_xyzField: Crucially, replace "new_xyzField" with the correct schema name of the field in the new form where you want to copy the value of xyz.

    • Error Handling: The errorCallback in the save().then() should include appropriate error logging or user feedback to handle cases where the save operation fails.

    • Asynchronous Nature: Remember that save() is asynchronous. The .then() block ensures that the navigation and value passing happen only after the save is successful.

    •  

    By implementing this approach, you ensure that the current form's details are saved (if there were changes) before the new form is opened, preventing the issues you were encountering. You also correctly pass the desired values to the new form using the parameters option of Xrm.Navigation.openForm().

     
    If my answer was helpful, please click Like, and if it solved your problem, please mark it as verified to help other community members find more. If you have further questions, please feel free to contact me.
     
    My response was crafted with AI assistance and tailored to provide detailed and actionable guidance for your Microsoft Dynamics 365 query.
     
    Regards,
    Daivat Vartak
  • Verified answer
    Lagortinez Profile Picture
    10 on at

    Hi there!

    There is a very simple way to set this up — you can use a function called entity.getIsDirty that is inside the formContext. You can combine this with formContext.data.save to check if your form has unsaved changes, and if that's the case, force a form save before leaving the form.

    This helps avoid the annoying popups that inform the user of unsaved changes.

    I will post below 3 options for you:


    • Two of them are functions (async and sync)

    • and the last one is a sync way without using a function, so you can simply copy the lines into your code. (But I would recommend you start getting familiar with functions 😉 — they will make your code cleaner and reusable!)

     


     

    🚀 Async Approach:

    async function saveIfDirty(formContext) {
        if (formContext.data.entity.getIsDirty()) {
            console.log("Saving form...");
            try {
                await formContext.data.save();
                console.log("Form saved successfully.");
            } catch (error) {
                console.error("Error saving the form:", error);
            }
        } else {
            console.log("Form is not dirty. No save needed.");
        }
    }

    You would need to call this function from an async event handler.

     
     

    ⚡ Sync Approach:

    function saveIfDirty(formContext) {
        if (formContext.data.entity.getIsDirty()) {
            console.log("Saving form...");
            formContext.data.save()
                .then(function() {
                    console.log("Form saved successfully.");
                })
                .catch(function(error) {
                    console.error("Error saving the form:", error);
                });
        } else {
            console.log("Form is not dirty. No save needed.");
        }
    }

    This works if your event or calling context is not async.

     
     

    ✂️ Quick Copy-Paste (without wrapping in a function):

     
    if (formContext.data.entity.getIsDirty()) {
        console.log("Saving form...");
        formContext.data.save()
            .then(function() {
                console.log("Form saved successfully.");
            })
            .catch(function(error) {
                console.error("Error saving the form:", error);
            });
    } else {
        console.log("Form is not dirty. No save needed.");
    }

    This way you can just paste it directly where you need it, but again — try to lean towards functions as your projects grow! 🚀

     

    Merging the third option with the example code you provided, it would look like this:

     

    ExecutionContext.data.entity.save();
    Const abcid= executionContext.data.entity.getId();
    Const xyz= executionContext.getAttribute("crm-xyz").get value();
    let formContext = ExecutionContext;
    if (formContext.data.entity.getIsDirty()) {
        console.log("Saving form...");
        formContext.data.save()
            .then(function() {
                console.log("Form saved successfully.");
                // Line below opens your form only in case of success. Keep that in mind!
                Xrm.navigate.open form();
            })
            .catch(function(error) {
                console.error("Error saving the form:", error);
            });
    } else {
        console.log("Form is not dirty. No save needed.");
    }

    I placed in red the new code that you would need to add, and in green the code you provided on your example. 


    Hope this helps you set up your save logic and make your user experience much smoother! If you found my awnser helpful, mark it as verified awnser, and like it in case it helped!

    See ya next time!

    José Martínez Lago

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 83 Super User 2025 Season 2

#2
Gerardo Rentería García Profile Picture

Gerardo Rentería Ga... 49 Most Valuable Professional

#3
#ManoVerse Profile Picture

#ManoVerse 40

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans