Tag: Make All fields Mandatory/Optional On Form Using Javascript

Make All fields Mandatory/Optional On Form Using Javascript

This should be a very quick blog on JavaScript helper which will let you make all fields on the form mandatory or optional. This requirement is hypothetical; I have not received any till now.

I am going to be calling below function on OnLoad event of the form based on a field value but you can very well call is on OnSave of record, or OnChange event of field.

For Dynamics CRM below v9:

function SetRequiredLevel()    
{
  var attributes = Xrm.Page.data.entity.attributes.get();
    for (var i in attributes) {
        attributes[i].setRequiredLevel("required");
    }
}

For Dynamics CRM v9 or above use below and make sure pass the context as first parameter ( checkbox) on the form editor while calling the function.

function SetRequiredLevel(executionContext)    
{
  var context = executionContext.getFormContext();
  var attributes =  context.data.entity.attributes.get();
    for (var i in attributes) {
        attributes[i].setRequiredLevel("required");
    }
}

1

 

1. If you need to check some value you can do that i.e.

If ( fieldAValue = 1)

{
//the above code goes here//

}

2. If you have to make fields optional rather then mandatory , do this:
setRequiredLevel(“none“);

I hope this helps!!