Compartir a través de


Form scripting quick reference

 

Applies To: Dynamics CRM 2013

This topic presents a quick reference of frequently used form scripting methods based on tasks you perform with them. For the full reference, see Client-side programming reference. All examples on this page use the default account entity main form unless otherwise specified.

In This Topic

Using Attributes

  • Accessing Attributes

  • Use Entity Attribute Data

  • Use Attribute Metadata

Using Save Event Arguments

Display Notifications

Using Controls

  • Accessing Form Controls

  • Use Form Controls

  • Use OptionSet Controls

  • Use IFRAME and Web Resource Controls

  • Use Lookup Controls

  • Use the SubGrid Control

  • Use the Date Control

Use Form Navigation

Use Tabs and Sections

Add or Remove Event Handlers at Runtime

Use Contextual Information

Use Entity Data

Using Attributes

Attributes store the data available in the record.

Accessing Attributes

Attributes are available from the Xrm.Page.data.entity.attributes collection. To access an attribute you can use the Xrm.Page.data.entity.attributes.get method or the shortcut version Xrm.Page.getAttribute. The get method accepts four types of arguments:

  • String: Returns an attribute object where the attribute name matches the string.

  • Number: Returns the attribute object where the Xrm.Page.data.entity.attributes collection index matches the number.

  • None: Returns an array of all the attributes.

  • Delegate function(attribute,index): Returns an array of any attributes from the Xrm.Page.data.entity.attributes collection that cause the delegate function to return true.

Task

Example

Access an attribute by name

var nameAttribute = Xrm.Page.getAttribute("name");

Assigns the attribute for the Account Name field to the nameAttribute variable

Access an attribute by index

var firstAttribute = Xrm.Page.getAttribute(0);

Assigns the first attribute in the Xrm.Page.data.entity.attributes collection to the firstAttribute variable.

Access all attributes

var allAttributes = Xrm.Page.getAttribute();

Assigns an array of all the attributes in the Xrm.Page.data.entity.attributes collection to the allAttributes variable.

Access all attributes that meet a specific criteria

var optionsetAttributes = Xrm.Page.getAttribute(function (attribute, index) {
return attribute.getAttributeType() == "optionset";
});

Assigns an array of all the attributes in the Xrm.Page.data.entity.attributes collection that meet the criteria set in the anonymous function, which returns true when the attribute type is “optionset” to the optionsetAttributes variable.

The Xrm.Page.data.entity.attributes collection also has a forEach method that you can use to access attributes within a function. The following writeRequiredAttributesToConsole function will write the names of any attributes that require data to the debugging console:

function writeRequiredAttributesToConsole() {
 var requiredAttributeNames = [];

 Xrm.Page.data.entity.attributes.forEach(
 function (attribute, index) {
  if (attribute.getRequiredLevel() == "required")
  { requiredAttributeNames.push(attribute.getName()); }
 });

 if (requiredAttributeNames.length > 0) {
  if (typeof console != "undefined") {
   console.log(requiredAttributeNames.join());
  }
 }
 else {
  if (typeof console != "undefined") {
   console.log("No required attributes detected");
  }
 }
}

In This Topic

Use Entity Attribute Data

The examples in the following table show how you can retrieve or change data stored in attributes.

Task

Method

Example

Get the value of an attribute

getValue

var nameValue = Xrm.Page.getAttribute("name").getValue();

Assigns the value of the Account Name field to the nameValue variable.

Set the value of an attribute

setValue

Xrm.Page.getAttribute("name").setValue("new name");

Sets the value of the Account Name field to “new name”.

Get the text value of the currently selected option of an optionset attribute

getText

var addressType = Xrm.Page.getAttribute("address1_addresstypecode").getText();

Assigns the text of the selected option in the Address Type field to the addressType variable.

Get the currently selected option object in an optionset attribute

getSelectedOption

var addressTypeOption = Xrm.Page.getAttribute("address1_addresstypecode").getSelectedOption();

Assigns the selected option in the Address Type field to the addressTypeOption variable.

In This Topic

Use Attribute Metadata

The examples in the following table show how you can query attribute properties to understand what kind of attribute it is or change the behavior of the attribute.

Task

Method

Example

Get the type of attribute

getAttributeType

var attributeType = Xrm.Page.getAttribute(0).getAttributeType();

