Export (0) Print
Expand All
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Use the Form Query String Parameter Tool to Demonstrate Setting Default Field Values in New Record Forms

Applies To: Microsoft Dynamics CRM 2011, Microsoft Dynamics CRM Online

Jim Daly
Microsoft Corporation

December, 2012

Summary

This article describes how to set default values for new Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online entity forms using query string parameters and a Microsoft Dynamics CRM 2011 managed solution. Install the managed solution and use it to verify what is possible and generate a URL or a JavaScript function that opens a new entity form with default values set for fields you specify.

The FormQueryStringParameterTool_1_0_0_0_managed.zip file contains the Form Query String Parameter Tool.

Applies To

Introduction

The Form Query String Parameter Tool demonstrates how to set default values for a new record form using query string parameters and provides a resource you can use to be more productive in evaluating whether this capability provides a solution for a requirement you need to implement. The following screenshot shows the user interface for the Form Query String Parameter Tool.

The Form Query String Parameter Tool

Before you continue reading, you should download this managed solution and install it. If you are not familiar with installing solutions, see How to Import or Export a Solution. Because it is a managed solution, you can easily uninstall it if you don’t need to use it. Other than some web resources, it adds no data to your system, introduces no dependencies, and doesn’t require any additional components. After you install it, the solution configuration page includes a button to launch the tool and instructions for how to use it. The Form Query String Parameter Tool requires Internet Explorer 9 or higher. Internet Explorer provides an easy way to programmatically copy text to the clipboard without depending on external plug-ins. This article does not provide details about how to use the tool. This article focuses on the following:

When to Set Default Form Values Using Query String Parameters

The Form Query String Parameter Tool is for developers or customizers to use when creating customizations or extensions that people will use with Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online. The tool lets you verify whether you can meet a requirement using this feature. However, you should also consider whether the ability to set values with query string parameters is the right approach. There may be other options that are easier or a better match for your requirements.

If you want to create a new related record, for example a new opportunity associated with an account, you can set default values using the attribute mappings exposed for the entity relationship. This allows you to copy values from the account record to a new opportunity record that was created in the context of the account when you click New Opportunity while viewing the opportunity list in the context of an account record. But you can only set values to data that already exists in the account record and the type of data must match. For more information, see Customize Entity and Attribute Mappings

If you just want to automatically create a new record with specific values, a process (workflow or dialog) provides an easier option. But with these methods the record is saved and the user has to find it and open it to add more information.

For some types of fields you can set default values by configuring the attribute. For example, with Option Set attributes you can choose a default value. A JavaScript developer can easily set default values using a function in a form Onload event handler. These are good solutions when you have just one consistent set of default values that you want everyone to use under all circumstances. But frequently default values that should be used change depending on different variations within entity definitions. These “sub-types” within an entity typically have an option set attribute on the form with a label such as Type or Category and options for users to choose from. When one or more of these appear in a form and require different default values to be set using scripts, it can become complicated pretty quickly.

Use query string parameters when you want to open a new form with default values set, but not save the record. You want to let the user change the default values or add more information if necessary before they save the record, or change their mind and close the window without saving. The key advantage that this technique provides is streamlining the data input process. Set values for the most common values and allow users to make just the modifications they need before saving the record. The goal is to make people more productive when using the system and reduce the need for training, especially when the business process rules are somewhat complex.

If your goal is just to streamline the creation of a new record with a specific set of default values, setting the values in the query string may provide a solution. Any time you find yourself documenting procedures to set certain form values, you may be able to replace those instructions with a URL so that the values are set automatically. Two possible ways to expose this to users are:

Add a URL to an intranet site or a web resource to create new records
In some organizations a specific process is documented and available to users via an intranet site. Or perhaps your organization uses web resources to provide instructions inline within a form. Rather than include procedural instructions for users to set fields to certain values, you can just provide a URL. Users can click a link with the URL to open a form with those values set.

Add a button to a ribbon or a web resource that will create a new record
Perhaps users frequently have to create certain categories of records with different default values set. For example, they may have high priority and low priority tasks that they create associated with a particular record, let’s say a contact. In this case you can add custom buttons to the ribbon or a web resource for each type of task. Configure this button to call a JavaScript function to open a new window with the values set in the URL. This way, with a single click, default values for that record can be set and the user can continue to fill in any additional details, or just click Save.

Limitations for Setting Default Values Using Query String Parameters

