Make All Form Fields As Read-Only With Webresource In Dynamics CRM

Introduction

During certain scenarios, we must make all CRM form fields as read-only. To achieve this functionality explicit logic should be written using JavaScript with form controls that are available on the form. Contact form was used to show this functionality.

Step 1

Login to the required environment and select required solution [Contact Customizations Solution in this case] as shown in the below figure.

Make All Form Fields as Readonly with Webresource in Dynamics CRM Figure1

Step 2

After Step 1, select contact web resource in solution and click on Edit as shown in the below figure.

Make All Form Fields as Readonly with Webresource in Dynamics CRM Figure2

Step 3

After Step 2, use below code to get all form controls present on a form

‘use strict’;
var formControls = formContext.getControl();

Step 4

After Step 3, loop through formControls variable and make each control as readonly by using setDisabled property as true by using below code

formControls.forEach(control => {
    control.setDisabled(true);
});

Step 5

After Step 4, include code present in Step 3 and Step 4 inside a function and below is the code

function disableformcontrols(executionContext) {
    'use strict';
    let formContext = executionContext.getFormContext();
    if (formContext !== null && formContext != 'undefined') {
        var formControls = formContext.getControl();
        formControls.forEach(control => {
            control.setDisabled(true);
        });
    }
}

Step 6

After Step 5, call function from respective event in this case from handleOnLoad function and the final code looks like below

if (typeof(ContosoVaccination) == "undefined") {
    var ContosoVaccination = {
        __namespace: true
    };
}
if (typeof(ContosoVaccination.Scripts) == "undefined") {
    ContosoVaccination.Scripts = {
        __namespace: true
    };
}
ContosoVaccination.Scripts.ContactForm = {
    handleOnLoad: function(executionContext) {
        console.log('on load - contact form');
        disableformcontrols(executionContext);
    },
    __namespace: true
}

function disableformcontrols(executionContext) {
    'use strict';
    let formContext = executionContext.getFormContext();
    if (formContext !== null && formContext != 'undefined') {
        var formControls = formContext.getControl();
        formControls.forEach(control => {
            control.setDisabled(true);
        });
    }
}

Step 7

After Step 6, save function and update Webresource with this file and publish it on the contact form and open any contact and observe all fields as readonly as shown in the below figure

Make All Form Fields as Readonly with Webresource in Dynamics CRM Figure7

Note
Make sure to publish all customizations and upload JavaScript (js) file.

Conclusion

In this way, one can easily make all fields present on a CRM form as readonly with javascript as webresource.


Similar Articles