Prevent double click of a CRM button

Often times, we come across a situation where we need to prevent a double click on the button in order for the request NOT to be submitted twice.

Suppose you are creating/updating (or any other relevant operation) a record on click of a button (through JS) on one of the entity records, and you do not want the records to be created/updated twice if you or the end user happen to click the button a second time by accident.

One way of implementing this, is through JS and configurations on the form.

Create a 'Two Option' field type and hide (visible by default is unchecked) it on the form and write the following script on the click of the button.

So, when the button is clicked for the first time, the JS fires and sets the field value to true. Now, on the second click, the JS checks if the field has already set to true. If true, the control is returned or an alert is generated.

var buttonClicked = Xrm.Page.data.entity.attributes.get('new_twoOptionsField')
    if (buttonClicked != null) {
        if (buttonClicked .getValue() === true){
           //alert("Button clicked twice");
            return;
       }
        else {
            buttonClicked .setValue(true);
            buttonClicked .setSubmitMode("never");
        }
    }

The setSubmitMode here is important (depends on your business requirements) if you want to prevent the page to popup the 'Changes to the page' alert. The setSubmitMode("never") doesn't pass the changes made to the hidden field to the 'OnSave' event. If you want to save the changes made to the field, set setSubitMode to 'always' i.e. setSubmitMode("always").

Comments