0 out of 9 rated this helpful - Rate this topic

Xrm.Page.ui Control Methods

The control object provides methods to change the presentation of a control and identify the corresponding attribute.

Examples shown are in the Sample: SDK.ControlSamples.js library.

The following table lists the methods of control objects.

 

Method Description

addCustomView

Adds a new view for the lookup dialog.

Control Types: Lookup

addOption

Adds an option to an Option set control.

Control Types: Option Set

clearOptions

Clears all options from an Option Set control.

Control Types: Option Set

getAttribute

Returns the attribute that the control is bound to.

Control Types: Standard, Lookup, OptionSet

getControlType

Returns a value that categorizes controls.

Control Types: All

getData

Returns the value of the data query string parameter passed to a Silverlight Web resource.

For more information, see setData.

Control Types: Silverlight Web resources.

getDefaultView

Returns the ID value of the default lookup dialog view.

For more information, see setDefaultView.

Control Types: Lookup

getDisabled

Returns a value that indicates whether the control is disabled.

For more information, see setDisabled.

Control Types: All except SubGrid.

getLabel

Returns the label for the control

See also setLabel

Control Types: All

getName

Returns the name assigned to the control.

Control Types: All

getParent

Returns a reference to the section object that contains the control.

Control Types: All

getSrc

Returns the current URL being displayed in an IFRAME.

See also setSrc

Control Types: IFrame, Web Resource

getInitialUrl

Returns the default URL that an IFrame control is configured to display.

Control Types: IFrame

getObject

Returns the object in the form representing an IFrame or Web resource.

Control Types: IFrame, Web resource

getVisible

Returns a value that indicates whether the control is currently visible.

For more information, see setVisible.

Control Types: All

refresh

Refreshes the data displayed in a Sub-Grid

Control Types: SubGrid

removeOption

Removes an option from an Option Set control.

Control Types: Option Sets

setData

Sets the value of the data query string parameter passed to a Silverlight Web resource.

For more information, see getData.

Control Types: Silverlight Web resources.

setDefaultView

Sets the default view for the lookup control dialog.

For more information, see getDefaultView.

Control Types: Lookup

setDisabled

Sets a value that indicates whether the control is disabled.

See also getDisabled

Control Types: All except Web Resources and SubGrid.

setFocus

Sets the focus on the control.

Control Types: All

setLabel

Sets the label for the control.

For more information, see getLabel.

Control Types: All

setSrc

Sets the URL to be displayed in an IFrame.

See also getSrc

Control Types: IFrame and Web Resource

setVisible

Sets a value that indicates whether the control is visible.

For more information, see getVisible.

Control Types: All

addCustomView

Adds a new view for the lookup dialog.

controlObj.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, isDefault)
Arguments
viewId
String: The string representation of a GUID for a view.

noteNote
This value is never saved and only needs to be unique among the other available views for the lookup. A string for a non-valid GUID will work, for example “{00000000-0000-0000-0000-000000000001}”. It is recommended that you use a tool like guidgen.exe to generate a valid GUID. The guidgen.exe tool is included in the Windows SDK.

entityName
String: The name of the entity.

viewDisplayName
String: The name of the view.

fetchXml
String: The fetchXml query for the view.

layoutXml
String: The XML that defines the layout of the view.

isDefault
Boolean: Whether the view should be the default view.