Assigns the string value that represents the type of attribute for the first attribute to the attributeType variable.

Get how the attribute is formatted

getFormat

var attributeFormat = Xrm.Page.getAttribute(0).getFormat();

Assigns the string value that represents the format of the first attribute to the attributeFormat variable.

Get the initial value of a Boolean or optionset attribute

getInitialValue

var attributeInitialValue = Xrm.Page.getAttribute("address1_addresstypecode").getInitialValue();

Assigns the initial number value of the Address Type field to the attributeInitialValue variable.

Determine whether an attribute value has changed

getIsDirty

var isNameChanged = Xrm.Page.getAttribute("name").getIsDirty();

Assigns a Boolean value that indicates whether the Account Name field value has changed to the isNameChanged variable.

Determines whether a lookup attribute represents a partylist lookup.

getIsPartyList

var isPartyList = Xrm.Page.getAttribute("to").getIsPartyList();

Assigns a Boolean value that indicates whether the Email entity to field represents a party list lookup.

This method is only available for Updated entities.

Get the maximum allowed value for an attribute that contains a number

getMax

var newValue = 100000000000001;
var newValueBelowMax = (newValue < Xrm.Page.getAttribute("creditlimit").getMax())

Assigns a Boolean value that indicates whether the value of the newValue variable exceeds the maximum value allowed for the Credit Limit field to the newValueBelowMax variable.

Get the maximum allowed length for an attribute that contains a string

getMaxLength

var newAccountName = "A Store";
var nameTooLong = (newAccountName.length > Xrm.Page.getAttribute("name").getMaxLength())

Assigns a Boolean value that indicates whether the value of the newAccountName variable exceeds the maximum length allowed for the Account Name field to the nameTooLong variable.

Get the minimum allowed value for an attribute that contains a number

getMin

var newValue = -1;
var newValueBelowMin = (newValue < Xrm.Page.getAttribute("creditlimit").getMin())

Assigns a Boolean value that indicates whether the value of the newValue variable is below the minimum value allowed for the Credit Limit field to the newValueBelowMin variable.

Gets the logical name of an attribute

getName

var attributeName = Xrm.Page.getAttribute(0).getName();

Assigns the logical name value of the first attribute on the page to the attributeName variable

Get the option object representing a value

getOption

var addressTypeOption = Xrm.Page.getAttribute("address1_addresstypecode").getOption(1);
alert(addressTypeOption.text); //displays 'Bill To'

Shows an alert that displays the text of the Address Type field option with a value of 1.

Get a number value representing the level of precision for the number attribute

getPrecision

var creditLimitPrecision = Xrm.Page.getAttribute("creditlimit").getPrecision();

Assigns the precision value of the Credit Limit field to the creditLimitPrecision variable.

Get a string value representing whether the an attribute is required to have a value

getRequiredLevel

var creditLimitRequired = Xrm.Page.getAttribute("creditlimit").getRequiredLevel();

The creditLimitRequired variable value may be none, required, or recommended.

Change whether data is required in a field in order to save a record

setRequiredLevel

Xrm.Page.getAttribute("creditlimit").setRequiredLevel("required");

Makes the Credit Limit field required.

Determine whether the data in an attribute will be submitted when the record is saved

getSubmitMode

var nameSubmitMode = Xrm.Page.getAttribute("name").getSubmitMode();

The nameSubmitMode variable value will be either always, never, or dirty to represent the submitMode for the Account Name field..

Control whether data in an attribute will be saved when the record is saved

setSubmitMode

Xrm.Page.getAttribute("name").setSubmitMode("always");

The example will force the Account Name field value to always be saved even when it has not changed.

When field level security has been applied to an attribute,
determine whether a user has privileges to perform create,
read, or update operations on the attribute. For more information, see
How field security can be used to control access to field values in Microsoft Dynamics CRM 2013

getUserPrivilege

var canUpdateNameAttribute = Xrm.Page.getAttribute("name").getUserPrivilege().canUpdate;

Assigns a Boolean value that represents the user’s privilege to update the Account Name field to the canUpdateNameAttribute variable.

In This Topic

Using Save Event Arguments

When enforcing business logic it is frequently necessary to prevent a record from being saved so that the user can include required information. To do this you must configure the event handler to pass in the execution context. The execution context contains the 279ca720-e304-4e51-b99f-91722431c2c8#BKMK_GetEventArgs method to retrieve arguments for the event. These arguments include methods you can use to control whether a record will be saved or query properties that tell you about the save event.

Task

Example

Prevent a record from being saved.

function My_PreventSaveFunction(eContext) {
 eContext.getEventArgs().preventDefault();
}

Use the eContext parameter to capture the execution context and use the preventDefault method included with the event arguments.

Determine what action initiated the save.

function My_GetSaveModeTextFunction(eContext) {
 var saveModeCode = eContext.getEventArgs().getSaveMode();
 var saveModeText = "Unknown";
 switch (saveModeCode) {
  case 1:
   saveModeText = "Save";
   break;
  case 2:
   saveModeText = "SaveAndClose";
   break;
  case 5:
   saveModeText = "Deactivate";
   break;
  case 6:
   saveModeText = "Reactivate";
   break;
  case 7:
   saveModeText = "Send";
   break;
  case 15:
   saveModeText = "Disqualify";
   break;
  case 16:
   saveModeText = "Qualify";
   break;
  case 47:
   saveModeText = "Assign";
   break;
  case 58:
   saveModeText = "SaveAsCompleted";
   break;
  case 59:
   saveModeText = "SaveAndNew";
   break;
  case 70:
   saveModeText = "AutoSave";
   break;
 }
 return saveModeText;
}

Use the eContext parameter to capture the execution context and use the getSaveMode method included with the event arguments to convert the integer code value into text.

In This Topic

Display Notifications

Notifications provide a way to display a message to the user.

Task

Method

Example

Display a message near the control to indicate that data is not valid.

setNotification

Xrm.Page.getAttribute("name").controls.forEach(
function (control, i) {
control.setNotification("'Test' is not a valid name.");
})

Sets a validation error message on every control in the form for the Account Name attribute.

While this message is displayed the record cannot be saved.

This method is only available for Updated entities.

Remove a message already displayed for a control.

clearNotification

Xrm.Page.getAttribute("name").controls.forEach(
function (control, i) {
control.clearNotification();
})

Clears all validation error messages on every control in the form for the Account Name attribute.

This method is only available for Updated entities.

Display form level notifications.

setFormNotification

Xrm.Page.ui.setFormNotification(
"Hello",
"INFO",
"helloMsg"
);

Displays the message “Hello” at the top of the form with a system info icon.

This method is only available for Updated entities.

Remove form level notifications

clearFormNotification

Xrm.Page.ui.clearFormNotification("helloMsg");

Clears the message previously set using “helloMsg” as the uniqueid parameter.

This method is only available for Updated entities.

Display a non-blocking alert dialog with a callback function.

alertDialog

var alertDisplayed = false;
Xrm.Utility.alertDialog(
"Showing Alert",
function () { alertDisplayed = true; }
)

Display an alert and set the value of the alertDisplayed variable when it is closed.

This method is only available for Updated entities.

Display a non-blocking confirm dialog with different callbacks depending on the button clicked by the user.

confirmDialog

var agree = false;
Xrm.Utility.confirmDialog(
"Do you agree?",
function () { agree = true;},
function () { agree = false; }
);

Display a confirmation message and set the value of the agree variable depending on the response.

This method is only available for Updated entities.

In This Topic

Using Controls

Controls represent the user interface elements in the form. Each attribute in the form will have at least one control associated with it. Not every control is associated with an attribute. IFRAME, web resource, and subgrids are controls that do not have attributes.

Accessing Form Controls

Controls are available from the Xrm.Page.ui.controls collection. To access a control you can use the Xrm.Page.ui.controls.get method or the shortcut version Xrm.Page.getControl.

The get method accepts four types of arguments:

  • String: Returns a control where the logical name matches the string.

  • Number: Returns the control where the Xrm.Page.ui.controls collection index matches the number.

  • None: Returns an array of all the controls.

  • Delegate function(control,index): Returns an array of any controls from the Xrm.Page.ui.controls collection that cause the delegate function to return true.

Task

Example

Access all the controls for a specific attribute

var nameControls = Xrm.Page.getAttribute("name").controls.get();

Assigns an array of all the controls for the name attribute to the nameControls variable.

Access a control by name

var nameControl = Xrm.Page.getControl("name");

Assigns the first control representing the Account Name field to the nameControl variable.

The first control added to a form for an attribute will have the same name as the attribute. Each additional control name will have an index number appended to the name. For example, three controls for the name attribute will have the names: name, name1, and name2 respectively.

Access a control by index

var firstControl = Xrm.Page.getControl(0);

Assigns the first control in the Xrm.Page.ui.controls collection to the firstControl variable.

Access all controls

var allControls = Xrm.Page.getControl();

Assigns an array of all the controls in the Xrm.Page.ui.controls collection to the allControls variable.

Access all controls that meet a specific criteria

var optionsetControls = Xrm.Page.getControl(function (control, index) {
return control.getControlType() == "optionset";
});

Assigns an array of all the attributes in the Xrm.Page.ui.controls collection that meet the criteria set in the anonymous function which returns true when the control type is “optionset” to the optionsetControls variable to.

Each section also has a controls collection that contains just the controls for that section. The following code sample assigns the generalTabAccountInfoSectionControls variable to an array of controls found in the Address section of the General tab.
var generalTabAccountInfoSectionControls = Xrm.Page.ui.tabs.get("general").sections.get("address").controls.get();

Note

Each attribute exists only once in the form, but a field can be added to the form for that attribute multiple times. Each field that is added creates another control. Forms may be further customized after you write your scripts. The scripts that you write for attribute controls should assume that it has been included in the form multiple times. Any actions you want to take on a control for an attribute should usually be applied to all controls for that attribute. For example, if you want to disable a control, but only disable one of them, the user may still enter data using a different one. For this reason we recommend you use the following pattern using the collection forEach method to apply the same logic to all controls for an attribute, even if there is only one control at the time you write your script.

Xrm.Page.getAttribute("name").controls.forEach(function (control, index) { control.setDisabled(true); });

In This Topic

Use Form Controls

After you have access to a control you can call the following methods.

Task

Method

Example

Determine if a control is visible

getVisible

var isNameVisible = Xrm.Page.getControl("name").getVisible();

Assigns a Boolean value to the isNameVisible variable that represents whether the Account Name field is visible.

Hide or show a control

setVisible

Xrm.Page.getControl("name").setVisible(false);

Hides the Account Name field.

Get a reference to the attribute for the control

getAttribute

var nameAttribute = Xrm.Page.getControl("name").getAttribute();

Assigns the attribute for the control for the Account Name field to the nameAttribute variable.

Note

Not all controls have attributes.

Determine the type of the control

getControlType

var optionSetControls = Xrm.Page.getControl(function (control, index) { return control.getControlType() == "optionset"; });

Assigns an array of optionset controls to the optionSetControls variable.

Determine if a control is enabled

getDisabled

var disabledControls = Xrm.Page.getControl(function(control, index) { return control.getDisabled(); });

Assigns an array of disabled controls to the disabledControls variable.

Note

Web resource and subgrid controls do not support this method.

Disable or enable a control

setDisabled

Xrm.Page.getAttribute("name").controls.forEach(function (control, index) { control.setDisabled(true); });

Disable each control for the name attribute.

Tip

Remember that any attribute may have multiple controls.

Get the label for a control

getLabel

var nameControlLabel = Xrm.Page.getControl("name").getLabel();

Assigns the value of the control for the Account Name field to the nameControlLabel variable.

Change the label for a control

setLabel

Xrm.Page.getControl("name").setLabel("Company Name");

Changes the label for the Account Name field to Company Name.

Get the name of a control

getName

var firstControlName = Xrm.Page.getControl(0).getName();

Assigns the name of the first control in the Xrm.Page.ui.controls collection to the firstControlName variable.

Get the parent of a control

getParent

var parentSection = Xrm.Page.getControl("name").getParent();

Assigns the parent section of the control for the Account Name field to the parentSection variable.

Set focus on a control

setFocus

Xrm.Page.getControl("name").setFocus();

Sets focus on the Account Name field.

In This Topic

Use OptionSet Controls

Optionsets have some special methods. It is important to remember that the attribute defines the valid options for an optionset. When you work with an optionset control you can manipulate available options but you cannot create new options.

Task

Method

Example

Add an option to an optionset control

addOption

var addressTypeCodeControl = Xrm.Page.getControl("address1_addresstypecode");
var billToAddressOption = addressTypeCodeControl.getAttribute().getOption(1);
addressTypeCodeControl.clearOptions();
addressTypeCodeControl.addOption(billToAddressOption);

Using a reference to the control for the Address Type field, access the attribute for the control and use the getOption method to set the billToAddressOption variable to the option representing the Bill To option.

Use clearOptions to remove any existing options and use addOption to set billToAddressOption as the only option available for this control.

Remove all the options from an optionset control

clearOptions

Xrm.Page.getControl("address1_addresstypecode").clearOptions();

Remove all the options from the control for the Address Type field.

Remove a single option from an optionset control.

removeOption

Xrm.Page.getControl("address1_addresstypecode").removeOption(1);

Remove the Bill To option from the control for the Address Type field.

In This Topic

Use IFRAME and Web Resource Controls

An IFRAME control allows you to include a page within a form by providing a URL. An HTML web resource added to a form is presented using an IFRAME element. Silverlight and image web resources are embedded directly within the page.

Task

Method

Example

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

getData

var dataValue = Xrm.Page.getControl("WebResource_SilverLightControl").getData();

Assigns the value passed through the data query string parameter to the dataValue variable.

Get the URL for the content currently displayed in an IFRAME.

getSrc

var iframeSource = Xrm.Page.getControl("IFRAME_targetPage").getSrc();

Assigns the string representing the current IFRAME.src attribute value to the iframeSource variable.

Set the URL for the content to be displayed in an IFRAME.

setSrc

Xrm.Page.getControl("IFRAME_targetPage").setSrc("http://www.bing.com");

Sets a URL to be the IFRAME.src for the control.

Get the URL that represents the default configured URL for an IFRAME.

getInitialUrl

var initialUrl = Xrm.Page.getControl("IFRAME_bing").getInitialUrl();

Assigns the initial URL configured to be displayed in the IFRAME to the initialUrl variable.

Gets the object in the form that represents the web resource or IFRAME.

getObject

var obj = Xrm.Page.getControl("IFRAME_bing").getObject();

Assigns an object reference to the obj variable. For an IFRAME this will be the IFRAME Document Object Model (DOM) element. For a Silverlight web resource it will be the Object Object element that represents the embedded Silverlight plug-in.

In This Topic

Use Lookup Controls

A common requirement for lookup controls is to specify the default view displayed when a user updates the field.

Task

Method

Example

Add a custom view for a lookup.

addCustomView

var viewId = "{C7034F4F-6F92-4DD7-BD9D-9B9C1E996380}";
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>";
Xrm.Page.getControl("parentaccountid").addCustomView(viewId, "account", viewDisplayName, fetchXml, layoutXml, true);

Sets the viewId, viewDisplayName, fetchXml, and layoutXml variables to pass as arguments so that a custom view is added as the default view to the control for the Parent Account lookup field.

Get the default view for a lookup.

getDefaultView

var defaultViewId = Xrm.Page.getControl("parentaccountid").getDefaultView();

Assign the id value of the default view to the defaultViewId variable.

Set the default view for a lookup.

setDefaultView

var viewId = "{C7034F4F-6F92-4DD7-BD9D-9B9C1E996380}";
Xrm.Page.getControl("parentaccountid").setDefaultView(viewId);

Sets the default view for the control for the Parent Account field to the id value in the viewId variable.

In This Topic

Use the SubGrid Control

The SubGrid control is a grid within a form. It has one unique method.

Task

Method

Example

Refresh the data displayed in the subgrid

refresh

Xrm.Page.getControl("accountcontactsgrid").refresh();

Refresh the Contacts subgrid.

In This Topic

Use the Date Control

The Date control has one unique method.

Task

Method

Example

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

setShowTime

Xrm.Page.getControl("createdon").setShowTime(false);

Set the Created On field so the time is not shown.

This method is only available for Updated entities.

In This Topic

Use Form Navigation

You can use and manipulate the navigation items on the left side of the form. These navigation items typically show records related to the record displayed in the form.

You can access navigation items using the Xrm.Page.ui.navigation.items collection Like all collections in the form, there is a get and forEach method.

Task

Method

Example

Get the name of a navigation item

getId

var navItemIds = [];
Xrm.Page.ui.navigation.items.forEach(
function (item, index)
{ navItemIds.push(item.getId()) }
);

Create a navItemIds array that contains the id values of each navigation item in the Xrm.Page.ui.navigation.items collection.

Get the label of a navigation item.

getLabel

var navAddressesLabel = Xrm.Page.ui.navigation.items.get("navAddresses").getLabel();

Assign the label for the More Addresses navigation item to the navAddressesLabel variable.

Set the label of a navigation item

setLabel

Xrm.Page.ui.navigation.items.get("navAddresses").setLabel("Other Addresses");

Change the More Addresses navigation item label to Other Addresses.

Show or hide a navigation item

setVisible

Xrm.Page.ui.navigation.items.get("navAddresses").setVisible(false);

Hide the More Addresses navigation item.

Determine if a navigation item is visible

getVisible

var moreAddressesVisible = Xrm.Page.ui.navigation.items.get("navAddresses").getVisible()

Assign a Boolean value to the moreAddressesVisible variable to represent whether the More Addresses navigation item is visible.

Set focus on a navigation item.

setFocus

Xrm.Page.ui.navigation.items.get("navAddresses").setFocus();

Set focus on the More Addresses navigation item.

In This Topic

Use Tabs and Sections

Each form has collection of tabs. Each Tab has a collection of sections. Each section has a collection of controls. You can programmatically access these elements and use their methods.

Task

Method

Example

Determine if a tab is expanded or collapsed

getDisplayState

var isGeneralTabExpanded = (Xrm.Page.ui.tabs.get("general").getDisplayState() == "expanded")

Assign a Boolean value to the isGeneralTabExpanded variable that indicates whether the General tab is expanded.

Expand or collapse a tab

setDisplayState

Xrm.Page.ui.tabs.get("general").setDisplayState("collapsed");

Collapse the General tab.

Determine if a tab is visible

getVisible

var isGeneralTabVisible = Xrm.Page.ui.tabs.get("general").getVisible();

Assign a Boolean value to the isGeneralTabVisible variable indicating whether the General tab is visible.

Show or hide a tab

setVisible

Xrm.Page.ui.tabs.get("general").setVisible(false);

Hide the General tab.

Get the label for a tab

getLabel

var generalTabLabel = Xrm.Page.ui.tabs.get("general").getLabel();

Assign the General tab label to the generalTabLabel variable.

Change the label for a tab

setLabel

Xrm.Page.ui.tabs.get("general").setLabel("Major");

Change the General tab label to Major.

Set focus on a tab

setFocus

Xrm.Page.ui.tabs.get("general").setFocus();

Set focus on the General tab.

Get the name of the tab

getName

var firstTabName = Xrm.Page.ui.tabs.get(0).getName();

Assign the name of the first tab to the firstTabName variable.

Get the parent tab of a section

getParent

Xrm.Page.getControl("industrycode").getParent().getParent().setFocus();

Set focus on the tab that contains the Industry field.

Determine if a section is visible

getVisible

var industrySectionVisible = Xrm.Page.getControl("industrycode").getParent().getVisible();

Assign a Boolean value to the industrySectionVisible variable indicating whether the section containing the Industry field is visible.

Show or hide a section

setVisible

Xrm.Page.getControl("industrycode").getParent().setVisible(false);

Hide the section that contains the Industry field.

Get the label for a section

getLabel

var industryFieldSectionLabel = Xrm.Page.getControl("industrycode").getParent().getLabel();

Assign the label of the section containing the Industry field to the industryFieldSectionLabel variable.

Change the label for a section

setLabel

Xrm.Page.getControl("industrycode").getParent().setLabel("Detailed Information");

Change the label of the section that contains the Industry field to Detailed Information.

In This Topic

Add or Remove Event Handlers at Runtime

Event handlers are usually configured using the form editor in the application but you can also add them to the form OnSave event and attribute OnChange events at run time using these APIs. The examples in this section will refer to the following function definition:
function myFunction() {
//perform action here
}

While you can add an anonymous function, the function must have a name to reference in order to remove it.

Task

Method

Example

Add a function to the OnSave event

addOnSave

Xrm.Page.data.entity.addOnSave(myFunction);

Add the myFunction function to the OnSave event.

Remove a function from the OnSave event

removeOnSave

Xrm.Page.data.entity.removeOnSave(myFunction);

Remove the myFunction function to the OnSave event.

Add a function to the OnChange event of an attribute.

addOnChange

Xrm.Page.getAttribute("name").addOnChange(myFunction);

Add the myFunction function to the OnChange event of the Account Name field.

Remove a function from the OnChange event of an attribute

removeOnChange

Xrm.Page.getAttribute("name").removeOnChange(myFunction);

Remove the myFunction function to the OnChange event of the Account Name field.

In This Topic

Use Contextual Information

Use these methods to get information about the user, the organization, and the client. The following table provides some of the most useful context methods. For all the context methods, see Client-side context (client-side reference)

Task

Method

Example

Get the URL to connect to the organization.

getClientUrl

var serverUrl = Xrm.Page.context.getClientUrl();

Assign a string that represents the URL to the serverUrl variable.

Get the unique identifier for the current user.

d7d0b052-abca-4f81-9b86-0b9dc5e62a66#BKMK_getUserId

var userId = Xrm.Page.context.getUserId();

Assign a string that represents the user’s Id to the userId variable.

Get the name of the current user.

getUserName

var userName = Xrm.Page.context.getUserName();

Assign a string that represents the user’s name to the userName variable.

This method is only available for Updated entities.

Get the language code that represents the user’s preferred user interface language.

d7d0b052-abca-4f81-9b86-0b9dc5e62a66#BKMK_getUserLcid

var userLCID = Xrm.Page.context.getUserLcid();

Assign a number that indicates the user’s preferred language to the userLCID variable.

Get an array of strings that represents the GUID values for each security role assigned to the current user and any teams that the user is associated with.

d7d0b052-abca-4f81-9b86-0b9dc5e62a66#BKMK_getUserRoles

var userRoles = Xrm.Page.context.getUserRoles();

Assign an array of strings that represents the user’s security roles to the userRoles variable.

Determine whether the script is running in the Microsoft Dynamics CRM for Microsoft Office Outlook client.

client.getClient

var isOutlookClient = (Xrm.Page.context.client.getClient() == "Outlook");

Assign a Boolean value that represents whether your code is running in the CRM for Outlook client to the isOutlookClient variable.

Determine whether the user is working offine with the Microsoft Dynamics CRM for Microsoft Office Outlook with Offline Access client.

client.getClientState

var IsOffline = (Xrm.Page.context.client.getClientState() == "Offline");

Assign a Boolean value that represents whether the user is currently working offline to the IsOffline variable.

In This Topic

Use Entity Data

The following table contains methods you can use to get information about the current record. For more information, see Xrm.Page.data.entity (client-side reference) and Xrm.Page.data (client-side reference).

Task

Method

Example

Get the logical name of the current entity

getEntityName

var entityName = Xrm.Page.data.entity.getEntityName();

Assign the logical entity name to the entityName variable.

Get the value of the primary attribute for the current entity.
The primary attribute is the value used to identify the record. For example contact.fullname.

getPrimaryAttributeValue

var primaryAttributeValue = Xrm.Page.data.entity.getPrimaryAttributeValue();

Assign the value of the primary attribute to the primaryAttributeValue variable.

This method is only available for Updated entities.

Get the Id of the current record

getId

var recordId = Xrm.Page.data.entity.getId();

Assign the id of the record to the recordId variable.

Asynchronously refresh the data of the form without reloading the page.

refresh

Xrm.Page.data.refresh();

Refreshes the data in the form.

This method is only available for Updated entities.

Save the current record

Xrm.Page.data.entity.save

Xrm.Page.data.entity.save();

Saves the record. There are optional arguments. Use saveandclose or saveandnew to perform the equivalent actions.

Save the current record asynchronously with the option to set
callback functions to be executed after the save operation is completed.

Xrm.Page.data.save

Xrm.Page.data.save().then(
function(){
Xrm.Utility.alertDialog("Record saved");
},
function(error){ 
Xrm.Utility.alertDialog(error.message);
});

Saves the record and displays a message showing the status of the save.

This method is only available for Updated entities.

Determine whether any data in the current record is changed.

getIsDirty

var isDirty = Xrm.Page.data.entity.getIsDirty();

Assign a Boolean value that represents whether data in the record has changed to the isDirty variable.

Get a string that represents the data that will be sent to the server when the record is saved.

getDataXml

var dataXml = Xrm.Page.data.entity.getDataXml();

Assign a string that represents the data to be saved to the dataXml variable.

In This Topic

See Also

Use the Xrm.Page object model
Write code for Microsoft Dynamics CRM 2013 forms
Client-side programming reference