There are a number of limitations involved with setting values using query string parameters. The Form Query String Parameter Tool allows you to verify what is possible.

  1. Only those entities that can use the ribbon support this capability. This includes any custom entity plus the system entities in the following table.

     

    account (Account)

    appointment (Appointment)

    campaign (Campaign)

    campaignactivity (Campaign Activity)

    campaignresponse (Campaign Response)

    competitor (Competitor)

    connection (Connection)

    contact (Contact)

    contract (Contract)

    email (E-mail)

    fax (Fax)

    goal (Goal)

    goalrollupquery (Rollup Query)

    incident (Case)

    invoice (Invoice)

    lead (Lead)

    letter (Letter)

    list (Marketing List)

    metric (Goal Metric)

    opportunity (Opportunity)

    phonecall (Phone Call)

    pricelevel (Price List)

    product (Product)

    productpricelevel (Price List Item)

    queueitem (Queue Item)

    quote (Quote)

    recurringappointmentmaster (Recurring Appointment)

    salesliterature (Sales Literature)

    salesorder (Order)

    service (Service)

    serviceappointment (Service Activity)

    sharepointdocumentlocation (Document Location)

    sharepointsite (SharePoint Site)

    systemuser (User)

    site (Site)

    task (Task)

    team (Team)

    territory (Territory)

  2. Not every entity that uses the ribbon can set values with the URL. Some entities, such as contractdetail (Contract Line), invoicedetail (Invoice Product), quotedetail (Quote Product), and salesorderdetail (Order Product) are child records and the forms for these records contain hidden fields that connect them with a specific parent record. These hidden fields cannot be set in the URL and they cannot be added to the form. Without this data, the record cannot be saved.

  3. Not every field can be set using the query string. Some attributes, like CreatedBy can be added to a form but are not valid for create because the AttributeMetadata.IsValidForCreate property Value is false. Typically, this is because the value is set when the record is created and then becomes read-only. This isn’t really a limitation but it just makes sense not to set the value.

  4. Party list lookup fields can’t be set. This means the To or From fields for emails or the Regarding field for tasks can’t be set this way. The workaround is to pass the values through using a custom form parameter and then use script in the form Onload event to set the values. The Form Query String Parameter Tool detects any custom form parameters and allows you to test setting values for them.

    To create a custom form parameter, in the Form editor, in the Form Properties there is a Parameters tab where you can set custom parameters that the form accepts. If you use any parameters that are not expected, you get an error. Details about setting up custom query string parameters is available in the SDK topic Configure a Form to Accept Custom Querystring Parameters.

    For example, if you need to set the value of a Regarding field in a task record, you can configure three custom query string parameters like the ones in the table below.

     

    Name Type Description

    regarding_id

    UniqueId

    The ID of the record

    regarding_name

    String

    The name to display in the lookup

    regarding_type

    String

    The type of record



    The following code shows a SDK.AddTaskFromAccount.setRegardingOnLoad function that can be set in the Task form Onload event to use these values to set the Regarding field value.



    if (typeof SDK === 'undefined') {
     var SDK = {};
    }
    SDK.AddTaskFromAccount = {};
    
    SDK.AddTaskFromAccount.setRegardingOnLoad = function () {
     if (Xrm.Page.ui.getFormType() == 1) {
      var querystringParameters = Xrm.Page.context.getQueryStringParameters();
      if (((typeof querystringParameters.regarding_id != "undefined") && (querystringParameters.regarding_id != null)) &&
       ((typeof querystringParameters.regarding_name != "undefined") && (querystringParameters.regarding_name != null)) &&
       ((typeof querystringParameters.regarding_type != "undefined") && (querystringParameters.regarding_type != null))) {
    
       var regardingLookupValue = [];
       var regardingEntityReference = {};
       regardingEntityReference.id = querystringParameters.regarding_id;
       regardingEntityReference.name = querystringParameters.regarding_name;
       regardingEntityReference.entityType = querystringParameters.regarding_type;
       regardingLookupValue[0] = regardingEntityReference;
       Xrm.Page.getAttribute("regardingobjectid").setValue(regardingLookupValue);
    
      }
     }
    }
    
    
  5. There is a limitation based on the maximum length of URL that a browser will support. This varies from browser to browser, but the limit set by the Form Query String Parameter Tool is 2083 characters.

How the Form Query String Parameter Tool Works

