Sunday, December 11, 2011

Programmatically add Custom action in SharePoint 2010

If you need to create a ribbon button that applies to a specific list in a farm deployment scenario you must write some code in a feature event receiver to create an SPUserCustomAction class as so:
SPList list = web.Lists["SomeList"];SPUserCustomAction action = list.UserCustomActions.Add();action.Title = "Do Something";action.Description = "Sample ribbon button";action.ImageUrl = "/_layouts/images/centraladmin_backupandrestore_granularbackup_32x32.png";action.Location = "CommandUI.Ribbon.ListView";action.Sequence = 0;action.Url = "javascript:DoAction();";action.CommandUIExtension =@"<CommandUIExtension xmlns='http://schemas.microsoft.com/sharepoint/'> <CommandUIDefinitions> <CommandUIDefinition Location='Ribbon.Documents.Manage.Controls._children'> <Button Id='Sample.DoSomething.Button' Command='Sample.DoSomething' Image32by32='/_layouts/images/centraladmin_backupandrestore_granularbackup_32x32.png' Image16by16='/_layouts/images/centraladmin_backupandrestore_granularbackup_32x32.png' Sequence='0' LabelText='Do Something' Description='Sample ribbon button' TemplateAlias='o1' /> </CommandUIDefinition> </CommandUIDefinitions> <CommandUIHandlers> <CommandUIHandler Command='Sample.DoSomething' CommandAction='javascript:DoAction();' EnabledScript='javascript:EnableDoAction();'/> </CommandUIHandlers></CommandUIExtension>";
action.Update();