Conditionally Enable or Disable a Button/Command in your SharePoint 2010 custom Ribbon group

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

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:

Command=”Ribbon.Awesome.NavButton_CMD”
CommandAction=”javascript:Alert(‘My Awesome Button Was Clicked’);
**          EnabledScript=”javascript:SP.ListOperation.Selection.getSelectedItems().length == 1;”** />

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.

Results

If you select one (and only one) item in the list, your custom command will be enabled:

image

If you didn’t select or selected more than one item, the command will be disabled as such:

image image

Summary

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 :-)

Enjoy.

About Tobias Zimmergren

Hi, I'm Tobias. I plan, architect and develop software and distributed cloud services. Nice to meet you!

Comments