Dynamics 365: Implementing on-save confirmation dialog with Alert.js

By | October 21, 2017

We can make some fields required and we can make other fields optional.. But what about all those not so black-and-white situations where the system may still be able to warn the users about some possible inconsistency in the data, but the user should still be able to override that warning?

There are different options we can use to make this work, but one of them would be to display a warning message form the on-save.  That means we would need to do a few things:

  • Add an on-save handler
  • Display a warning message
  • Allow the user to click “ok” or “cancel” in that message
  • If the user clicks “ok”, we should still save the record
  • And we will likely need to disable autosave, at least in that particular OnSave handler

 

Here is what I ended up with:

image

And here is what I had to do to get it to work:

Step 1: Download alert.js and install the solution

First, I went to the  alert.js github page ( Alert.js ) and downloaded the solution from there:

image

Step 2: Add a web resource

Then, I’ve added the following script to a web resource:

var isConfirmed = false;
function onSave(executionObj)
{
  var eventArgs = executionObj.getEventArgs();
  if(eventArgs.getSaveMode() == 70)//AUTOSAVE
  {
    eventArgs.preventDefault();
    return;  
  }

  var condition = Xrm.Page.getAttribute("name").getValue() == "123";//If not “123”, display a confirmation 
  if(!condition && !isConfirmed)
  {
    eventArgs.preventDefault();
    Alert.show("This is not a 123 account", "Are you sure you want to save the changes?", [
         new Alert.Button("Save", confirmCallback, true),
         new Alert.Button("Cancel")  
         ], "WARNING");
  }
  else
  {
    isConfirmed = false;//Reset the flag for the next save
  }
}

function confirmCallback()
{
  isConfirmed = true;//to make sure we don't display alert dialog from onSave this time
  Xrm.Page.data.save(); 
}


Step 3: Add web resources to the form

After that, I’ve added my new web resource to the form together with the Alert.js web resource:

image

Step 4: Configure OnSave handler for the form

image

Step 5: Save, Publish All, and Run a test

image

That was quick and easy!

But I still wanted to clarify a couple of things

Alert.show call does not block javascript execution. That’s the reason there is a call back function there, and there is a call to Xrm.Page. data.save() from that callback.

And I needed that additional isConfirmed boolean variable so the script would not display the confirmation dialog every time.

Happy 365-ing!

Leave a Reply

Your email address will not be published. Required fields are marked *