Thursday, April 7, 2011

CRM 2011 Javascript - attributes and controls

Based on an optionset (picklist) value I wanted to show or hide a field and make it required or not. Within CRM 4.0 I would write the script by heart. It would look something like this:

//CRM 4.0 Toggle field visible and required
if(crmForm.all.new_picklist.SelectedText == "value-A")
{
    crmForm.SetFieldReqLevel("new_showhidefield", 0);
    crmForm.all.new_showhidefield_c.style.display = 'none';
    crmForm.all.new_showhidefield_d.style.display = 'none';
}
else
{
    crmForm.SetFieldReqLevel("new_showhidefield", 1);
    crmForm.all.new_showhidefield_c.style.display = 'inline';
    crmForm.all.new_showhidefield_d.style.display = 'inline';
}

With the CRM 2011 Xrm.Page model, things have changed quite a lot. The Microsoft Dynamics CRM 2011 SDK describes the Xrm.Page Object Hierarchy. It shows there is a difference between the attributes (Xrm.Page.data.entity.attributes) and the controls (Xrm.Page.ui.controls). Trying to hide or show a field and make it required/not required made me realize that depending on functional requirements you have to figure out if you need to work with the attribute or the control (or both).

For example:
For making a field required, you need to work with the attribute
For making a field hidden, you need to work with the control

The SDK describes for both the methods supported:
Xrm.Page.data.entity attribute Methods
Xrm.Page.ui control Methods

So the CRM 2011 javascript for toggling a field visible/not visible and required or not required is this:

toggleLeadVisible = function()
{
    var Leadcontrol = Xrm.Page.ui.controls.get("new_leadid");
    var Leadattribute = Xrm.Page.data.entity.attributes.get("new_leadid");

    if(Xrm.Page.getAttribute("new_customertype").getText() == "Lead")
    {
        Leadcontrol.setVisible(true);
        Leadattribute.setRequiredLevel("required");
    }
    else
    {
        Leadcontrol.setVisible(false);
        Leadattribute.setRequiredLevel("none");
    }
}

It’s quite simple. Just know what you can do with attributes and what with controls!