May 6, 2013

CRM 2011 ribbon button data dependency

 

The problem

It is not uncommon for a button in the ribbon to be enabled / disabled based on data from another (probably related) entity, or fields from the current entity which are not on the form.

In such cases it is necessary to query the organization service in order to retrieve the required data.

The most commonly used AJAX requests by default are asynchronous. This means that a callback function is called with the response as argument.
$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});
image

This method is great in general, because it doesn’t block the UI thread in the browser. Although when used in functions determining if a ribbon button should be enable they won’t work. The obvious reason is that the callback is called after the base function has finished. So the base function that is supposed to return the yes/no answer does not have access to the results.
image

 

The solution

image

This synchronous behavior is trivial to achieve.

var jsonResponse= $.parseJSON($.ajax({
            type: "GET",
            dataType: "json",
           
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet?QUERY
   
        cache: false,
            async: false
        }).responseText);

Setting the async parameter to false will cause the query to be synchronous. It will block the UI thread, but in most cases for such a short period of time it’s barely noticeable.

After retrieving the jsonResponse all you need to do is to parse it and return true / false from the base function.