Zdieľať cez


Write code for Microsoft Dynamics CRM 2015 forms

 

Applies To: Dynamics CRM 2015

Form programming provides ways to interact with entity forms by using JavaScript that is executed for events that occur on the form.

In This Topic

When to use form programming

Factors to consider when you use form programming

Manage library dependencies

Write form scripts that perform well

Different Form Presentations

Development tools

When to use form programming

Microsoft Dynamics CRM provides many options to control business processes. Form programming is one option. But remember that you have another option: business rules. Business rules provide a way for someone who does not know JavaScript and is not a developer to apply business process logic in a form. See the customization guide topic: TechNet: Create and edit business rules for more information.

The primary advantage of form programming and business rules is that they are immediate. They do not require data to be submitted to the server and, therefore, provides the best performance for many scenarios. Because they allow for human interaction, they are also the most flexible option.

While business rules have an advantage because they can be created and maintained by someone who is not a developer, they have certain limitations and are not intended to replace form scripts. Form programming allows you to achieve things that cannot yet be done using business rules.

Tasks frequently performed by using form programming include the following:

  • Data validation

  • Automation

  • Process enhancement and enforcement

Data validation

Whenever possible, you should perform validation of data while the data is being edited. The definition of the Form field will perform the most common data validation for you. For example, a Single Line of Text field formatted for an email address will not allow an invalid value to be entered into it.

Use form programming for additional validation of data that is unique to your organization. For example, your organization may have specific rules about how telephone numbers should be formatted or a minimum length for the Subject field in a service activity.

Automation

You can achieve significant productivity enhancements when you use form scripting to automate common tasks. You can set field values that depend on the data that is entered into a form, that will help save users considerable time when entering data. Using form programming for automation is valuable because it lets the user verify that a standard process is valid in a particular case. Users can make necessary adjustments before saving a record.

Process enhancement and enforcement

You can customize what data to display in the form or the layout of the form to optimize it for specific tasks performed by people in your organization. You can use form programming to show or hide specific form elements, or to open different forms that have been defined for an entity. You can control which fields are required based on data present in the form or in related records.

With Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update you can write code to control the business process flows that appear at the top of forms. More information: Write scripts for business process flows.

Factors to consider when you use form programming

The logic applied in form programming can only be executed in the browser of someone interacting within the Microsoft Dynamics CRM application entity form. Because of this, you should not rely solely on form programming to initiate or enforce processes related to your data. Records can be created or updated directly through the Web service APIs or through workflows outside the context of the form. Form programming should complement business logic applied by using plugins and processes so that all records created or updated in any manner will comply with the same processes.

With Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update, business rules can be defined to run at the entity scope so that the same logic is applied on the server regardless of where the action originated. More information: TechNet: Create and edit business rules

While form programming provides capabilities to hide form fields so that users may not be able to view or update some entity data, it does not represent a complete solution for enforcing security requirements. A user can see entity data that is not visible on the form by using a variety of methods, such as Advanced Find. More information: The security model of Microsoft Dynamics CRM 2015

Manage library dependencies

As a performance optimization, Microsoft Dynamics CRM forms load JavaScript web resources asynchronously and in parallel. This means that the order in which the libraries are configured for a form does not guarantee that a library will be fully downloaded and initialized before another library might attempt to use one of the objects defined in it.

If you have code that depends on another library to be fully downloaded and initialized, the most straightforward approach is to combine both libraries within a single JavaScript web resource with your code below the library code. A more sophisticated approach is to use libraries such as head.js or require.js to control how the separate libraries are loaded.

Write form scripts that perform well

