Κοινή χρήση μέσω


Xrm.Page.ui control (client-side reference)

 

Applies To: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

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

You access controls using the following collections: Xrm.Page.ui.controls, Xrm.Page.ui Section.controls, or Xrm.Page.data.entity Attribute.controls. The Xrm.Page.getControl method is a shortcut method to access Xrm.Page.ui.controls.get.

The syntax examples in this topic show the use of the Xrm.Page.getControl method to access a control. Which control depends on the arguments passed to the method. The args parameter to access a single control must be either the name of the control or the index.

When a form displays a business process flow control in the header, additional controls will be added for each attribute that is displayed in the business process flow. These controls have a unique name similar to the following example: header_process_<attribute name>.

Note

Only controls in the active stage of the business process flow can be accessed by name this way.

Controls displayed in the form header are accessible and have a unique name like the following: header_<attribute name>.

For controls that are bound to attributes it is common to access controls through the Xrm.Page.data.entity Attribute.controls collection.

The custom controls for Dynamics 365 mobile clients (phones and tablets) supports all the control properties and methods except the following: Auto-completion methods, getValue, Keypress methods and Lookup control methods and events.

With Microsoft Dynamics CRM Online 2016 Update 1 and Microsoft Dynamics CRM 2016 Service Pack 1 (on-premises) release, the following methods are now supported for the timer control on the new form rendering engine (also called "turbo forms"): getControlType, getName, getParent, Label methods, refresh, and Visible methods.

Control properties and methods

  • Auto-completion methods
    Configure the auto-completion experience in text controls in Dynamics 365 forms. These methods were introduced in Dynamics 365.

  • Disabled
    Detect the state and enable or disable controls using the getDisabled and setDisabled methods.

  • getAttribute
    Get the attribute that the control is bound to.

  • getControlType
    Get information about the type of control.

  • getName
    Get the name of the control

  • getParent
    Get the section object that the control is in.

  • getValue
    Gets the latest value for a control as users type a character in a specific text or number field. This method was introduced in Dynamics 365.

  • Keypress methods
    Add, remove, or perform a function when the user presses a key in a control. These methods were introduced in Dynamics 365.

  • Knowledge base control methods
    These methods are only available for the knowledge base search control in a Dynamics 365 instance that has the knowledge management feature enabled.

    For information about this control, see Knowledge base search control (client-side reference).

  • Label
    Get or change the label for a control using the getLabel and setLabel methods.

  • Lookup control methods and events
    Control the results displayed for a user to choose from when they set the value of a lookup control using the addCustomFilter, addCustomView, getDefaultView, setDefaultView methods.

    You can add or remove event handlers for the PreSearch event using the addPreSearch and removePreSearch methods.

  • Notification
    Display and remove notifications to users about a control using the setNotification, addNotification and clearNotification methods.

  • OptionSet control methods
    Modify the options displayed in OptionSet controls using the addOption, clearOptions, and removeOption methods.

  • ShowTime
    Use setShowTime to specify whether a date control should show the time portion of the date and getShowTime to determine whether the time portion of the date is currently displayed.

  • Subgrid control methods
    For organizations using CRM Online 2015 Update 1 there are new capabilities to work with sub-grid controls. More information: Grid (read-only) objects and methods (client-side reference)

    For other organizations, the refresh method is the only unique method available for subgrid controls. This method will refresh the data displayed in the subgrid.

  • Visible
    Determine which controls are visible and show or hide them using the getVisible and setVisible methods.

  • Web resource and IFRAME control methods
    Interact with web resource and IFRAME controls using the getData, setData, getInitialUrl, getObject, setSrc and getSrc methods.

Auto-completion methods

Use the showAutoComplete and hideAutoComplete methods to configure the auto-completion experience in text controls in forms.

For a sample JavaScript code that demonstrates the auto-completion feature, see Sample: Auto-complete in Dynamics 365 controls

Note

