Monday, June 4, 2012

Create your own SetMandatory function instead of using setRequiredLevel directly

It happens again and again that I am searching for SetMandatory in the SDK of MS CRM 2011. Yes, there is setRequiredLevel. But I never use the option of 'recommended' in my projects. I my opinion a field is mandatory or not mandatory. So therefore I have created the following function and put it in my global library:

var CRM_REQUIRED_LEVEL_NORMAL = "none";
var CRM_REQUIRED_LEVEL_RECOMMENDED = "recommended";
var CRM_REQUIRED_LEVEL_REQUIRED = "required";


function SetMandatory(vsFieldName, vbTrueFalse)
{
    try
    {
        if (Xrm.Page.getAttribute(vsFieldName) != null)
        {
            var loFieldName = Xrm.Page.getAttribute(vsFieldName);
            AddDebugMessage("Set mandatory field: '" + vsFieldName + "' to: " + vbTrueFalse.toString());

            if (vbTrueFalse)
            {
                loFieldName.setRequiredLevel(CRM_REQUIRED_LEVEL_REQUIRED);
            }
            else
            {
                loFieldName.setRequiredLevel(CRM_REQUIRED_LEVEL_NORMAL);
            }
        }
        else
        {
            throw ("The following field is not on the form: " + vsFieldName);
        }
    }
    catch (e)
    {
        CatchErrorMessage(e);
    }
}


To use the function simply call the function just created:
SetMandatory("yourfieldname", true);

Or to set the required Level to "normal":
SetMandatory("yourfieldname", false);

By the way AddDebugMessage is my little helper alert message function. It is called if a debug flag is set to true.

No comments:

Post a Comment