Conditionally Enable or Disable a Button/Command in your SharePoint 2010 custom Ribbon group
In most of my recent projects I’ve been required to hook up some custom functionality and add custom forms, pages and Web Parts. Some of the forms and pages I designed needed to be launched from the Ribbon menu, which of course is contextual. This basically means that when you visit a specific list which inherits from a specific content type, we can choose to display our custom Ribbon controls. One of the most common requirements I bumped into was having some kind of conditional check whether to enable or disable the button based on a set of conditions.
In your Ribbon XML for the CommandUIHandler there’s a property called “EnabledScript” which is a tag that enables you to enter a validation script to determine whether or not the ribbon button should be enabled. In my case I need to disable the custom Ribbon-controls if one item is selected, but otherwise always disable it.
Use the following snippet from the SP.ListOperation, which contains the Selection.getSelectedItems method:
It’s really only the last line that is of interest here since that’s where the script magic happens to determine if the control should be enabled or not.
MSDN have some nice samples in one of their articles over here.
If you select one (and only one) item in the list, your custom command will be enabled:
If you didn’t select or selected more than one item, the command will be disabled as such:
I know many people have been struggling with the Ribbon and making it behave. In this article I simply wanted to highlight one of the very common tasks I’ve seen developers looking for and trying to achieve in some of the last few projects I’ve been involved.
Since my awesome mate Wictor covered a bunch of awesome posts about the Ribbon, I’m not going to dive into any more details than so :-)