These methods aren’t supported for Dynamics 365 mobile clients (phones or tablets) and the interactive service hub. These methods are only available for Updated entities.

showAutoComplete

Use this to show up to 10 matching strings in a drop-down list as users press keys to type character in a specific text field. You can also add a custom command with an icon at the bottom of the drop-down list. On selecting an item in the drop-down list, the value in the text field changes to the selected item, the drop-down list disappears, and the OnChange event for the text field is invoked.

Xrm.Page.getControl(arg).showAutoComplete(object)
  • Parameter
    Type: Object that defines the result set, which includes results and commands, to be displayed in the auto-completion drop-down list.

    Remarks: Call this method in a function that you added using the addOnKeyPress method to execute on the keypress event.

    Example: The following example shows the definition of the object to be passed to the showAutoComplete method.

    var resultset = { 
       results: [{ 
             id: <value1>, 
             icon: <url>, 
             fields: [<fieldValue1>]}, 
    
             {...}, 
    
             { 
             id: <valueN>, 
             icon: <url>, 
             fields: [<fieldValue1, fieldValue2,..., fieldValueN>]}],
       commands:{ 
             id: <value>, 
             icon: <url>, 
             label: <value>, 
             action: <function reference> 
       } 
    }
    

hideAutoComplete

Use this function to hide the auto-completion drop-down list you configured for a specific text field.

Xrm.Page.getControl(arg).hideAutoComplete()

Note

You don’t have to explicitly use the hideAutoComplete method because, by default, the drop-down list hides automatically if the user clicks elsewhere or if a new drop-down list is displayed. This function is available in case developers need to explicitly hide the auto-completion drop-down list to handle a custom scenario.

Disabled

Use getDisabled and setDisabled to detect whether a control is disabled or to enable or disable it.

Control Types: standard, lookup, optionset.

getDisabled

Returns whether the control is disabled.

Xrm.Page.getControl(arg).getDisabled()
  • Return Value
    Type: Boolean. True if the control is disabled, otherwise false.

setDisabled

Sets whether the control is disabled.

Xrm.Page.getControl(arg).setDisabled(bool)
  • Arguments
    Type: Boolean. True if the control should be disabled, otherwise false.

getAttribute

Returns the attribute that the control is bound to.

Control Types: standard, lookup, optionset.

Xrm.Page.getControl(arg).getAttribute()

Note

Controls that aren’t bound to an attribute (subgrid, web resource, and IFRAME) don’t have this method. An error will be thrown if you attempt to use this method on one of these controls.

  • Return Value
    Type: Object: An attribute.

Remarks

The constituent controls within a quick view control are included in the controls collection and these controls have the getAttribute method. However, the attribute is not part of the attribute collection for the entity. While you can retrieve the value for that attribute using getValue and even change the value using setValue, changes you make will not be saved with the entity.

The following code shows using the value the contact mobilephone attribute when displayed on an account entity form using a quick view control named contactQuickForm. This code hides the control when the value of the attribute is null.

var quickViewMobilePhoneControl = Xrm.Page.getControl("contactQuickForm_contactQuickForm_contact_mobilephone");
 if (quickViewMobilePhoneControl.getAttribute().getValue() == null)
 {
  quickViewMobilePhoneControl.setVisible(false);
 }

getControlType

Returns a value that categorizes controls.

Control Types: all.

Xrm.Page.getControl(arg).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 option set control.

    subgrid

    A subgrid control.

    webresource

    A web resource control.

    notes

    A notes control.

    timercontrol

    A timer control.

    kbsearch

    A knowledge base search control.

    customcontrol: <namespace>.<name>

    A custom control for Dynamics 365 mobile clients (phones and tablets).

    customsubgrid:<namespace>.<name>

    A custom dataset control for Dynamics 365 mobile clients (phones and tablets).

getName

Returns the name assigned to the control.

Note

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.

Control Types: all.

Xrm.Page.getControl(arg).getName()
  • Return Value
    Type: String. The name of the control.

getParent

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

