Skip to main content

Notifications

Announcements

No record found.

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 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
    115 on at
    RE: Prevent saving crm record using preventDefault is nor working

    Thanks for helping me :)

  • Verified answer
    Fubar Profile Picture
    2,752 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,752 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

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 293,006 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,837 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156 Moderator

Leaderboard

Product updates

Dynamics 365 release plans