Defaulting a Lookup field via a REST query at Form Load

Here’s some sample code that demonstrates how to dynamically determine the GUID of a related record and use that to default a lookup field on a CRM form on form load.

In this example I have a dummy Contact record called “new contact” which I want to default onto the Phone Call form each time a new Phone Call record is created. 

i.e when I click New Phone Call on the ribbon…

image

…. I want to see this:

image

note: I have also re-configured the Phone Call entity’s Direction field so that “Incoming” is the default.  The idea being that the user is launching the Phone Call form to record an incoming call from an unknown caller.

Defaulting in a dummy Contact may some an unusual scenario but it is not uncommon to utilise a dummy record when dealing with anonymous callers or when wanting to defer the collection of contact details until later in the process.   In a Call Centre environment for example you will not achieve desired efficiencies if you except having to manually create new Contact records before being able to create Phone Calls, Cases, Opportunities, etc or before being able to convert Phone Calls to Cases or Opportunities (I expand on this Call Centre scenario in my next post).

Anyway, here’s how to make this work…

There are 2 parts to this.  Firstly, we need to find out the GUID of the Contact record that we want to default on to our Phone Call.   You could figure this out manually and then hardcode the GUID but then your code will not be transportable across environments.   Instead in this example I have hardcoded only the name of the contact (we can easily create this Contact in each environment, it’s just data).  My dummy Contact is called “new contact” and I use the REST oData endpoint to locate that record’s GUID by searching on that name (An alternative approach would be to  store the GUID in a configuration entity and then use REST to query for the GUID from there, however the same coding approach applies).   And  then secondly, once we know the GUID it’s a relatively simple matter of doing a SetValue to populate the field on the form.

Here’s the jscript:

// Set lookup value of a field 
function SetLookupValue(fieldName, id, name, entityType) { 
    if (fieldName != null) { 
        var lookupValue = new Array(); 
        lookupValue[0] = new Object(); 
        lookupValue[0].id = id; 
        lookupValue[0].name = name; 
        lookupValue[0].entityType = entityType; 
        Xrm.Page.getAttribute(fieldName).setValue(lookupValue); 
    } 
} 

function GetDefaultContactGUID() { 
    if (Xrm.Page.ui.getFormType() == 1) { 
        // Get the CRM URL 
        var serverUrl = Xrm.Page.context.getServerUrl(); 

        // Cater for URL differences between on premise and online 
        if (serverUrl.match(/\/$/)) { 
            serverUrl = serverUrl.substring(0, serverUrl.length - 1); 
        } 

        // Specify the ODATA end point (this is the same for all CRM 2011 implementations) 
        var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc"; 

        // Specify the ODATA entity collection (this needs to be specific to your entity) 
        var ODATA_EntityCollection = "/ContactSet"; 

        // Specify the ODATA filter 
        var ODATA_Query = "?$select=ContactId&$filter=FullName%20eq%20\'new%20contact\'&$top=1"; 

        // Build the URL 
        var ODATA_Final_url = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + ODATA_Query; 

        //Calls the REST endpoint 
        $.ajax({ 
            type: "GET", 
            contentType: "application/json; charset=utf-8", 
            datatype: "json", 
            url: ODATA_Final_url, 
            beforeSend: function (XMLHttpRequest) { 
                //Specifying this header ensures that the results will be returned as JSON.      
                XMLHttpRequest.setRequestHeader("Accept", "application/json"); 
            }, 
            success: function (data, textStatus, XmlHttpRequest) { 
                //This function will trigger asynchronously if the Retrieve was successful 
                SetLookupValue("from", data.d.results[0].ContactId, "new contact", "contact"); 
            }, 
            error: function (XmlHttpRequest, textStatus, errorThrown) { 
                //This function will trigger asynchronously if the Retrieve returned an error 
                alert("ajax call failed"); 
            } 
        }); 
    } 
}

The code snippet above contains 2 functions.  The “SetLookupValue” function is used to default the lookup field.  It is called by the 2nd function “GetDefaultContactGUID” which is where the REST query is constructed.

To deploy the above you need to load it into a jscript web resource and then reference that web resource on the Phone Call form and add a call in the Phone Call’s On Load event to the GetDefaultContactGUID function.   You will also need to upload json and jquery supporting  web resources and make sure they are specified in the order shown below:

image 

If you’re not sure what I’m talking about when I mention json and jquery web resources have a read of this earlier post.

That’s it, the code is well commented so have a read of that to understand the syntax. 

A solution file containing the above web resources and minor change to the Phone Call entity is available here for download.   Hope this helps someone.

G.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s