Control Types: all.

Xrm.Page.getControl(arg).getParent()

getValue

Gets the latest value in a control as the user types characters in a specific text or number field. This method helps you to build interactive experiences by validating data and alerting users as they type characters in a control.

The getValue method is different from the attribute getValue method because the control method retrieves the value from the control as the user is typing in the control as opposed to the attribute getValue method that retrieves the value after the user commits (saves) the field.

Note

This method isn’t supported for the Dynamics 365 mobile clients (phones or tablets), and is only available for Updated entities.

For a sample JavaScript code that uses the getValue method to configure the auto-completion experience, see Sample: Auto-complete in Dynamics 365 controls.

Xrm.Page.getControl(arg).getValue()
  • Return Value
    Type: String. The latest data value for a control.

Keypress methods

Use addOnKeyPress, removeOnKeyPress, and fireOnKeyPress methods to provide immediate feedback or take actions as user types in a control. These methods enable you to perform data validations in a control even before the user commits (saves) the value in a form.

Note

These methods aren’t supported for the Dynamics 365 mobile clients (phones or tablets), and are only available for Updated entities.

addOnKeyPress

Use this to add a function as an event handler for the keypress event so that the function is called when you type a character in the specific text or number field.

For a sample JavaScript code that uses the addOnKeyPress method to configure the auto-completion experience, see Sample: Auto-complete in Dynamics 365 controls.

Xrm.Page.getControl(arg).addOnKeyPress([function reference])
  • Parameter
    Type: function reference

    Remarks: The function will be added to the bottom of the event handler pipeline. The execution context is automatically set to be passed as the first parameter passed to event handler set using this method. More information: Execution context (client-side reference)

    You should use reference to a named function rather than an anonymous function if you may later want to remove the event handler for the field.

removeOnKeyPress

Use this to remove an event handler for a text or number field that you added using addOnKeyPress.

Xrm.Page.getControl(arg).removeOnKeyPress([function reference])
  • Parameter
    Type: function reference

    Remarks: If an anonymous function is set using addOnKeyPress, it can’t be removed using this method.

fireOnKeyPress

Use this to manually fire an event handler that you created for a specific text or number field to be executed on the keypress event.

Xrm.Page.getControl(arg).fireOnKeyPress()

Knowledge base control methods

These methods are only available for the knowledge base search control, which is available when the Dynamics 365 organization is enabled for the knowledge management feature. For information about these controls, see Knowledge base search control (client-side reference).

Label

Get or change the label for a control using the getLabel and setLabel methods.

Control Types: all.

getLabel

Returns the label for the control.

Xrm.Page.getControl(arg).getLabel()
  • Return Value
    Type: String. The label of the control.

setLabel

Sets the label for the control.

Xrm.Page.getControl(arg).setLabel(label)
  • Arguments
    Type: String. The new label for the control.

Lookup control methods and events

Control the results displayed for a user to choose from when they set the value of a lookup control using the addCustomFilter, addCustomView, getDefaultView, and setDefaultView methods. The Lookup control also exposes the PreSearch event so that you can programmatically add event handlers using the addPreSearch and removePreSearch methods.

Control Types: lookup.

addCustomFilter

Use to add filters to the results displayed in the lookup. Each filter will be combined with any previously added filters as an “AND” condition.

