Looping through a SharePoint List Column with jQuery and replacing a GUID with a name from CRM 2011

This is a very specialized piece of code, but it came together nicely, so I thought I would share it.

I have a SharePoint List that has a bunch of Microsoft CRM 2011 Contact GUIDs in it. Some columns have one GUID and others have multiple GUIDs separated by semicolons. My goal was: when a user visits the default view for this list, the GUIDs are looked up agains CRM and displayed as the contact’s full name. I wrote the following code to do just that. The 4th, 5th and 10th columns has guide in them. I use this method to loop through the column.

$('table.ms-listviewtable td:nth-child(4),table.ms-listviewtable td:nth-child(5),table.ms-listviewtable td:nth-child(10)').each(function () {
        var guids = $(this).text().split(";");
        var names = ''
        $.each(guids, function () {
            var guid = this;
            var serverUrl = "http://crmserver.company.com"
            var ODATA_ENDPOINT = "/Organization/XRMServices/2011/OrganizationData.svc";
            var ODATA_EntityCollection = "/ContactSet(guid'" + guid + "')";
            var URL = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection
            $.ajax({
                type: "GET",
                contentType: "application/json",
                datatype: "json",
                async: false,
                url: URL,
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    XMLHttpRequest.setRequestHeader("Content-Type", "application/json")
                },
                success: function (data, textStatus, XmlHttpRequest) {
                    names = names + data.d.FullName + ","
                }
            });
        });
        $(this).text(names.substring(0, names.length - 1));
    });

Line 1: is the jQuery selector for all the columns that have GUIDs. And we loop through each of them.
Line 2: splits the contents of the column.
Line 4: loops through the all the GUIDs in each row/column
Lines 5-9: are setting up the CRM 2011 REST url for the ajax call
Lines 10-24: query the Microsoft CRM 2011 rest endpoint with the contact’s GUID and assign the full name to a variable
Line 25: displays the full name instead of the GUID.

Some slim code that works pretty well.

, ,

Comments are closed.

Powered by WordPress. Designed by WooThemes