Example:The SDK.ControlSamples.addCustomView function will add a new custom lookup called “SDK Sample View” to any lookup on the form that has a default view that shows account records.


   addCustomView: function ()
   {
       var viewId = "{C7034F4F-6F92-4DD7-BD9D-9B9C1E996380}";
       var entityName = "account";
       var viewDisplayName = "SDK Sample View";
       var fetchXml = "<fetch version='1.0' " +
                       "output-format='xml-platform' " +
                       "mapping='logical'>" +
                   "<entity name='account'>" +
                   "<attribute name='name' />" +
                   "<attribute name='address1_city' />" +
                   "<order attribute='name' " +
                           "descending='false' />" +
                   "<filter type='and'>" +
                       "<condition attribute='ownerid' " +
                                   "operator='eq-userid' />" +
                       "<condition attribute='statecode' " +
                                   "operator='eq' " +
                                   "value='0' />" +
                   "</filter>" +
                   "<attribute name='primarycontactid' />" +
                   "<attribute name='telephone1' />" +
                   "<attribute name='accountid' />" +
                   "<link-entity alias='accountprimarycontactidcontactcontactid' " +
                                   "name='contact' " +
                                   "from='contactid' " +
                                   "to='primarycontactid' " +
                                   "link-type='outer' " +
                                   "visible='false'>" +
                       "<attribute name='emailaddress1' />" +
                   "</link-entity>" +
                   "</entity>" +
               "</fetch>";

       var layoutXml = "<grid name='resultset' " +
                             "object='1' " +
                             "jump='name' " +
                             "select='1' " +
                             "icon='1' " +
                             "preview='1'>" +
                         "<row name='result' " +
                              "id='accountid'>" +
                           "<cell name='name' " +
                                 "width='300' />" +
                           "<cell name='telephone1' " +
                                 "width='100' />" +
                           "<cell name='address1_city' " +
                                 "width='100' />" +
                           "<cell name='primarycontactid' " +
                                 "width='150' />" +
                           "<cell name='accountprimarycontactidcontactcontactid.emailaddress1' " +
                                 "width='150' " +
                                 "disableSorting='1' />" +
                         "</row>" +
                       "</grid>";

       var lookupsModified = [];
       var lookupControls = Xrm.Page.ui.controls.get(SDK.ControlSamples.isLookup);

       for (var i in lookupControls)
       {
           SDK.ControlSamples.processLookup(lookupControls[i], viewId, entityName, viewDisplayName, fetchXml, layoutXml);
       }
   },

   processLookup: function (lookupControl, viewId, entityName, viewDisplayName, fetchXml, layoutXml)
   {
       // Get the default view of the lookup before it is modified
       var currentDefaultViewId = lookupControl.getDefaultView();
       var oReq = SDK.ControlSamples.getXMLHttpRequest();
       if (oReq != null)
       {
           var url = Xrm.Page.context.getServerUrl() +
"/XRMServices/2011/OrganizationData.svc/SavedQuerySet(guid'" + currentDefaultViewId + "')";

           oReq.url = url;
           oReq.open("GET", url, true);
           oReq.onreadystatechange = function ()
           {
               SDK.ControlSamples.changeLookupDefaultView(oReq, lookupControl, viewId, entityName, viewDisplayName, fetchXml, layoutXml);
           };

           oReq.send();
       }

   },

   isLookup: function (control, index)
   {
       return control.getControlType() == "lookup";
   },

   getXMLHttpRequest: function ()
   {
       if (window.XMLHttpRequest)
       {
           return new window.XMLHttpRequest;
       }
       else
       {
           try
       { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); }
           catch (ex)
           {
               return null;
           }
       }
   },

   changeLookupDefaultView: function (oReq, lookupControl, viewId, entityName, viewDisplayName, fetchXml, layoutXml)
   {
       if (oReq.readyState == 4 /* complete */)
       {
           if (oReq.status == 200)
           {
               xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
               xmlDoc.async = false;
               xmlDoc.loadXML(oReq.responseText);

               var returnedTypeCodeNode = xmlDoc.selectSingleNode("//d:ReturnedTypeCode");
               if (returnedTypeCodeNode)
               {
                   var entityName = returnedTypeCodeNode.text;
                   if (entityName == "account")
                   {
                       lookupControl.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, false);
                       lookupControl.setDefaultView(viewId);
                       alert("The lookup control for the '" + lookupControl.getName() +
                   "' attribute was updated with a new default view.\n\nThe new view id is '" +
                   lookupControl.getDefaultView() + "'.");
                   }
               }
           }
       }
   },

Go to top

addOption

Adds an option to an option set control.

controlObj.addOption(option, [index])
ImportantImportant
This method does not check that the values within the options you add are valid. You should only add options that have been defined for the specific option set control you are working with.

Arguments
option
Object: An option object to add to the OptionSet.

index
Number: (Optional) The index position to place the new option. If not provided the option will be added to the end.

Example:The SDK.ControlSamples.reverseOptions function reverses the order of all available options in the first option set control on the form.


