Skip to main content

Notifications

Community site session details

Community site session details

Session Id :
Power Apps - Power Apps Pro Dev & ISV
Answered

How to prevent save event when validation required database call?

(0) ShareShare
ReportReport
Posted on by 306

I have a form in my model-driven app (9.0) that has an Amount field.  When saving the form, I need to do a lookup on the database for the user's Limit amount.  If the Amount exceeds their Limit, I need to prevent the save from happening.  I'm using 

Xrm.WebApi.retrieveRecord to make the database call, which is asynchronous.  So by the time I get the value back from the DB, the save has already happened.  Any ideas on how I can accomplish this?
 
Here's my javascript code that's wired to the OnSave event:
 
function CheckUserLimit(executionContext) {
    var formContext = executionContext.getFormContext();
    var globalContext = Xrm.Utility.getGlobalContext();

    var userId = globalContext.userSettings.userId.slice(1, -1);
    var enteredAmount = formContext.getAttribute("amount").getValue();

    Xrm.WebApi.retrieveRecord("systemuser"userId"?$select=userlimit").then(
        function success(result) {
            var userLimitresult.userlimit;
            if (enteredAmount > userLimit) {
                var alertStrings = { confirmButtonLabel: "OK"text: "The amount exceeds your user limit."title: "Limit Exceeded" };
                Xrm.Navigation.openAlertDialog(alertStrings);
                // Prevent the Save
                executionContext.getEventArgs().preventDefault();
            }
        },
        function (error) {
            var alertStrings = { confirmButtonLabel: "OK"text: "Error retrieving system user limit: " + error.messagetitle: "Error Encountered" };
            Xrm.Navigation.openAlertDialog(alertStrings);
        }
    );
}
  • Community Power Platform Member Profile Picture
    on at
    Re: How to prevent save event when validation required database call?

    If you're having issues with "prevent default" like I was, I liked the simplicity of setting notifications on fields:

    if(remaining < 0) {
    
     formContext.getControl("rsf_type").setNotification('Cannot enter a PTO request. No remaining balance.');
    
     } else {
    
     formContext.getControl("rsf_type").clearNotification();
    
     }
  • Verified answer
    tschopp Profile Picture
    306 on at
    Re: How to prevent save event when validation required database call?

    Your ideas are good ones.  Thank you.  They led me to my solution which is to get the user limit value in the OnLoad event for the form and save it in a global JS variable.  Then, in OnSave, I can make the comparison without need to make the async retrieveRecord call.

  • Verified answer
    Diana Birkelbach Profile Picture
    3,072 Most Valuable Professional on at
    Re: How to prevent save event when validation required database call?

    Hi @tschopp , 

     

    Since the callback added with addOnSave doesn't work with promises, the only way you can go is stopping the Saving while it waits for the promise, as @a33ik 's Blog shows.

    In my experience, this might cause some issues when the standard functionality is calling the formContext.data.save, since this promise will always get rejected, and the promise.then will never be executed (even if the save is restarted after the async request, the original promise gets rejected). Some examples of issues are the BusinessProcessFlows or some standard ribbon buttons.

    The sdk recommends to implement the saving validation using a PlugIn, in case the data is not on the form. This doesn't work good in some cases where you have to react to it and show the user some choices, but it seems to me that in your case a PreValidate PlugIn might be a good choice.

    Hope it helps.

    Kind regards,

    Diana
    ----------
    Please click "Accept as Solution" if my post answered your question so that others may find it more quickly. If you found this post helpful consider giving it a "Thumbs Up."

  • Verified answer
    a33ik Profile Picture
    3,304 Most Valuable Professional on at
    Re: How to prevent save event when validation required database call?

    Hello,

    You can check my post that describes scenario that is pretty similar to yours - https://butenko.pro/2018/11/15/cancelling-save-based-on-the-result-of-async-operation/

  • magesoe Profile Picture
    80 on at
    Re: How to prevent save event when validation required database call?

    Both the onsave event and the retrieve call supports promises. So if you make your onsave function async and await your retrieve call you can treat the retrieve call as synchronous.

     

    So the code would look like 

    async function OnSave(){

    ....

    var response = await Xrm.WebApi.retrieve(..)

    ...

    }

     

    Learn more about async await here https://javascript.info/async-await

     

    Also consider using typescript instead, makes it easier to maintain the code

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

🌸 Community Spring Festival 2025 Challenge Winners! 🌸

Congratulations to all our community participants!

Warren Belz – Community Spotlight

We are honored to recognize Warren Belz as our May 2025 Community…

Congratulations to the April Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard > Power Apps - Power Apps Pro Dev & ISV

#1
WarrenBelz Profile Picture

WarrenBelz 69 Most Valuable Professional

#2
mmbr1606 Profile Picture

mmbr1606 51 Super User 2025 Season 1

#3
Michael E. Gernaey Profile Picture

Michael E. Gernaey 35 Super User 2025 Season 1

Overall leaderboard