When you write scripts for forms, use the following practices to help achieve the best performance:

  • Avoid including unnecessary JavaScript web resource libraries
    The more scripts you add to the form, the more time it will take to download them. Usually scripts are cached in your browser after they are loaded the first time, but the performance the first time a form is viewed often creates a significant impression.

    For a specific example, don’t include jQuery in your form scripts simply because you want to use XMLHttpRequests. While jQuery has the $.ajax function that many people are familiar with to perform these requests, it is a developer preference, not a necessity. It is possible to perform these requests using the native XMLHttpRequest object found in all browsers supported by Microsoft Dynamics CRM. More information: Use of jQuery

  • Avoid loading all scripts in the Onload event
    If you have code that only supports OnChange events for fields or the OnSave event, make sure to set the script library with the event handler for those events instead of the OnLoad event. This way loading those libraries can be deferred and increase performance when the form loads.

    We do not recommend using the addOnChange method within the OnLoad event handler simply as a matter of convenience. While this may reduce the number of steps necessary to add your event handlers, it causes the form to load more slowly.

  • Use collapsed tabs to defer loading web resources
    When web resources or IFRAMES are included in sections inside a collapsed tab, they will not be loaded if the tab is collapsed. They will be loaded when the tab is expanded. When the tab state changes, the TabStateChange event occurs. Any code that is required to support web resources or IFRAMEs within collapsed tabs can use event handlers for the TabStateChange event and reduce code that might otherwise have to occur in the OnLoad event.

  • Set default visibility options
    Avoid using form scripts in the OnLoad event that hide form elements. Instead, set the default visibility options for form elements that might be hidden to not be visible by default when the form loads. Then, use scripts in the OnLoad event to show those form elements you want to display.

Different Form Presentations

There are several different ways that forms are presented. These affect the type of code or available events you can use for each.

Legacy form rendering

With Microsoft Dynamics CRM Online 2015 Update 1 there is a new system setting: Use legacy form rendering. With this release, the rendering of the form has been improved and the internal structure of the page is changed. As a result, form scripts that used unsupported methods will not be able to access elements of the DOM that were available in previous releases. If you have new errors after upgrading to this release, try applying this setting to see if the errors go away. If so, there is a good chance that the scripts causing these errors are using unsupported methods.

You can set Use legacy form rendering to allow time to address these issues, however, you won’t experience the performance improvements that the new form rendering infrastructure provides.

Note

The Use legacy form rendering setting will be removed from the next major release. At that time all form scripts must work with the new form rendering.

Updated entities

All custom entities and certain system entities have an updated user interface that includes using the command bar and new form APIs. The updated system entities are listed in the following table:

Account

Appointment

Campaign

Campaign Activity

Campaign Response

Case

Competitor

Contact

Contract

Contract Line

Email

Entitlement

Entitlement Template

Fax

Invoice

Lead

Letter

Marketing List

Opportunity

Opportunity Product

Order

Phone Call

Position

Price List Item

Product

Product Association

Product Relationship

Queue

Quick Campaign

Quote

Recurring Appointment

Sales Literature

SLA

SLA KPI Instance

Social Activity

Social Profile

Task

Team

User

Note

Some updated entities include composite attributes. These require some special consideration. More information: Write scripts for composite attributes.

Updated entity forms may also include a collaboration control that provides access to Notes, Activities, and Posts if they are enabled for the entity. The Xrm.Page object does not provide access to the collaboration control. You can access the section element that contains the collaboration control if you want to show or hide it by using scripts.

Form programming methods and PreSearch event for updated entities

The following table lists the form programming methods available for updated entities only.

Method

Description

Xrm.Page.context.client.getClient

Returns a value to indicate which client the script is executing in.

Xrm.Page.context.client.getClientState

Returns a value to indicate the state of the client.

Xrm.Page.context.getUserName

Returns the name of the current user.

Xrm.Page.data.entity.getPrimaryAttributeValue

Gets a string for the value of the primary attribute of the entity.

Xrm.Page.data.refresh

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

Xrm.Page.data.save

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

Xrm.Page.data.entity attribute.getIsPartyList

Determines whether a lookup attribute represents a partylist lookup.

Xrm.Page.ui control.clearNotification

Removes a message already displayed for a control.

Xrm.Page.ui control.setNotification

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

Xrm.Page.ui.clearFormNotification

Use this method to remove form level notifications.

Xrm.Page.ui.setFormNotification

Use this method to display form level notifications.

Xrm.Page.ui control.addCustomFilter

Use fetchXml to add additional filters to the results displayed in the lookup. Each filter will be combined with any previously added filters as an ‘AND’ condition.

Xrm.Page.ui control.setShowTime

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

Xrm.Utility.alertDialog

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

Xrm.Utility.confirmDialog

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

PreSearch Event

The new PreSearch event occurs just before the search dialog box opens when you set a lookup value. This event does not have user interface to set an event handler in the application; it can only be set using the Xrm.Page.ui control.addPreSearch method. Use this event with the addCustomFilter, addCustomView and setDefaultView methods to control the views opened when people search for a record to set as the value of a lookup field.

Entities that use classic forms