The Form Query String Parameter Tool is not a sample so we are not publishing the code. Key interactions with Microsoft Dynamics CRM messages is done using libraries used by other samples. The remaining code is specific to the user interface provided by this tool and for the most part is not related to Microsoft Dynamics CRM. Yet if you are curious, after installing the managed solution you can use a tool like the Developer Toolkit for Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online or the WebResources Manager for Microsoft Dynamics CRM 2011 you can easily review the code to see how it works. The JavaScript code is not minimized or obfuscated. The code is designed to support all releases of Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online so it does not include some of the enhancements to the metadata messages introduced with Microsoft Dynamics CRM 2011 Update Rollup 12 and Microsoft Dynamics CRM December 2012 Service Update, even though there are several places where performance could be improved by doing so.

SDK.SOAP.FormQueryStringParameterTool.js is the JavaScript file that contains the logic for the FormQueryStringParameterTool.htm page. When the page is ready, after all the variables that reference page elements and event handlers are set, the page uses the SDK.Metadata.RetrieveAllEntities function from the SDK.Metadata.js library. This is the same library used in the SDK topic Sample: Retrieve Entity Metadata Using JavaScript. This function just retrieves the information about the entities and doesn’t contain information about individual attributes. EntityMetadata for entities that support query string parameters is cached and the list of available entities is generated so a user can select an entity.

When an entity is selected from the list the getForms function uses the SDK.REST.retrieveMultipleRecords function from the sdk.rest.js library. This is the same library used in the SDK topic Sample: Retrieve Multiple Records Using the REST Endpoint with JavaScript. The code uses SDK.REST.retrieveMultipleRecords function to query the SystemForm entity to retrieve the form definitions for that entity. The SystemForm.FormXml property contains the definitions of the forms. If an entity has more than one main form, the user must select a form, otherwise it is assumed that the single main form should be used.

When the form is selected, the FormXML is parsed for any <control> (FormXml) elements that contain a datafieldname attribute value. This value represents the attribute for the value displayed in the field. For each attribute, the code first checks the cache to see if this attribute has already been retrieved. If it hasn’t, the code uses the SDK.Metadata.RetrieveAttribute function from the sdk.metadata.js library to retrieve the metadata for that attribute. When the data is returned it is added to the cache and attached to a field object that will be used to render the form. At the same time, the field.isValid property is set using a setFieldisValid function using the attribute metadata as a parameter. When the attribute metadata for each field has been set the code is ready to render the form.

The form is rendered by generating <tr> elements and appending them to a table that is contained by a <div> to create a scrollable list. Fields and custom parameters are generated separately. Each row has four columns. The first is a checkbox to indicate whether the field or parameter should be included in the query string parameters for the URL to be generated. Second is the attribute display name or the name of a parameter. Third is a label for the type of attribute or parameter, and the fourth column is an HTML control that is appropriate for the type of attribute or parameter and how the attribute is formatted. If the field is not valid the text “This value cannot be set in the URL.” will be shown rather than a control. The renderControl function parses the attribute metadata and in some cases the classid value of the <control> (FormXml) to determine which control to create. The classid value is used to differentiate attribute types, such as Integer, that can be formatted in different ways. There are 13 different types of field controls and 10 different controls for custom parameters. The parameterControl function directly generates controls for each type of parameter using a switch statement for the type of parameter. The definitions for the attribute and parameter controls are about half the entire library.

Most of the attribute controls do not require any information other than the attribute metadata. The only exceptions are when an Integer attribute is formatted as a time zone or a language. In these cases the SDK.SOAP.FormQueryStringParameterTool.js library provides the SDK.SOAP.getAllTimeZonesWithDisplayName and SDK.SOAP.retrieveProvisionedLanguages functions. These functions call the GetAllTimeZonesWithDisplayNameRequest and RetrieveProvisionedLanguagesRequest messages respectively using the SOAP endpoint for web resources. The values retrieved by these messages are used to populate the control options with the same option values used in the application.

Each control contains a getValue and getData method. The getValue method generates the query string parameter for each field. The getData method returns just the data value in the form. The getData method is used when generating the JavaScript function that can be copied to the user’s clipboard.

Each control includes some validation logic so that a message is displayed if invalid data is entered. Each control also implements an appropriate event handler so that when the user interacts with it the control will call the select method on the containing row. The select method will mark the row as selected and call the calculateExtraQS function which will refresh the URL and the function text that is displayed or would be available when the Copy Function button is pressed. If the user unchecks the checkbox for each row, it is removed from the selected attributes or parameters.