Xrm.Page.getControl(arg).addCustomFilter(filter, entityLogicaName)
  • Arguments

    • filterXml
      Type: String: The fetchXml filter element to apply. For example:

      <filter type="and">
       <condition attribute="address1_city" operator="eq" value="Redmond" />
      </filter>
      
    • entityLogicalName
      Type: String: (Optional) If this is set, the filter only applies to that entity type. Otherwise, it applies to all types of entities returned.

  • Remarks
    More information: FetchXML schema.

    This method is only available for Updated entities.

    This method can only be used in a function in an event handler for the Lookup Control PreSearch event.

    The following code sample is for the Opportunity form Account (parentaccountid) lookup. When the Sdk.setParentAccountIdFilter function is set in the form Onload event handler, the Sdk.filterCustomAccounts function is added to the PreSearch event for that lookup. The result is that only accounts with the Category (accountcategorycode) value of Preferred Customer (1) will be returned.

    var Sdk = window.Sdk || {};
    
    Sdk.filterCustomerAccounts = function () {
        //Only show accounts with the type 'Preferred Customer'
        var customerAccountFilter = "<filter type='and'><condition attribute='accountcategorycode' operator='eq' value='1'/></filter>";
        Xrm.Page.getControl("parentaccountid").addCustomFilter(customerAccountFilter, "account");
    }
    //set 'Sdk.setParentAccountIdFilter' in the Opportunity form onload event handler
    Sdk.setParentAccountIdFilter = function () {
        Xrm.Page.getControl("parentaccountid").addPreSearch(Sdk.filterCustomerAccounts);
    }
    

addCustomView

Adds a new view for the lookup dialog box.

Xrm.Page.getControl(arg).addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, isDefault)
  • Arguments

    • viewId
      Type:String: The string representation of a GUID for a view.

      Note

      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’s 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
      Type: String: The name of the entity.

    • viewDisplayName
      Type: String: The name of the view.

    • fetchXml
      String: The fetchXml query for the view.

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

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

  • Remarks
    This method doesn’t work with Owner lookups. Owner lookups are used to assign user-owned records.

DefaultView

You can detect which view is the default view that’s shown to allow users to select records in a lookup and change the default view using getDefaultView and setDefaultView.

getDefaultView

Returns the ID value of the default lookup dialog view.

Xrm.Page.getControl(arg).getDefaultView()
  • Return Value
    Type: String. The ID value of the default view.

setDefaultView

Sets the default view for the lookup control dialog box.

Xrm.Page.getControl(arg).setDefaultView(viewGuid)
  • Arguments
    Type: String. The ID of the view to be set as the default view.

Example: This setDefaultViewSample function will set the account entity form primary contact lookup default view to the My Active Contacts view.

function setDefaultViewSample() {
    Xrm.Page.getControl("primarycontactid").setDefaultView("{00000000-0000-0000-00AA-000010001003}");
}​

PreSearch event

You can add or remove event handlers for the Lookup Control PreSearch event using the addPreSearch and removePreSearch methods.

Use the PreSearch event to control what results are displayed for the control using the form data current as the user is beginning to search for records.

Both methods have the Execution context (client-side reference) passed as the first parameter.

addPreSearch

Use this method to apply changes to lookups based on values current just as the user is about to view results for the lookup.

Xrm.Page.getControl(arg).addPreSearch(handler)
  • Arguments
    Type: Function to add.

  • Remarks
    This method is only available for Updated entities.

The argument is a function that will be run just before the search to provide results for a lookup occurs. You can use this handler to call one of the other lookup control functions and improve the results to be displayed in the lookup.

removePreSearch

Use this method to remove event handler functions that have previously been set for the PreSearch event.

Xrm.Page.getControl(arg).removePreSearch(handler)
  • Arguments
    Type: Function to remove.

  • Remarks
    This method is only available for Updated entities.

Notification

Use these methods to display and clear notifications for a control.

setNotification

Displays an error message for the control to indicate that data isn’t valid. When this method is used,  a red "X" icon appears next to the control. On Dynamics 365 mobile clients, tapping on the icon will display the message.

Xrm.Page.getControl(arg).setNotification(message,uniqueId)

Remarks

Setting an error notification on a control will block the form from saving.

This method is only available for Updated entities.

Arguments

  • message
    Type: String: The message to display.

  • uniqueId
    Type: String: The ID to use to clear just this message when using clearNotification. Optional.

Return Value

Type: Boolean: Indicates whether the method succeeded.

addNotification