reverseOptions: function ()
{

    var optionsetControl = Xrm.Page.ui.controls.get(SDK.ControlSamples.isOptionSet)[0];
    if (optionsetControl != null)
    {
        var options = optionsetControl.getAttribute().getOptions();

        // Reverse all of the options in the optionset.
        optionsetControl.clearOptions();
        for (var i = 1; i <= options.length; i++)
        {
            if (options[options.length - i].value != "null")
            {
                optionsetControl.addOption(options[options.length - i], i - 1);
            }


        }
        alert("The options for the " + optionsetControl.getLabel() + " field have been reversed.");
    }
    else
    { alert("There are no Option set controls in this form."); }


},

isOptionSet: function (control, index)
{
    return control.getControlType() == "optionset";
},

Go to top

clearOptions

Clears all options from an Option Set control.

controlObj.clearOptions()

Example: See the SDK.ControlSamples.reverseOptions function sample in addOption.

Go to top

getAttribute

Returns the attribute that the control is bound to.

controlObj.getAttribute()
noteNote
Controls that are not bound to an attribute do not have this method. They will return error number -2146823281 with the error message: “'getAttribute()' is null or not an object”.

Return Value
Type: Array

Example:See the SDK.ControlSamples.reverseOptions function sample in addOption.

Go to top

getControlType

Returns a value that categorizes controls.

controlObj.getControlType()
Return Value
Type: String

Possible return values of getControlType:

 

Return Value Description

standard

A Standard control.

iframe

An IFrame control

lookup

A Lookup control.

optionset

An OptionSet control

subgrid

A subgrid control

webresource

A Web resource control

Example: The SDK.ControlSamples.showControlTypes function will display a page in a new window showing the control type for every control on the form.


showControlTypes: function ()
{
    var html = "<html><head><title>Show Control Types</title>";
    html += "<style type=\"text/css\">body { font-family:Calibri;}";
    html += "table {border:1px solid gray; border-collapse:collapse;}";
    html += "th {text-align:left; border:1px solid gray;}";
    html += "td {border:1px solid gray;}</style>";
    html += "</head><body>";
    html += SDK.ControlSamples.getControlTypes();
    html += "</body></html>";
    var theWindow = window.open("", "_blank");
    theWindow.document.open();
    theWindow.document.write(html);
    theWindow.document.close();
},

getControlTypes: function ()
{
    var html = "<table><thead><th>Control Label</th><th>Attribute Type</th>" +
"<th>Attribute Format</th><th>Control Type</th></thead><tbody>";
    var controls = Xrm.Page.ui.controls.get();
    for (var i in controls)
    {
        var control = controls[i];
        var label = control.getLabel();

        if (label == null)
        {
            var attributeName;
            try
            {
                attributeName = control.getName();
                if (attributeName != "undefined")
                {
                    label = "attribute: " + attributeName;
                }
            }
            catch (e)
            {
                label = "Control is not bound to an attribute and does not have a label.";
            }
        }

        var attributeType;

        try
        {
            attributeType = control.getAttribute().getAttributeType();
        }
        catch (e)
        {
            attributeType = "No Attribute";
        }

        var attributeFormat;
        try
        {
            attributeFormat = control.getAttribute().getFormat();
        }
        catch (e)
        {
            attributeFormat = "No Attribute";
        }

        var controlType = control.getControlType();
        html += "<tr><td>" + label +
     "</td><td>" + attributeType +
     "</td><td>" + attributeFormat +
     "</td><td>" + controlType +
      "</td></tr>";
    }

    html += "</tbody></table>";
    return html;
},

Go to top

getData

Returns the value of the data query string parameter passed to a Silverlight Web resource.

controlObj.getData()
Return Value
Type: String

This method is only available for Silverlight Web resources. For Web page (HTML) web resources, the data parameter can be extracted from the getSrc method.

Go to top

getDefaultView

Returns the Id value of the default lookup dialog view.

controlObj.getDefaultView()
Return Value
Type: String

Example: See the SDK.ControlSamples.addCustomView function sample in addCustomView..

Go to top

getDisabled

Returns whether the control is disabled. This method is not available for Web resource controls.