Lookup controls are broken out into three types: Customer, Lookup, and Owner. Each of these controls launches a simple lookup dialog that uses the customerDialog.htm, lookupDialog.htm or ownerDialog.htm respectively. Each of these dialogs work the same way, the only difference is the type of entities that they search. Customer and Owner dialogs allow the choice of two possible types of records while a Lookup dialog will allow only one. These dialogs provide a simple grid populated by the first 50 records for each type which can be filtered based on their primary attribute value. The dialogs use the SDK.REST.retrieveMultipleRecords function from the sdk.rest.js library. These dialogs each include a lot of the same code, so there is an opportunity to merge them into a single lookup dialog for better efficiency and improved maintainability. The following screenshot shows the Lookup dialog when used to set the Primary Contact field for an account.

Lookup Dialog for Contact

After the form is rendered and the user has made their choices for the values they want to set using query string parameters, the only remaining actions are the three buttons in the top part of the user interface. The Test URL button uses window.open with the URL displayed. The Copy Url button copies the contents of the URL displayed to the user’s clipboard using the clipboardData.setData method. The Copy function button also uses the clipboardData.setData method to copy a generated JavaScript function to the user’s clipboard.

The text of the JavaScript function is generated by the data in the form and includes code to use the Xrm.Utility.openEntityForm method if it exists. Because the Xrm.Utility namespace was included in Microsoft Dynamics CRM 2011 Update Rollup 8, not all organizations may have it. Or if the function is being used in another application, the Xrm.Utility functions may not be present. If the Xrm.Utility object is not found it will use window.open instead. The code includes a reference to the specific formid representing the form definition used when generating it. The function also depends on the Xrm.Page.context to get an organization root URL using either the deprecated getServerUrl method or the getClientUrl added with Microsoft Dynamics CRM 2011 Update Rollup 12 or Microsoft Dynamics CRM December 2012 Service Update if it exists. If the function needs to be used from outside of Microsoft Dynamics CRM, that portion of the function will need to be replaced with a URL that is appropriate for the organization. The following code represents an example of a JavaScript function generated for a Lead entity main form with the subject, firstname, lastname, companyname, emailaddress1, description, and leadsourcecode values prepopulated. At the bottom is an example showing how to use the function.

function openNewLead(subject, firstname, lastname, companyname, emailaddress1, description, leadsourcecode)
{
///<summary>Opens a window for a new Lead record using the Information form.</summary>
///<param name="subject" optional="false" type="String">
///Subject associated with the lead.
///</param>
///<param name="firstname" optional="false" type="String">
///First name for the lead.
///</param>
///<param name="lastname" optional="false" type="String">
///Last name for the lead.
///</param>
///<param name="companyname" optional="false" type="String">
///Name of the company with which the lead is associated.
///</param>
///<param name="emailaddress1" optional="false" type="String">
///First e-mail address for the lead.
///</param>
///<param name="description" optional="false" type="String">
///Description of the lead.
///</param>
///<param name="leadsourcecode" optional="false" type="Number">
///Source of the lead. Expected value is a number that represents a valid option value for this attribute.
///</param>
if ((typeof Xrm != "undefined") && (typeof Xrm.Utility != "undefined"))
{
var p = {};
p.formid = "9886ead0-4fcc-4747-9a18-08e7a9a6de71"
p.subject = subject;
p.firstname = firstname;
p.lastname = lastname;
p.companyname = companyname;
p.emailaddress1 = emailaddress1;
p.description = description;
p.leadsourcecode = leadsourcecode;
Xrm.Utility.openEntityForm("lead", null, p);
}
else
{
var features = "location=no,menubar=no,status=no,toolbar=no,resizable=yes";
var extraqs = ["formid=9886ead0-4fcc-4747-9a18-08e7a9a6de71",
"subject=" + subject,
"firstname=" + firstname,
"lastname=" + lastname,
"companyname=" + companyname,
"emailaddress1=" + emailaddress1,
"description=" + description,
"leadsourcecode=" + leadsourcecode]
var url = Xrm.Page.context.getServerUrl();
if (url.match(/\/$/)) {
url = url.substring(0, url.length - 1);
}
if (typeof Xrm.Page.context.getClientUrl != "undefined") {
url = Xrm.Page.context.getClientUrl();
}
window.open(url + "/main.aspx?etn=lead&pagetype=entityrecord&extraqs=" + encodeURIComponent(extraqs.join("&")), "_blank", features, false);
}

}

//Example:
//openNewLead("Lead Topic","Jim","Daly","Contoso","someone@example.com","This is the description for the lead.",4);

Conclusion

 

The ability to set default values using query string parameters can be useful in a variety of situations, but it has some limitations. The Form Query String Parameter Tool is a managed solution that can help you understand what is possible and help you be more productive using this feature because it generates a properly formatted URL or a JavaScript function.

Send comments about this article to Microsoft.

Community Additions

Show:
© 2014 Microsoft