Displays an error or recommendation notification for a control, and lets you specify actions to execute based on the notification. When you specify an error type of notification, a red "X" icon appears next to the control. When you specify a recommendation type of notification, an "i" icon appears next to the control. On Dynamics 365 mobile clients, tapping on the icon will display the message, and let you perform the configured action by clicking the Apply button or dismiss the message.

Xrm.Page.getControl(arg).addNotification(object)

Remarks

Setting an error notification on a control blocks saving the form; setting a recommendation notification does not block saving the form.

This method was introduced in December 2016 update for Dynamics 365 (online and on-premises), and is only available for Updated entities.

Arguments

The method accepts an object with the following attributes:

Attribute

Data Type

Required

Description

messages

Array

Yes

The message to display in the notification. In the current release, only the first message specified in this array will be displayed. The string that you specify here appears as bold text in the notification, and is typically used for title or subject of the notification. You should limit your message to 50 characters for optimal user experience.

notificationLevel

String

No

Defines the type of notification. Valid values are ERROR or RECOMMENDATION. If you do not specify this attribute in your object definition, it is set to ERROR by default.

uniqueId

String

No

The ID to use to clear this notification when using clearNotification.

actions

Array of objects

No

A collection of objects with the following attributes:

  • message: String. The secondary or body message of the notification to be displayed to the user. Limit your message to 100 characters for optimal user experience.

  • actions: Array. The corresponding actions for the message.

In the current release, only single body message and corresponding action are supported. However, you can define multiple tasks to be performed using JavaScript code in the actions block.

Note

The addNotification method displays a notification with the messages you specified and two standard buttons: Apply and Dismiss. Clicking Apply executes the action you define; clicking Dismiss closes the notification message.

Return Value

Type: Boolean: Indicates whether the method succeeded.

Example

The following sample code displays a notification on the Account Name field of the account form to set the Ticker Symbol if the Account Name field contains "Microsoft". Clicking Apply in the notification will set the Ticker Symbol field to "MSFT".

function addTickerSymbolRecommendation() {
    var myControl = Xrm.Page.getControl('name');
    var accountName = Xrm.Page.data.entity.attributes.get('name');
    var tickerSymbol = Xrm.Page.data.entity.attributes.get('tickersymbol');

    if (accountName.getValue('Microsoft') && tickerSymbol.getValue() != 'MSFT') {
        var actionCollection = {
            message: 'Set the Ticker Symbol to MSFT?',
            actions: null
        };

        actionCollection.actions = [function () {
            tickerSymbol.setValue('MSFT');
            myControl.clearNotification('my_unique_id');
        }];

        myControl.addNotification({
            messages: ['Set Ticker Symbol'],
            notificationLevel: 'RECOMMENDATION',
            uniqueId: 'my_unique_id',
            actions: [actionCollection]
        });
    }
    else
        console.log("Notification not set");
}

clearNotification

Remove a message already displayed for a control.

Xrm.Page.getControl(arg).clearNotification(uniqueId)

Arguments

  • uniqueId
    Type: String: The ID to use to clear a specific message that was set using setNotification or addNotification.

    If the uniqueId parameter isn’t specified, the current notification shown will be removed.

Remarks

This method is only available for Updated entities.

Return Value

Type: Boolean: Indicates whether the method succeeded.

OptionSet control methods

Use the addOption, clearOptions, and removeOption methods to manipulate options available for OptionSet controls.

addOption

Adds an option to an option set control.

Xrm.Page.getControl(arg).addOption(option, [index])

Important

This method doesn’t check that the values in the options you add are valid. If you add invalid options they will not work correctly. You must only add options that have been defined for the specific option set attribute that the control is bound to. Use the attribute getOptions or getOption methods to get valid option objects to add using this method.

  • Arguments

    • option
      Type: Object: An option object to add to the OptionSet.

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

clearOptions

Clears all options from an option set control.

Xrm.Page.getControl(arg).clearOptions()

removeOption

Removes an option from an option set control.

Xrm.Page.getControl(arg).removeOption(number)
  • Arguments
    Type: Number: The value of the option you want to remove.