controlObj.getDisabled()
Return Value
Type: Boolean

Example:The SDK.ControlSamples.toggleEnableControls function sets a value that indicates whether the control is disabled based on the results of the getDisabled method.


toggleEnableControls: function ()
{
    var controls = Xrm.Page.ui.controls.get();
    for (var i in controls)
    {
        var control = controls[i];
        if (control.getDisabled())
        {
            control.setDisabled(false);
        }
        else
        {
            control.setDisabled(true);
        }
    }
},

Go to top

getLabel

Returns the label for the control

controlObj.getLabel()
Return Value
Type:String

Example:The SDK.ControlSamples.toggleControlLabels function will show or hide a specified prefix for all control labels on the form.


toggleControlLabels: function (prefix)
{
    var controls = Xrm.Page.ui.controls.get();
    for (var i in controls)
    {
        var control = controls[i];
        var currentLabel = control.getLabel();
        if (currentLabel.substring(0, prefix.length) == prefix)
        {
            var newLabel = currentLabel.substring(prefix.length);
            control.setLabel(newLabel);
        }
        else
        {
            control.setLabel(prefix + currentLabel);
        }
    }
},

Go to top

getName

Returns the name assigned to the control.

noteNote
The name assigned to a control is not determined until the form loads. Changes to the form may change the name assigned to a given control.

controlObj.getName()
Return Value
Type: String

Example:See the SDK.ControlSamples.addCustomView function sample in addCustomView..

Go to top

getParent

Returns a reference to the section object that contains the control.

controlObj.getParent()
Return Value
Type: Object

Example: The SDK.ControlSamples.showControlParents function will display a page in a new window showing the section label values for controls on the page.


showControlParents: function ()
{
    var html = "<html><head><title>Show Control Parents</title>";
    html += "<style type=\"text/css\">body { font-family:Calibri;}";
    html += "table {border:1px solid gray; border-collapse:collapse;}";
    html += "th {text-align:left; border:1px solid gray;}";
    html += "td {border:1px solid gray;}</style>";
    html += "</head><body>";
    html += SDK.ControlSamples.getControlParents();
    html += "</body></html>";
    var theWindow = window.open("", "_blank");
    theWindow.document.open();
    theWindow.document.write(html);
    theWindow.document.close();
},

getControlParents: function ()
{
    var html = "<table><thead><th>Control Label</th><th>Section Label</th>" +
"</thead><tbody>";
    var controls = Xrm.Page.ui.controls.get();
    for (var i in controls)
    {
        var control = controls[i];

        var controlLabel = control.getLabel();
        var sectionLabel = control.getParent().getLabel();
        if (sectionLabel == null)
        {
            sectionLabel = "No Label";
        }

        html += "<tr><td>" + controlLabel +
     "</td><td>" + sectionLabel +
      "</td></tr>";
    }
    html += "</tbody></table>";
    return html;
},

Go to top

getSrc

Returns the current URL being displayed in an IFrame or Web resource.

IFrameControlObj.getSrc()
Return Value
Type: String

Example: The SDK.ControlsSamples.showIframeUrls function displays the URL for every I-frame on the form


showIframeUrls: function ()
{
    var controls = Xrm.Page.ui.controls.get(SDK.ControlSamples.isIframe);
    if (controls.length > 0)
    {
        var iframeUrls = [];
        for (var i in controls)
        {
            iframeUrls.push(controls[i].getSrc());
        }

        var message = "The iframes on the current form have the following urls:\n\n- " + iframeUrls.join("\n- ");
    }
    else
    {
        var message = "There are no iframe controls on the current form.";
    }

    alert(message);
},

isIframe: function (control, index)
{
    return control.getControlType() == "iframe";
},

Go to top

getInitialUrl

Returns the default URL that an I-frame control is configured to display. This method is not available for Web resources.

IFrameControlObj.getInitialUrl()
Return Value
Type: String

Example: The SDK.ControlSamples.redirectAllIframes function sets the src for every I-frame on the form to www.microsoft.com, and then alerts the user with the old and new URL.


