Disabling a SharePoint ribbon control based on user list permissions
I had a requirement to create a button on a SharePoint list ribbon that was only enabled for Contributors of that list. The post will explain how to set that up in javascript using the SharePoint 2010 Client Object Model.
I assume that you already have knowledge of working with the Ribbon in SharePoint 2010 and in particular using javascript page components. The snippets assume you have the rest of the ribbon definition in place and an existing page component file. If you don’t, I’d recommend you head on over to Chris O’Brien’s great articles on ribbon customisations.
Creating the button.
First up we need to declare the button we wish to disable or rather enable based on the users permission.
<Button Id="Ribbon.MyButton.Button" Alt="Ribbon.MyButton.Button" Command="Ribbon.MyButton.Button.Configure" Image16by16="/_layouts/images/splogo.gif" Image32by32="/_layouts/images/settingsIcon.png" LabelText="Configure" Sequence="10" TemplateAlias="o1" ToolTipTitle="Configure" ToolTipDescription="Configure merge" />
The above definition is just that of an ordinary ribbon button, nothing special is declared in there.
Javascript page component.
The next step is to modify our page component file.
canHandleCommand: function (commandId) { if(commandId === 'Ribbon.MyButton.Button.Configure') { if(userIsContrib == null) { checkUserIsContrib();
return false; } else { return userIsContrib; } } else { return false; } },
... var userIsContrib = null; function checkUserIsContrib() { var context = SP.ClientContext.get_current(); var web = context.get_web(); list = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList()); context.load(list,'EffectiveBasePermissions'); context.executeQueryAsync(Function.createDelegate(this, gotUserIsContrib), Function.createDelegate(this, failedUserIsContrib)); } function gotUserIsContrib() { // update the variable based on the users permission userIsContrib = list.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems); //Update the UI RefreshCommandUI(); } function failedUserIsContrib() { alert("failed failedUserIsContrib"); }
Because we want to check the user permissions asynchronously, we need to set userIsContrib initially to null. This will disable the button for all users while the checkUserIsContrib() method goes off and checks the users permissions.
After checking the users permissions and settings the flag appropriately we call RefreshCommandUI() which will again cause canHandleCommand to be run again. This time it will return the value that was set in the gotUserIsContrib() method. As a value has now been set on userIsContrib, no more checks against the server will be made by any other calls to RefreshCommandUI.
References.
Posted in SharePoint