Search code examples
sharepoint-2010custom-action

SharePoint 2010 CustomActions: EnabledScript and executeQueryAsync


I have a CustomAction which adds a button to the ribbon. My CommandHandler specifies an EnabledScript which determines when the button should be enabled/disabled. See below:

<CommandUIHandlers>
 <CommandUIHandler
  Command="CreateSiteGroup"
  CommandAction="javascript:CreateCreateSiteGroup();" 
  EnabledScript="javascript:CreateCreateSiteGroupButtonEnabled();">
 </CommandUIHandler>
</CommandUIHandlers>

The CreateCreateSiteGroupButtonEnabled() function just needs to return a true/false, however I've had to use the executeQueryAsync function inside it so that I can load the properties of some objects. Obviously, because now the method is executing asynchronously, the true/false value is never returned.

My code looks like this:

function CreateContributorsGroupButtonEnabled() {
 this.clientContext = new SP.ClientContext.get_current();
 this.web = this.clientContext.get_web();
 this.clientContext.load(this.web, "Title");
 this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnContextSucceeded), Function.createDelegate(this, this.OnQueryFailed));
}

function OnContextSucceeded() {
 this.siteGroups = web.get_siteGroups();
 this.clientContext.load(this.siteGroups);
 this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnQuerySucceeded), Function.createDelegate(this, this.OnQueryFailed));
}

function OnQuerySucceeded() {
 var contributorsGroupTitle = String.format("{0} Contributors", web.get_title());
 var siteGroupEnumerator = this.siteGroups.getEnumerator();

 while (siteGroupEnumerator.moveNext()) {
  var siteGroup = siteGroupEnumerator.get_current();

  if (siteGroup.get_title().toLowerCase() == contributorsGroupTitle.toLowerCase())
   return false;
 }

 return true;
}

Does anyone know how I can return the true/false back from the async function? Or alternatively, how I can tell whether a site group with a specific name already exists without using executeQueryAsync?


Solution

  • When using async calls to check if a button has to be available in the ribbon you have to tell the ribbon when the async method is finished to check if the status of the button has to be updated.

    In the Core.js you can find a function called RefreshCommandUI(). This function causes the Ribbon to refresh and EnableScript functions get called on the ribbon buttons.

    In the code a variable have to be set to keep track of the status(enable or disable) of the button.

    Regards, Anita