System entities that were not updated use classic form presentation. Forms for these entities continue to use the ribbon if they did in CRM 2011 and do not have access to form APIs added in this release. These entities are listed in the following table:

Address

Article

Article Comment

Bulk Delete Operation

Business Unit

Connection

Discount

Discount List

Document Location

Email Attachment

Follow

Goal

Goal Metric

Import Source File

Invoice Product

Order Product

Price List

Queue Item

Quote Product

Rollup Field

Rollup Query

Saved View

Service

Service Activity

SharePoint Site

Site

Territory

Unit

Unit Group

Entities enabled for CRM for tablets

Only selected system entities and custom entities are available to be shown by using Microsoft Dynamics CRM for tablets. The following system entities may have editable forms in CRM for tablets.

Account

Activity

Appointment

Case

Competitor

Connection

Contact

Lead

Note

Opportunity

Opportunity Product

Phone Call

Queue Item

Social Activity

Social Profile

Task

Because CRM for tablets does not have the same behaviors as forms in the web application, some APIs are not available. For example, in CRM for tablets tabs cannot be expanded or collapsed, so the Tab TabStateChange event does not occur and the Xrm.Page.ui tab. setDisplayState cannot be used to expand or collapse tabs. More information: Write and debug scripts for CRM for tablets.

Development tools

Your experience writing JavaScript for CRM forms will be better when you use good tools.

Use good authoring tools

Because JavaScript is an interpreted language special development tools are not required. JavaScript is just text so it can be edited in the application or in a text editor such as Notepad. However, you can achieve significant productivity gains when you use authoring tools that provides features to specifically support editing JavaScript files, such as Microsoft Visual Studio and Microsoft Visual Studio Express. You can get Visual Studio Community 2013 for free.

Use browser developer tools

All modern browser provide built-in tools to enable debugging scripts. These tools can also be a tremendous help when writing scripts for CRM forms. These developer tools are frequently called F12 tools because that is the key used to open them. See W3Schools JavaScript Debugging for information about using these tools.

Use the developer tools to verify the syntax of scripts you will upload as script web resources. With these tools you can also get a better understanding of the object model you’re programming against. For example, when you write code to access specific objects in a form, you frequently need to access them by name. Rather than look up the name of the object in the form editor, use the console in the developer tools to interrogate the Xrm.Page object model to get the names of the attributes or controls you’re accessing. For example, if you want to access a specific subgrid control by name, you can use the browser developer tools console to write the following code.

Xrm.Page.ui.controls.get(
function(ctrl,i){
 if(ctrl.getControlType() == "subgrid")
  console.log(ctrl.getName()
  );
});

The names of all the subgrid controls will be written to the output pane of the console. This script leverages the capability to pass an anonymous delegate function to the get method found in collections as well as other methods found on objects to filter by type and to return the object name, such as Xrm.Page.ui control.getControlType and Xrm.Page.ui control.getName used in this example.

Important

CRM forms are composed of several frames. For the code to work in the console you must select the right frame. For CRM Online 2015 Update 1 forms, select the frame named ClientApiWrapper.aspx. For earlier releases use the frame named main.aspx.

Here are some more examples.

  • Show the names of all attributes in a form with their type

    Xrm.Page.getAttribute(
    function (att, i) {
     console.log(att.getName() + " : " + att.getAttributeType())
    });
    
  • Show the valid option values for optionset attributes

    Xrm.Page.getAttribute(
    function (att, i) {
     if (att.getAttributeType() == "optionset") {
      console.log(att.getName())
      var options = att.getOptions();
      var optionsLength = options.length;
      for (var i = 0; i < optionsLength; i++) {
       var option = options[i];
       console.log("   value: " + option.value + " Label: " + option.text)
      }
     }
    });
    

See Also

Write client application extensions
Open forms, views, dialogs and reports with a URL
Form scripting quick reference
Use JavaScript with Microsoft Dynamics CRM 2015
JavaScript libraries for Microsoft Dynamics CRM 2015
Developers guide to customization for Microsoft Dynamics CRM 2015
Use form and field events
Use the Xrm.Page object model
Write and debug scripts for CRM for tablets
Write scripts for composite attributes
Write scripts for business process flows
Write scripts for subgrids
Use execution context and the form event pipeline
Use an IFRAME and web resource controls on a form
Use the OData endpoint with Ajax and JScript web resources

© 2016 Microsoft. All rights reserved. Copyright