Dynamically setting field requirement levels in Microsoft Dynamics CRM

In Dynamics CRM you may have a field you want to be required some of the time, but not required, or maybe not even enabled, the rest of the time. In this post I'll show you how to dynamically enable/disable and set/unset the required attribute of CRM form fields using JavaScript.

Let's say you have a delivery restaurant that sells pizza and wings. You could store the order attributes in CRM on a custom DeliveryOrder entity. You could have a picklist to represent the order type, pizza or wings, and you could store the pizza toppings in a text field. If the order type is pizza, you want to require something be entered in the toppings field. If the order type is wings, you don't want to even allow an entry in the toppings field.

First, create the entity attributes. We'll call the picklist lucas_ordertype, and we'll call the text field lucas_toppings. The picklist values for lucas_ordertype are Pizza and Wings, and it is a business required field. When you create the lucas_toppings field, don't change the default requirement attribute.

Once you've added the fields to your CRM form, you'll need to add some JavaScript to enable or disable the toppings field and set its requirement level appropriately. Here's script that does it:

//get a references to our picklist object  
var oOrderType = crmForm.all.lucas_ordertype;  
  
//default toppings field as disabled, not required  
crmForm.all.lucas_toppings.Disabled = true;  
crmForm.SetFieldReqLevel("lucas_toppings", false);  
  
//if order type is pizza, enable and require toppings field  
if(oOrderType.SelectedText=="Pizza")  
{  
crmForm.all.lucas_toppings.Disabled = false;  
crmForm.SetFieldReqLevel("lucas_toppings", true);  
}

Add this script to the form's onLoad event and the lucas_ordertype field's onChange event, and you're set. Now you'll get the information you need without unduly inconveniencing your users.

comments powered by Disqus