My prevoius posts(here and here) described how to create a custom ribbon action and how to retrieve selected list items in SharePoint 2010. Right now I’ll show You one more thing that can be usefull while creating Your own ribbon buttons – how to enable or disable ribbon button using defined by You conditions.

“EnabledScript” is a property of CommandUIHandler. It allows You to set if the ribbon button should be enabled(available to click for the user) or disabled(greyed out). To set this property dynamically You can use the script shown below:


var EnableDisable = function() {
 this.clientContext = SP.ClientContext.get_current();
 this.selectedItems = SP.ListOperation.Selection.getSelectedItems(this.clientContext);
 var ci = CountDictionary(selectedItems);
 return (ci > 0);
 };
 EnableDisable();

In the script I check if user has selected one or more list items. If yes, then method returns true, otherwise false.

Full command should be placed in the elements.xml and should look like this:


<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<CustomAction

Id="CAAlertRibbonButton"
RegistrationId="100"
RegistrationType="List"
Location="CommandUI.Ribbon"
Sequence="5"
Title="Alert Ribbon Button">

<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.List.Settings.Controls._children">
<Button
Id="AlertRibbonButtonId"
Alt="Alert Ribbon Button"
Sequence="5"
Command="CMDAlertRibbonButton"
Image32by32="/_layouts/images/menulistsettings.gif"
Image16by16="/_layouts/images/itdcl.gif"
LabelText="Alert Ribbon Button"
TemplateAlias="o1" />
</CommandUIDefinition>
</CommandUIDefinitions>

<CommandUIHandlers>
<CommandUIHandler
Command="CMDAlertRibbonButton"
EnabledScript="javascript: var EnableDisable = function() {
 this.clientContext = SP.ClientContext.get_current();
 this.selectedItems = SP.ListOperation.Selection.getSelectedItems(this.clientContext);
 var ci = CountDictionary(selectedItems);
 return (ci > 0);
 };
 EnableDisable();"
CommandAction="javascript: alert('My Command!');" />
</CommandUIHandlers>

</CommandUIExtension>
</CustomAction>
</Elements>