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

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Answered

Prevent saving crm record using preventDefault is nor working

(0) ShareShare
ReportReport
Posted on by 121

I want to cancel saving process if the new_name is existing in the current entity.
Here's what i have tried:

function preventsave(context){
	var login_name = Xrm.Page.getAttribute("new_name").getValue();
	var Entity = "new_parentrecord";
	var Select = "?$select=new_name";
	var Filter = "&$filter=new_name eq '"  login_name  "'";
	 
	var saveEvent = context.getEventArgs();
//alert(login_name);
	Xrm.WebApi.retrieveMultipleRecords(Entity, Select   Filter).then(
		function success(result) {
			alert("Login Name Exist !!");
			if (result.entities[0].new_name !== null) {
				SetPageNotification("Login Name Exist !", "INFO", "InfoNotification");
				saveEvent.preventDefault(); //1st prevent
			}
		},
		function (error) {
			console.log(error.message);
		}
	);
	saveEvent.preventDefault(); //2nd prevent
}

function SetPageNotification(aMessage, aType, aNotificationName) {

       Xrm.Page.ui.setFormNotification(
         aMessage,
         aType,
         aNotificationName
       );
   }

function ClearAllNotifications() {
       ClearPageNotification("InfoNotification");
}

after trial and error i noticed that the 1st prevent is not working. but the 2nd prevent is working. Can you help me to make the 1st prevent to work ?

I have the same question (0)
  • FikriHailal Profile Picture
    121 on at
    RE: Prevent saving crm record using preventDefault is nor working

    Thanks for helping me :)

  • Verified answer
    Fubar Profile Picture
    2,756 on at
    RE: Prevent saving crm record using preventDefault is nor working

    Just played with await:

    async function savetest(ex){
    
    	await Xrm.WebApi.retrieveMultipleRecords("account", "?$select=name&$top=3").then(
        function success(result) {
            alert('alert 1');
    		for (var i = 0; i < result.entities.length; i  ) {
                console.log(result.entities[i]);
            }                    
        },
        function (error) {
            console.log(error.message);
        }
    );	
    	alert('alert 2');
    	
    }

    My form on save calls savetest

    alert 1 occurs before alert 2

    Edit: after a bit more trial an error I found that the await plays havoc with the preventDefault, it appears to make it work you would need a global variable, preventDefault prior to the await, inside the success set the global variable and then initiate a re-save - a little similar to some of the code here butenko.pro/.../

  • Verified answer
    Community Member Profile Picture
    on at
    RE: Prevent saving crm record using preventDefault is nor working

    Hi FikriHailal,

    As LA said, the 2nd prevent excute before 1st because that WebApi is by default asynchronous.

    So you can try to use synchronous odata to build request.

    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl()   "/api/data/v9.1/new_customs?$select=new_name&$filter=new_name eq 'A'", false);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function() {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
                for (var i = 0; i < results.value.length; i  ) {
                    var new_name = results.value[i]["new_name"];
                }
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();

    And the function that you need is check existing name, why not use duplicate detection, which is OOB function of the system.

    1.Enable Duplicate detection.

    Go Setting > Data management > Duplicate detection settings.

     4336.pastedimage1606721568905v4.png

    2.set Duplicate detection rule.

    Go Setting > Data management > Duplicate detection rules.

     7762.pastedimage1606721539177v3.png

    Save and publish it.

    3.Test.

    0317.pastedimage1606721355302v2.png

    You can refer following link to learn more about duplicate detection:

    https://rocketcrm.co.uk/dynamics-365-duplicate-detection-rules/

    Regards,

    Leah Ju

    Please mark as verified if the answer is helpful. Welcome to join hot discussions in Dynamics 365 Forums.

  • Verified answer
    Fubar Profile Picture
    2,756 on at
    RE: Prevent saving crm record using preventDefault is nor working

    WebApi is by default asynchronous as such the code will complete (or get to your last preventDefault) before  the success function has completed.

    Last time I had to do something similar we used oData with a synchronous call, but I believe I saw someone the other day suggest that you can a use a JavaScript 'await' as the WebApi uses promises. 

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…

Andrés Arias – Community Spotlight

We are honored to recognize Andrés Arias as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
DAnny3211 Profile Picture

DAnny3211 239

#2
Abhilash Warrier Profile Picture

Abhilash Warrier 139 Super User 2025 Season 2

#3
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 91 Super User 2025 Season 2

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans