Поделиться через


Xrm.Page.data.entity attribute (client-side reference)

 

Applies To: Dynamics CRM 2015

Attributes contain the data in the form. Use the Xrm.Page.data.entity.attributes collection or the Xrm.Page.getAttribute shortcut method to access a collection of attributes. For more information see Collections (client-side reference).

Attribute Properties and Methods

  • Boolean and OptionSet Attribute methods
    The getInitialValue, getOption, getOptions, getSelectedOption, and getText methods provide ways to get information about Boolean or OptionSet attributes.

  • controls
    Access controls associated with attributes.

  • getAttributeType
    Get the type of attribute.

  • getFormat
    Get the attribute format.

  • getIsDirty
    Determine whether the value of an attribute has changed since it was last saved.

  • getIsPartyList
    Determine whether a lookup attribute represents a partylist lookup.

  • getMaxLength
    Get the maximum length of string which an attribute that stores string data can have.

  • getName
    Get the name of the attribute.

  • getParent
    Get a reference to the Xrm.Page.data.entity object that is the parent to all attributes.

  • getUserPrivilege
    Determine what privileges a user has for fields using Field Level Security.

  • Number Attribute methods
    Use the getMax, getMin, and getPrecision methods to access information about the properties of number attributes.

  • OnChange Event
    Use the addOnChange, removeOnChange, and fireOnChange methods and to manage event handlers for the OnChange event.

  • RequiredLevel
    Use the setRequiredLevel and getRequiredLevel methods to control whether an attribute must have a value in order to save a record.

  • SubmitMode
    Use the setSubmitMode and getSubmitMode methods to control whether the value of an attribute will be submitted when a record is saved.

  • Value
    Use the getValue and setValue methods to determine the values set for an attribute and change the value.

Boolean and OptionSet Attribute methods

The getInitialValue, getOption, getOptions, getSelectedOption, and getText methods provide ways to get information about Boolean or OptionSet attributes.

getInitialValue

Returns a value that represents the value set for an OptionSet or Boolean attribute when the form opened.

Attribute Types: Optionset and Boolean

Xrm.Page.getAttribute(arg).getInitialValue()
  • Return Value
    Type: Number. The initial value for the attribute.

getOption

Returns an option object with the value matching the argument passed to the method.

Attribute Types: optionset

Xrm.Page.getAttribute(arg).getOption(value)
  • Arguments
    String or Number value

  • Return Value
    Type: Option object with text and value properties.

getOptions

Returns an array of option objects representing the valid options for an optionset attribute.

Attribute Types: optionset

Xrm.Page.getAttribute(arg).getOptions()
  • Return Value
    Type: Array of option objects.

getSelectedOption

Returns the option object that is selected in an optionset attribute.

Attribute Types: optionset

Xrm.Page.getAttribute(arg).getSelectedOption()
  • Return Value
    Type: Option object with text and value properties.

getText

Returns a string value of the text for the currently selected option for an optionset attribute.

Attribute Types: optionset

Xrm.Page.getAttribute(arg).getText()
  • Return Value
    Type: String. The text value of the selected option.

    Note

    When no option is selected, getText will return an empty string value.

controls

See Collections (client-side reference) to learn about the methods exposed by collections.

Because each attribute may be represented more than one time on the page, the controls collection provides access to all controls representing that attribute. If the attribute is represented by only one field in the page, the length of this collection will be 1. When you use the control getName method the name of the first control will be the same as the name of the attribute. The second instance of a control for that attribute will be ‘<attributeName>1’. The pattern <attributeName>+N will continue for each additional control added to the form for a specific attribute.

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 like the following: header_process_<attribute name>.

When performing actions on controls that are tied to an attribute you should always consider that the control may be included on the page more than once and you should generally perform the same actions for each control for the attribute. You can do this by looping through the attribute controls collection and perform the actions on each control.

The following sample represents a JavaScript library with two reusable functions that use the attribute controls collection to hide and show controls:

  • SDK.Sample.hideAllAttributeControls: Hides all controls for the attribute.

  • SDK.Sample.showAllAttributeControls: Shows all controls for the attribute.

if (typeof (SDK) == "undefined")
{SDK = { __namespace: true }; }
SDK.Sample = { __namespace: true };
SDK.Sample.hideAllAttributeControls = function (attributeLogicalName) {
    /// <summary>
    /// Hides all controls for the attribute.
    /// </summary>
    /// <param name="attributeLogicalName" type="String" mayBeNull="false" optional="false" >
    /// The logical name of an attribute.
    /// </param>
    if ((typeof attributeLogicalName != "string") ||
        (attributeLogicalName.length <= 3))
    { throw new Error("SDK.Sample.hideAllAttributeControls attributeLogicalName parameter must be a string at least 4 characters long."); }
    Xrm.Page.getAttribute(attributeLogicalName).controls.forEach(
        function (control, i) {
            control.setVisible(false);
            }
        );
}
SDK.Sample.showAllAttributeControls = function (attributeLogicalName) {
    /// <summary>
    /// Shows all controls for the attribute.
    /// </summary>
    /// <param name="attributeLogicalName" type="String" mayBeNull="false" optional="false" >
    /// The logical name of an attribute.
    /// </param>
    if ((typeof attributeLogicalName != "string") ||
        (attributeLogicalName.length <= 3))
    { throw new Error("SDK.Sample.showAllAttributeControls attributeLogicalName parameter must be a string at least 4 characters long."); }
    Xrm.Page.getAttribute(attributeLogicalName).controls.forEach(
        function (control, i) {
            control.setVisible(true);
            }
        );
}

To use these functions, pass the logical name of the attribute as shown here:

//Hide the controls for the subject attribute.
SDK.Sample.hideAllAttributeControls("subject");
//Show the controls for the subject attribute.
SDK.Sample.showAllAttributeControls("subject");

getAttributeType

Returns a string value that represents the type of attribute.

Attribute Types: All

Xrm.Page.getAttribute(arg).getAttributeType()
  • Return Value
    Type: String

    This method will return one of the following string values:

    • boolean

    • datetime

    • decimal

    • double

    • integer

    • lookup

    • memo

    • money

    • optionset

    • string

getFormat

Returns a string value that represents formatting options for the attribute.

Attribute Types: All

Xrm.Page.getAttribute(arg).getFormat()
  • Return Value
    Type: String

    This method will return one of the following string values or null:

    • date

    • datetime

    • duration

    • email

    • language

    • none

    • phone

    • text

    • textarea

    • tickersymbol

    • timezone

    • url

Note

This format information generally represents the format options of the application field. Format options for Boolean fields are not provided.

The following table lists the format string values to expect for each type of attribute schema type and format option.

Application Field Type

Format Option

Attribute Type

Format Value

Date and Time

Date Only

datetime

date

Date and Time

Date and Time

datetime

datetime

Whole Number

Duration

integer

duration

Single Line of Text

E-mail

string

email

Whole Number

Language

optionset

language

Whole Number

None

integer

none

Single Line of Text

Text Area

string

textarea

Single Line of Text

Text

string

text

Single Line of Text

Ticker Symbol

string

tickersymbol

Single Line of Text

Phone

string

phone

Whole Number

Time Zone

optionset

timezone

Single Line of Text

Url

string

url

getIsDirty

Returns a Boolean value indicating if there are unsaved changes to the attribute value.

Attribute Types: All

Xrm.Page.getAttribute(arg).getIsDirty()
  • Return Value
    Type: Boolean. True if there are unsaved changes, otherwise false.

getIsPartyList

Returns a Boolean value indicating whether the lookup represents a partylist lookup. Partylist lookups allow for multiple records to be set, such as the To: field for an email entity record.

Attribute Types: lookup

Xrm.Page.getAttribute(arg).getIsPartyList()
  • Return Value
    Type: Boolean. True if the lookup attribute is a partylist, otherwise false.

  • Remarks
    This method is only available for Updated entities.

getMaxLength

Returns a number indicating the maximum length of a string or memo attribute.

Attribute Types: string, memo

Xrm.Page.getAttribute(arg).getMaxLength()
  • Return Value
    Type: Number. The maximum allowed length of a string for this attribute.

    Note

    The email form description attribute is a memo attribute, but it does not have a getMaxLength method.

getName

Returns a string representing the logical name of the attribute.

Attribute Types: All

Xrm.Page.getAttribute(arg).getName()
  • Return Value
    Type: String. The logical name of the attribute.

getParent

Returns the Xrm.Page.data.entity object that is the parent to all attributes.

This function exists to provide a consistent interface with other objects. In this case, because every attribute returns the same object, there are not many situations where it is useful.

Attribute Types: All

Xrm.Page.getAttribute(arg).getParent()
  • Return Value
    Type: Xrm.Page.data.entity object.

getUserPrivilege

Returns an object with three Boolean properties corresponding to privileges indicating if the user can create, read or update data values for an attribute. This function is intended for use when Field Level Security modifies a user’s privileges for a particular attribute. For more information, see How field security can be used to control access to field values in Microsoft Dynamics CRM.

Attribute Types: All

Xrm.Page.getAttribute(arg).getUserPrivilege()
  • Return Value
    Type: Object

    The object has three Boolean properties:

    • canRead

    • canUpdate

    • canCreate

Number Attribute methods

Use the getMax, getMin, and getPrecision methods to access information about the properties of number attributes.

getMax

Returns a number indicating the maximum allowed value for an attribute.

Attribute Types: money, decimal, integer, double

Xrm.Page.getAttribute(arg).getMax()
  • Return Value
    Type: Number. The maximum allowed value for the attribute.

getMin

Returns a number indicating the minimum allowed value for an attribute.

Attribute Types: money, decimal, integer, double

Xrm.Page.getAttribute(arg).getMin()
  • Return Value
    Type: Number. The minimum allowed value for the attribute.

getPrecision

Returns the number of digits allowed to the right of the decimal point.

Attribute Types: money, decimal, double, and integer

Xrm.Page.getAttribute(arg).getPrecision()
  • Return Value
    Type: Number. The number of digits allowed to the right of the decimal point.

OnChange Event

There are three methods you can use to work with the OnChange event for an attribute:

  • addOnChange

  • removeOnChange

  • fireOnChange

addOnChange

Sets a function to be called when the attribute value is changed.

Xrm.Page.getAttribute(arg).addOnChange([function reference])
  • Parameter
    Type: function pointer

    Remarks: The function will be added to the bottom of the event handler pipeline. The execution context is automatically set to be the first parameter passed to the event handler. See Execution context (client-side reference) for more information.

    **Example:**In this example, the JScript library contains two functions. Adding the addMessageToOnChange function to the form OnLoad event will add the displayMessage function as a handler for the OnChange event for the first attribute in the form.

    function addMessageToOnChange() 
    { 
       Xrm.Page.data.entity.attributes.get(0).addOnChange(displayOrgName);
    }
    function displayOrgName(execContext) 
    { 
       Xrm.Utility.alertDialog(execContext.getContext().getOrgUniqueName()); 
    }
    

removeOnChange

Removes a function from the OnChange event hander for an attribute.

Xrm.Page.getAttribute(arg).removeOnChange([function reference])
  • Parameter
    Type: function reference

    Example: In this example, the JScript library contains two functions. Adding the removeMessageFromOnChange function to another form event will remove the displayOrgName function as a handler for the OnChange event for the first attribute on the form.

    function removeMessageFromOnChange() 
    {
       Xrm.Page.data.entity.attributes.get(0).removeOnChange(displayOrgName);
    }
    function displayOrgName(execContext) 
    { 
       Xrm.Utility.alertDialog(execContext.getContext().getOrgUniqueName()); 
    }
    

fireOnChange

Causes the OnChange event to occur on the attribute so that any script associated to that event can execute.

Attribute Types: All

Xrm.Page.getAttribute(arg).fireOnChange()

RequiredLevel

You can control whether the application will require that a field contain data before a record can be saved. Use the getRequiredLevel and setRequiredLevel methods to adjust this requirement.

getRequiredLevel

Returns a string value indicating whether a value for the attribute is required or recommended.

Attribute Types: All

Xrm.Page.getAttribute(arg).getRequiredLevel()
  • Return Value
    Type: String

    Returns one of the three possible values:

    • none

    • required

    • recommended

setRequiredLevel

Sets whether data is required or recommended for the attribute before the record can be saved.

Important

Reducing the required level of an attribute can cause an error when the page is saved. If the attribute is required by the server an error will occur if the there is no value for the attribute.

Attribute Types: All

Xrm.Page.getAttribute(arg).setRequiredLevel(requirementLevel)
  • Arguments
    Type: String

    One of the following values:

    • none

    • required

    • recommended

SubmitMode

You can control when data for an attribute is submitted when a record is created or saved. For example, you may have a field on the form which is only intended to control logic in the form. You are not interested in capturing the data in it. You might set it so that the data is not saved. Or you may have a Plugin registered that depends on the value always being included. You may want to set the attribute so that it will always be included. Attributes that do not get updated after the initial save of the record, such as createdby, are set so that they will not be submitted on save. To force an attribute value to be submitted whether it has changed or not, use the setSubmitMode function with the mode parameter set to “always”.

When using setSubmitMode you have three options:

  • always: The value is always submitted.

  • never: The value is never submitted. When this option is set, data cannot be edited for any fields in the form for this attribute.

  • dirty (default): The value is submitted on create if it is not null, and on save only when it is changed.

Use getSubmitMode to determine the current setting.

getSubmitMode

Returns a string indicating when data from the attribute will be submitted when the record is saved.

Attribute Types: All

Xrm.Page.getAttribute(arg).getSubmitMode()
  • Return Value
    Type: String

    Returns one of the three possible values:

    • always

    • never

    • dirty

    The default value for editable fields is ‘dirty’, which means that the value will be submitted to the server only when that data value is changed.

setSubmitMode

Sets whether data from the attribute will be submitted when the record is saved.

Attribute Types: All

Xrm.Page.getAttribute(arg).setSubmitMode()
  • Arguments
    Type: String

    One of the following values:

    • always: The data is always sent with a save.

    • never: The data is never sent with a save. When this is used the field(s) in the form for this attribute cannot be edited.

    • dirty: Default behavior. The data is sent with the save when it has changed.

Value

Accessing or setting the value of attributes are the most commonly performed actions in form scripts.

getValue

Retrieves the data value for an attribute.

Attribute Types: All

Xrm.Page.getAttribute(arg).getValue()
  • Return Value
    Type: Depends on type of attribute.

    Attribute Type

    Return Type

    boolean

    Boolean

    datetime

    Date

    To get the string version of a date using the Microsoft Dynamics CRM user’s locale preferences, use the format and localeFormat methods. Other methods will format dates using the operating system locale rather than the user’s Microsoft Dynamics CRM locale preferences.

    decimal

    Number

    Double

    Number

    integer

    Number

    lookup

    Array

    An array of lookup objects.

    Note

    Certain lookups allow for multiple records to be associated in a lookup, such as the To: field for an email entity record. Therefore, all lookup data values use an array of lookup objects – even when the lookup attribute does not support more than one record reference to be added.

    Each lookup has the following properties:

    entityType

    String: the name of the entity displayed in the lookup

    id

    String: The string representation of the GUID value for the record displayed in the lookup.

    name

    String: The text representing the record to be displayed in the lookup.

    memo

    String

    money

    Number

    optionset

    Number

    string

    String

setValue

Sets the data value for an attribute.

Attribute Types: All

Xrm.Page.getAttribute(arg).setValue()
  • Arguments
    Depends on the type of attribute.

    Attribute Type

    Argument Type

    boolean

    Boolean

    datetime

    Date

    decimal

    Number

    double

    Number

    Integer

    Number

    lookup

    Array

    An array of lookup objects.

    Note

    Certain lookups, known as ‘partylist’ lookups, allow for multiple records to be associated in a lookup, such as the To: field for an email entity record. Therefore, all lookup data values use an array of lookup objects – even when the lookup attribute does not support more than one record reference to be added.

    Each lookup value has the following properties:

    entityType

    String: the logical name of the entity represented by the lookup.

    id

    String: The string representation of the GUID value for the record displayed in the lookup. The value should match the following format: {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}.

    name

    String: The text representing the record to be displayed in the lookup. Typically the primary attribute for the entity.

    See Set Lookup Attribute Value for an example of a helper function you can create to set simple lookup attribute values.

    memo

    String

    money

    Number

    optionset

    Number

    Note

    The getOptions method returns option values as strings. You must use parseInt to convert them to numbers before you can use those values to set the value of an optionset attribute.

    Valid statuscode (Status Reason) options depend on the current statecode of the record. The statecode (Status) field cannot be set in form scripts. To understand which statecode values are valid, refer to the metadata for the attributes. See TechNet: Default status and status reason values for a list of default values for system entities. For custom entities use the Entity Metadata browser described in Browse the metadata for your organization. Finally, also consider any custom state transitions that have been applied to the field. More information: TechNet: Define status reason transitions.

    String

    String

    Note

    A String field with the email format requires that the string represents a valid email address.

Note

  • Updating an attribute using setValue will not cause the OnChange event handlers to run. If you want the OnChange event handlers to run you must use fireOnChange in addition to setValue.

  • When Microsoft Dynamics CRM for tablets is not connected to the server setValue will not work.

  • You cannot set the value of composite attributes. More information: Write scripts for composite attributes.

Set Lookup Attribute Value

The following example shows the definition of a setSimpleLookupValue helper function that sets the value for simple lookup attributes.

function setSimpleLookupValue(LookupId, Type, Id, Name) {
   /// <summary>
   /// Sets the value for lookup attributes that accept only a single entity reference.
   /// Use of this function to set lookups that allow for multiple references, 
   /// a.k.a 'partylist' lookups, will remove any other existing references and 
   /// replace it with just the single reference specified.
   /// </summary>
   /// <param name="LookupId" type="String" mayBeNull="false" optional="false" >
   /// The lookup attribute logical name
   /// </param>
   /// <param name="Type" type="String" mayBeNull="false" optional="false" >
   /// The logical name of the entity being set.
   /// </param>
   /// <param name="Id" type="String" mayBeNull="false" optional="false" >
   /// A string representation of the GUID value for the record being set.
   /// The expected format is "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}".
   /// </param>
   /// <param name="Name" type="String" mayBeNull="false" optional="false" >
   /// The text to be displayed in the lookup.
   /// </param>
   var lookupReference = [];
   lookupReference[0] = {};
   lookupReference[0].id = Id;
   lookupReference[0].entityType = Type;
   lookupReference[0].name = Name;
   Xrm.Page.getAttribute(LookupId).setValue(lookupReference);
  }

The following is an example using the setSimpleLookupValue function to set the primarycontactid attribute value on an account form:

setSimpleLookupValue("primarycontactid", "contact", "{6D9D4FCF-F4D3-E011-9D26-00155DBA3819}", "Brian Lamee");

See Also

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

© 2016 Microsoft. All rights reserved. Copyright