redirectAllIframes: function ()
{
    var controls = Xrm.Page.ui.controls.get(SDK.ControlSamples.isIframe);
    if (controls.length > 0)
    {
        for (var i in controls)
        {
            var control = controls[i];

            var controlName = control.getName();

            var newUrl = "http://www.microsoft.com";
            control.setSrc(newUrl);

            var oldUrl = control.getInitialUrl();
            alert("The source of the iframe '" + controlName + "' has been changed from '" + oldUrl + "' to '" + newUrl + "'.");
        }
    }
    else
    {
        alert("There are no iframe controls on the current form.");
    }
},

Go to top

getObject

Returns the object in the form that represents an I-frame or Web resource.

controlObj.getObject()
Return Value
Type: Object

An I-frame will return the IFrame element from the Document Object Model (DOM).

A Web resource will return the Object element from the DOM that represents the embedded Silverlight plug-in.

Go to top

getVisible

Returns a value that indicates whether the control is currently visible.

noteNote
If the containing section or tab for this control is not visible, this method can still return true. To make certain that the control is actually visible, you need to also check the visibility of the containing elements.

controlObj.getVisible()
Return Value
Type: Boolean

Example: The SDK.ControlSamples.toggleVisibleControls function hides or reveals all controls on the form each time the event occurs.


toggleVisibleControls: function ()
{
    var controls = Xrm.Page.ui.controls.get();
    for (var i in controls)
    {
        var control = controls[i];
        if (control.getVisible())
        {
            control.setVisible(false);
        }
        else
        {
            control.setVisible(true);
        }
    }
},

Go to top

refresh

Refreshes the data displayed in a Sub-Grid

controlObj.refresh()

Example:The SDK.ControlSamples.refreshAllSubGrids function refreshes every sub-grid on the form.


refreshAllSubGrids: function ()
{
    var controls = Xrm.Page.ui.controls.get(SDK.ControlSamples.isSubGrid);

    if (controls.length > 0)
    {
        
        var subGridNames = "";
        for (var i in controls)
        {
            controls[i].refresh();
            subGridNames += (" - "+controls[i].getName() + "\n");
        }
        alert("The following subgrids were refreshed: \n" + subGridNames);
    }
    else
    {
        alert("There are no subgrid controls on the current form.");
    }
},

isSubGrid: function (control, index)
{
    return control.getControlType() == "subgrid";
},

Go to top

removeOption

Removes an option from an Option Set control.

controlObj.removeOption(value)
Arguments
Number: The value of the option you want to remove.

Example:The SDK.ControlSamples.removeLastOption function removes the last option from the first optionset control on the form.


removeLastOption: function ()
{
    var controls = Xrm.Page.ui.controls.get(SDK.ControlSamples.isOptionSet);
    if (controls.length > 0)
    {
        var firstOptionSet = controls[0];
        var options = firstOptionSet.getAttribute().getOptions();

        var lastOptionText = options[options.length - 1].text;
        var lastOptionValue = options[options.length - 1].value;
        firstOptionSet.removeOption(lastOptionValue);

        alert("The option '" + lastOptionText + "' has been removed from the '" + firstOptionSet.getName() + "' control.");
    }
    else
    {
        alert("There are no optionset controls on the current form.");
    }
},

isOptionSet: function (control, index)
{
    return control.getControlType() == "optionset";
},

Go to top

setData

Sets the value of the data query string parameter passed to a Silverlight Web resource.

controlObj.setData()
Arguments
Type: String

This method is only available for Silverlight Web resources. For Web Page (HTML) Web resources the data parameter can be set by using the setSrc method.

Go to top

setDefaultView

Sets the default view for the lookup control dialog.

controlObj.setDefaultView(viewGuid)
Arguments
Type: String

Example:See the SDK.ControlSamples.addCustomView function sample in addCustomView..

Go to top

setDisabled

Sets whether the control is disabled.

controlObj.setDisabled(bool)
Arguments
Boolean

Example:See the SDK.ControlSamples.toggleEnableControls function sample in getDisabled..

Go to top

setFocus

Sets the focus on the control.

controlObj.setFocus()