setFocus

Sets the focus on the control.

Xrm.Page.getControl(arg).setFocus()

ShowTime

Use setShowTime to specify whether a date control should show the time portion of the date and use getShowTime to determine whether the time portion of the date is currently displayed.

getShowTime

Get whether a date control shows the time portion of the date.

Control Types: standard control for datetime attributes.

var showsTime = Xrm.Page.getControl(arg).getShowTime();

Remarks

This method was introduced with Microsoft Dynamics CRM Online 2015 Update 1.

setShowTime

Specify whether a date control should show the time portion of the date.

Control Types: standard control for datetime attributes.

Xrm.Page.getControl(arg).setShowTime(bool)

Remarks

This method is only available for Updated entities. This method will show or hide the time component of a date control where the attribute uses the DateAndTime format. This method will have no effect when the DateOnly format is used.

Subgrid control methods

For releases prior to Microsoft Dynamics CRM Online 2015 Update 1 the only method available for a subgrid control is refresh. With CRM Online 2015 Update 1 there are new capabilities you can use. More information: Grid (read-only) objects and methods (client-side reference)

refresh

Refreshes the data displayed in a subgrid.

Xrm.Page.getControl(arg).refresh()

Note

The refresh method isn’t available in the form OnLoad event because subgrids load asynchronously. With the subgrid OnLoad event introduced in CRM Online 2015 Update 1 you can now detect when the subgrid is loaded and use this method with event handlers for that event.

Visible

Determine which controls are visible and show or hide them using the getVisible and setVisible methods.

getVisible

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

Note

If the containing section or tab for this control isn’t 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.

Xrm.Page.getControl(arg).getVisible()
  • Return Value
    Type: Boolean. True if the control is visible; otherwise, false.

setVisible

Sets a value that indicates whether the control is visible.

Xrm.Page.getControl(arg).setVisible(bool)
  • Arguments
    Type: Boolean. True if the control should be visible; otherwise, false.

Note

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’re 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 can improve performance.

Web resource and IFRAME control methods

Use these methods to interact with web resource and IFRAME controls.

Data

Web resources have a special query string parameter named data to pass custom data. The getData and setData methods only work for Silverlight web resources added to a form. More information: Passing data from a form to an embedded Silverlight web resource

For web page (HTML) web resources, the data parameter can be extracted from the getSrc method or set using the setSrc method.

Note

The getData and setData methods aren't supported for the interactive service hub.

getData

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

Xrm.Page.getControl(arg).getData()
  • Return Value
    Type: String. The data value passed to the Silverlight web resource.

setData

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

Xrm.Page.getControl(arg).setData(string)
  • Arguments
    Type: String. The data value to pass to the Silverlight web resource.

getInitialUrl

Returns the default URL that an IFRAME control is configured to display. This method is not available for web resources.

Xrm.Page.getControl(arg).getInitialUrl()
  • Return Value
    Type: String. The initial URL.

getObject

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

Xrm.Page.getControl(arg).getObject()
  • Return Value
    Type: Object. Which object depends on the type of control.

    An IFRAME returns the IFrame element from the Document Object Model (DOM).

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

Src

IFRAMEs or web resources have a src property to define what to display in the embedded window. You can get or change the src property using the getSrc and setSrc methods.

getSrc

Returns the current URL being displayed in an IFRAME or web resource.

Xrm.Page.getControl(arg).getSrc()
  • Return Value
    Type: String. A URL representing the src property of the IFRAME or web resource.

setSrc

Sets the URL to be displayed in an IFRAME or web resource.

Xrm.Page.getControl(arg).setSrc(string)
  • Arguments
    Type: String: The URL.

See Also

Client-side programming reference
Form scripting quick reference
Xrm.Page.ui (client-side reference)
Write code for Microsoft Dynamics 365 forms
Use the Xrm.Page object model

Microsoft Dynamics 365

© 2016 Microsoft. All rights reserved. Copyright