Skip to main content
Dynamics 365 general forum
Answered

Prevent saving crm record using preventDefault is nor working

editSubscribe (0) ShareShare
ReportReport
Posted on by 115

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 ?

  • FikriHailal Profile Picture
    FikriHailal 115 on at
    RE: Prevent saving crm record using preventDefault is nor working

    Thanks for helping me :)

  • Verified answer
    Fubar Profile Picture
    Fubar 2,744 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
    Community Member UG Leader 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
    Fubar 2,744 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. 

Helpful resources

Quick Links

What Motivates a Super User?

We know many of you visit the Dynamics 365 Community and Power Platform…

Demystifying Copilot with Georg Glantschnig…

Industry experts answer burning questions directly from our amazing Community…

Setting Up Knowledge Sources for Copilot…

Look at how configuring a comprehensive knowledge base is crucial…

Leaderboard

#1
Andre Arnaud de Calavon Profile Picture

Andre Arnaud de Cal... 283,068 Super User

#2
Martin Dráb Profile Picture

Martin Dráb 222,591 Super User

#3
nmaenpaa Profile Picture

nmaenpaa 101,138

Product updates

Dynamics 365 release plans