Example:The SDK.ControlSamples.SetFocusDemo function will open a new page containing a table with rows for each enabled and visible control corresponding to an attribute. Each row contains a button that will use the window.opener to access the Xrm.Page object to call the setFocus method for the control in the entity record form.


setFocusDemo: function ()
{
    var html = "<html><head><title>Set focus demo</title>";
    html += "<style type=\"text/css\">body { font-family:Calibri;}";
    html += "table {border:1px solid gray; border-collapse:collapse;}";
    html += "th {text-align:left; border:1px solid gray;}";
    html += "td {border:1px solid gray;}</style>";
    html += "<script type=\"text/jscript\" >";
    html += "function setFocus(name) { ";
    html += "window.opener.Xrm.Page.data.entity.attributes.get(name).controls.get(0).setFocus();";
    html += "}";
    html += "</script>";
    html += "</head><body>";
    html += SDK.ControlSamples.buildFocusDemoTable();
    html += "</body></html>";
    var theWindow = window.open("", "_blank");
    theWindow.document.open();
    theWindow.document.write(html);
    theWindow.document.close();
},

buildFocusDemoTable: function ()
{
    var html = "<table><thead><th>Control Label</th><th></th>" +
"</thead><tbody>";
    var attributes = Xrm.Page.data.entity.attributes.get();
    for (var i in attributes)
    {
        var control = attributes[i].controls.get(0);
        //setFocus will cause an error if used on a control that is 
        //disabled, not visible, or cannot accept focus.
        if (control != null && !control.getDisabled() && control.getVisible())
        {
            var controlLabel = attributes[i].controls.get(0).getLabel();
            var attributeName = attributes[i].getName();
            html += "<tr><td>" + controlLabel +
     "</td><td><input type=\"button\" onclick=\"setFocus('" + attributeName +
      "');\" value='Set Focus on " + controlLabel + "' /></td></tr>";
        }
    }
    html += "</tbody></table>";
    return html;
}

Go to top

setLabel

Sets the label for the control.

controlObj.setLabel(label)
Arguments
String

Example: See the SDK.ControlSamples.toggleControlLabels function sample in getLabel..

Go to top

setSrc

Sets the URL to be displayed in an IFrame or Web Resource

IFrameControlObj.setSrc()
Arguments
String

Example: See the SDK.ControlSamples.redirectAllIframes function sample in getInitialUrl.

Go to top

setVisible

Sets a value that indicates whether the control is visible.

controlObj.setVisible()
Arguments
Boolean

Example: See the SDK.ControlSamples.toggleVisibleControls function sample in getVisible.

noteNote
When you selectively show fields to users in code that runs in the Onload event, we recommend that you configure the fields to not be visible by default and then use setVisible(true) to show the fields when conditions are right. Using setVisible(false) to hide fields in the Onload event may result in the field briefly appearing to the user before being hidden.

If you are hiding a larger number of fields using setVisible(false), consider if you can group them together into tabs or sections and hide the tab or section rather than the fields separately. This will provide better performance.

Go to top

Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online
Send comments about this topic to Microsoft.
© 2012 Microsoft Corporation. All rights reserved.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
WORKAROUND: setFocus() does not work with the SubGrid control
Here is a workaround that can be used in the mean time: http://prodynamicscrm.com/blog/using-javascript-set-focus-subgrid-control
setFocus() does not work with the SubGrid control
The setFocus() method does not appear work for the SubGrid control type. Currently, there appears to be no method to set the focus to a SubGrid and have the Ribbon Toolbar behave accordingly.
Add an option to optionset

  If you need add an option value to a optionset you can use a Javascript object:

        var optionsetControl = Xrm.Page.ui.controls.get(<OptionSet Field Name>);
        optionsetControl.clearOptions();
        var newOptionValue = new Object();
        lsoOpt.value =1234567890;
        lsoOpt.text = 'Lorenzo Soncini - LSO Added';
        optionsetControl.addOption(lsoOpt);

make attention at the value : you need a valid integer value

LSo

This is true, however it is a best practice to simply manipulate the existing options. The existing options are the only valid options for the control. So before you remove an option using removeOption, copy the option object to a local variable. If you need to add it back, use addOption referencing that option object. This way you never need to define an option and risk potentially creating an invalid option.

-jdalysdk