Monday, 18 January 2010

Customizing the ribbon (part 1) – creating tabs, groups and controls

In this article series:

  1. Customizing the ribbon – creating tabs, groups and controls (this post)
  2. Adding ribbon items into existing tabs/groups
  3. Ribbon customizations - dropdown controls, Client Object Model and JavaScript Page Components
  4. Customize the ribbon programmatically from web parts and field controls

Some good posts are starting to appear on SharePoint 2010 ribbon customization now, and over the next couple of articles I want to cover some key things you might want to do with the ribbon when developing your solutions. Diving straight in then, some ribbon fundamentals:

  • Ribbon elements must be defined in declarative XML with the CustomAction tag - even if you will actually use code to manipulate them (e.g. make visible, enable/disable etc.)
  • The “control hierarchy” is ribbon > tab > group > controls – we’ll explore all these in this post
  • Individual buttons/controls do not appear and disappear on the ribbon. This is a key ribbon principle, to avoid the “I’m sure this button was here yesterday!” effect - instead, depending on the context:
    • Entire tabs can be shown/hidden
    • Individual controls can be enabled/disabled
  • It’s not possible to add custom controls to the ribbon e.g. a custom .ascx/server control. The list of controls defined by the ribbon can be found here in the MSDN docs, and includes things like Button, Checkbox, Color Picker, Combo Box, Dropdown, Textbox, Toggle Button etc, but also some funky ones like Spinner, Split Button and Flyout Anchor (definitions of these exotic varieties can be found in the documentation). Flyout Anchor is particularly interesting as it takes XML as a datasource and can be used to build interesting “pickers” e.g. with images – I’ll hopefully cover this in detail in a future post
  • The definitions for the out-of-the-box ribbon elements are split across several files in the SharePoint root, with TEMPLATE\GLOBAL\XML\CMDUI.XML being the main one. You will likely spend significant time in this file looking for examples similar to what you’re building.

It’s also worth giving special consideration to how JavaScript plays with the ribbon – it’s used frequently since much happens on the client. Depending on the scope you need for your JavaScript (e.g. every page vs. a couple) and the complexity of what you’re doing, JavaScript can be supplied in a few ways:

  • By embedding it into your declarative XML (via a separate CustomAction with a new ‘Location="ScriptLink"’ attribute) – this post uses this approach, though later in the series I’ll show the next option
  • By deploying a custom .js file which contains some object-oriented JavaScript. This is the approach used for more complex customizations, where you need to create an object which is the client-side “page component” in addition to your XML. The page component supplies the implementation for how your custom ribbon elements should handle various events (“commands”) . This object needs to be derived from the existing CUI.Page.Component object defined in CUI.js. As with any JavaScript file, you then have a couple of options for referencing it on your page.

In this post we’ll show adding JavaScript the first way, though later in the series I’ll show the use of a page component.

Example - creating a new custom tab

This is a fairly in-depth example, since by necessity it also covers creating custom groups and controls too. Also, to kill two birds with one stone, I thought it would be good to look at the new ‘notifications’ and ‘status’ frameworks in the Client Object Model for passing messages back to the user in your SharePoint app. First we’ll walk through what my custom tab looks like, then what it actually does. I have a tab titled “Chris’s custom tab” with 3 groups (“Notification messages”, “Add status messages” and “Remove status messages”) each with some buttons of different sizes and images in them:

CustomRibbonTab

Clicking the ‘Notify hello’ button adds a transient message in the notifications area (fades in from right and stays for 5 seconds by default):

SP.UI.Notify

Clicking the ‘Info status’ button shows a status message this time, in the default color (this remains on screen until removed with another API call):

SP.UI.Status_Info

Clicking the ‘Warning status’ button shows a status message of a different color to indicate severity, I chose red:

SP.UI.Status_Warning

You might also have noticed the ‘remove status’ buttons have become enabled when a status message is present – such client-side checks can be done by linking a ‘CommandUIHandler’ with an ‘EnabledScript’ attribute, as we’re about to see.

So what XML is required to get that? Well before you scroll through, note that I’ve taken the complex route with some of the declarations so that my example is as informative as possible – most samples I’ve seen so far simply add a button or two in a single group and don’t specify the "’group template” details which determines how the controls in the group get laid out. This is fine for a button or two as you can just reference an out-of-the-box group template, but if you want to do anything different you’re a bit stuck so hopefully this is good documentation:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
   Id="COB.SharePoint.Ribbon.CustomTab"
   Location="CommandUI.Ribbon" RegistrationType="List" RegistrationId="101">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Tabs._children">
          <Tab Id="COB.SharePoint.Ribbon.CustomTab" Title="Chris's custom tab" Description="Groups and controls will go in here" Sequence="501">
            <Scaling Id="COB.SharePoint.Ribbon.CustomTab.Scaling">
              <MaxSize Id="COB.SharePoint.Ribbon.CustomTab.NotificationGroup.MaxSize"
                       GroupId="COB.SharePoint.Ribbon.CustomTab.NotificationGroup"
                       Size="OneLarge"/>
              <Scale Id="COB.SharePoint.Ribbon.CustomTab.NotificationGroup.Scaling.CustomTabScaling"
                     GroupId="COB.SharePoint.Ribbon.CustomTab.NotificationGroup"
                     Size="OneLarge" />
              <MaxSize Id="COB.SharePoint.Ribbon.CustomTab.StatusGroup.MaxSize"
                      GroupId="COB.SharePoint.Ribbon.CustomTab.StatusGroup"
                      Size="TwoMedium"/>
              <Scale Id="COB.SharePoint.Ribbon.CustomTab.StatusGroup.Scaling.CustomTabScaling"
                     GroupId="COB.SharePoint.Ribbon.CustomTab.StatusGroup"
                     Size="TwoMedium" />
              <MaxSize Id="COB.SharePoint.Ribbon.CustomTab.RemoveStatusGroup.MaxSize"
                      GroupId="COB.SharePoint.Ribbon.CustomTab.RemoveStatusGroup"
                      Size="TwoLarge"/>
              <Scale Id="COB.SharePoint.Ribbon.CustomTab.RemoveStatusGroup.Scaling.CustomTabScaling"
                     GroupId="COB.SharePoint.Ribbon.CustomTab.RemoveStatusGroup"
                     Size="TwoLarge" />
            </Scaling>
            <Groups Id="COB.SharePoint.Ribbon.CustomTab.Groups">
              <Group
                Id="COB.SharePoint.Ribbon.CustomTab.NotificationGroup"
                Description="Contains notification items"
                Title="Notification messages"
                Sequence="52"
                Template="Ribbon.Templates.OneLargeExample">
                <Controls Id="COB.SharePoint.Ribbon.CustomTab.NotificationGroup.Controls">
                  <Button
                    Id="COB.SharePoint.Ribbon.CustomTab.NotificationGroup.Notify"
                    Command="COB.Command.Notify"
                    Sequence="15" Image16by16="/_layouts/images/NoteBoard_16x16.png" Image32by32="/_layouts/images/NoteBoard_32x32.png"
                    Description="Uses the notification area to display a message."
                    LabelText="Notify hello"
                    TemplateAlias="cust1"/>
                </Controls>
              </Group>
              <Group
                Id="COB.SharePoint.Ribbon.CustomTab.StatusGroup"
                Description="Contains 'add status' items"
                Title="Add status messages"
                Sequence="49"
                Template="Ribbon.Templates.TwoMediumExample">
                <Controls Id="COB.SharePoint.Ribbon.CustomTab.StatusGroup.Controls">
                  <Button
                   Id="COB.SharePoint.Ribbon.CustomTab.StatusGroup.AddStatusInfo"
                   Command="COB.Command.AddStatusInfo" 
                   Sequence="17" Image16by16="/_layouts/images/info16by16.gif" Image32by32="/_layouts/images/info16by16.gif"
                   Description="Uses the status bar to display an info message."
                   LabelText="Info status"
                   TemplateAlias="cust2"/>
                  <Button
                    Id="COB.SharePoint.Ribbon.CustomTab.StatusGroup.AddStatusWarning"
                    Command="COB.Command.AddStatusWarning"
                    Sequence="17" Image16by16="/_layouts/images/warning16by16.gif" Image32by32="/_layouts/images/warning32by32.gif"
                    Description="Uses the status bar to display a warning message."
                    LabelText="Warning status"
                    TemplateAlias="cust3"/>
                </Controls>
              </Group>
              <Group
                Id="COB.SharePoint.Ribbon.CustomTab.RemoveStatusGroup"
                Description="Contains 'remove status' items"
                Title="Remove status messages"
                Sequence="52"
                Template="Ribbon.Templates.TwoLargeExample">
                <Controls Id="COB.SharePoint.Ribbon.CustomTab.RemoveStatusGroup.Controls">
                  <Button
                    Id="COB.SharePoint.Ribbon.CustomTab.RemoveStatusGroup.RemoveLastStatusButton"
                    Command="COB.Command.RemoveLastStatus"
                    Sequence="15" Image16by16="/_layouts/images/warning16by16.gif" Image32by32="/_layouts/images/CRIT_32.GIF"
                    Description="Removes the last message from the status bar."
                    LabelText="Remove last status message" 
                    TemplateAlias="cust4"/>
                  <Button
                    Id="COB.SharePoint.Ribbon.CustomTab.RemoveStatusGroup.RemoveAllStatusButton"
                    Command="COB.Command.RemoveAllStatus"
                    Sequence="15" Image16by16="/_layouts/images/warning16by16.gif" Image32by32="/_layouts/images/CRIT_32.GIF"
                    Description="Removes all messages from the status bar."
                    LabelText="Remove all status messages"
                    TemplateAlias="cust5"/>
                </Controls>
              </Group>
            </Groups>
          </Tab>
        </CommandUIDefinition>
        <CommandUIDefinition Location="Ribbon.Templates._children">
          <GroupTemplate Id="Ribbon.Templates.OneLargeExample">
            <Layout Title="OneLarge" LayoutTitle="OneLarge">
              <Section Alignment="Top" Type="OneRow">
                <Row>
                  <ControlRef DisplayMode="Large" TemplateAlias="cust1" />
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>
        </CommandUIDefinition>
        <CommandUIDefinition Location="Ribbon.Templates._children">
          <GroupTemplate Id="Ribbon.Templates.TwoMediumExample">
            <Layout Title="TwoMedium" LayoutTitle="TwoMedium">
              <Section Alignment="Top" Type="TwoRow">
                <Row>
                  <ControlRef DisplayMode="Medium" TemplateAlias="cust2" />
                </Row>
                <Row>
                  <ControlRef DisplayMode="Medium" TemplateAlias="cust3" />
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>
        </CommandUIDefinition>
        <CommandUIDefinition Location="Ribbon.Templates._children">
          <GroupTemplate Id="Ribbon.Templates.TwoLargeExample">
            <Layout Title="TwoLarge" LayoutTitle="TwoLarge">
              <Section Alignment="Top" Type="OneRow">
                <Row>
                  <ControlRef DisplayMode="Large" TemplateAlias="cust4" />
                  <ControlRef DisplayMode="Large" TemplateAlias="cust5" />
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="COB.Command.Notify"
          CommandAction="javascript:
          
          var notificationId = SP.UI.Notify.addNotification('Hello from the notification area'); 
          " />
        <CommandUIHandler
          Command="COB.Command.AddStatusInfo"
          CommandAction="javascript:
          
          var statusId = SP.UI.Status.addStatus('Quite important status message');
          latestId = statusId;
          enableRemoveStatusButton();
          " />
        <CommandUIHandler
          Command="COB.Command.AddStatusWarning"
          CommandAction="javascript:
          
          var statusId = SP.UI.Status.addStatus('Very important status message');
          SP.UI.Status.setStatusPriColor(statusId, 'red');
          latestId = statusId;
          enableRemoveStatusButton();
          " />
        <CommandUIHandler
          Command="COB.Command.RemoveLastStatus" EnabledScript="javascript:enableRemoveStatusButton();"
          CommandAction="javascript:
          
          SP.UI.Status.removeStatus(latestId);
          latestId = '';
          enableRemoveStatusButton();" />
        <CommandUIHandler
          Command="COB.Command.RemoveAllStatus" EnabledScript="javascript:enableRemoveStatusButton();"
          CommandAction="javascript:
          
          SP.UI.Status.removeAllStatus(true);
          latestId = '';
          enableRemoveStatusButton();" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
  <CustomAction Id="COB.Command.RemoveLastStatus.CheckEnable" Location="ScriptLink"
             ScriptBlock="
                var latestId = '';
                          
                function enableRemoveStatusButton() 
                { 
                  if (latestId == '')
                  {
                    return false;
                  }
                  else
                  {
                    return true;
                  }
                }"
                />
</Elements>

Some key points, following the XML sequence:

  • CustomAction:
    • Notice I have two CustomAction elements – one for the ribbon elements, the other for some JavaScript I want to use with my custom elements. This is the approach mentioned earlier where the JavaScript is effectively embedded in your XML [sidenote: you don’t have to be doing ribbon customization to leverage this approach - this use of CustomAction is a new way of providing JavaScript to the page, just be aware it will be added for every page in the Feature scope (e.g. site/web) and you have no control over where in the page it will be injected. It does give you the ability to take away your JavaScript via Feature deactivation though, which could be useful for many scenarios).
      • The Location attribute of CustomAction for ribbon elements should always be “CommandUI.Ribbon”
      • The Location attribute of CustomAction for script is a new value, “ScriptLink”
    • My ribbon tab is scoped to document libraries only – this is courtesy of the RegistrationType="List" RegistrationId="101" attributes (which is exactly what you did when targeting a CustomAction to doc libs in SharePoint 2007, no change there)
    • When targeting a list in this way, RegistrationId refers to the list template ID (e.g. generic list = 100. document library = 101 etc. – here’s a full list of list template IDs for 2007, there could be a couple of new ones in 2010) – it is not possible to declaratively target a list by e.g. GUID or URL. So consider that this could drive you to create a list template when you otherwise might not have.
    • Other options for the RegistrationType continue to be “ContentType”, “ProgID” and “FileType”, but I’m pretty sure only “List” can be used for ribbon elements, but I’ve not tested that yet so I reserve the right to be wrong! If you want a different scope level, you would omit the RegistrationType and RegistrationId attributes and use code such as SPRibbon.MakeTabAvailable() to conditionally show the ribbon. More on this later in the series when I show how to add ribbon customizations for a web part or custom field control.
  • CommandUIDefinition:
    • Another element you might have multiple of – one for the main customization definition, one for each of the “GroupTemplate” elements being provisioned (more on this later). For the main one, the “Location” attribute here is crucially important as this specifies where the customization should appear. My value of “Ribbon.Tabs._children” indicates I’m adding something into the “Ribbon.Tabs” collection defined by SharePoint (typically in CMDUI.XML) – “_children” is a convention used when adding to many collections in the ribbon architecture. We’ll look at how to add new groups and controls into an existing group in the next article, but as a quick example, adding a group into “Ribbon.Library.Groups._children” would make your group appear somewhere in here (depending on the “Sequence” value assigned on the definition for the group):
      Ribbon.Library.Groups
  • Tab:
    • The “Sequence” attribute decides where to place my tab amongst the existing ones. Out-of-the-box values are generally multiples of 10, sometimes of 5, so your sequence values should avoid such numbers to avoid conflict. Generally you’ll need to find the declaration of the surrounding elements near where you are targeting (in CMDUI.XML) to find the appropriate number.
  • Scaling (and children):
    • This section defines how your elements should behave when the window is resized and there’s not enough room. You need a “MaxSize” and “Scale” element for each Group you define. These define the size and layout the element(s) should be at when at “max”, and also what to change to when the window is smaller – effectively you can provide multiple layouts for your controls depending on the window size (e.g. prioritising the important buttons).
  • Group:
    • This is the “section on the ribbon tab” which is the container for your controls – in the small image above, an example of a Group is ‘View Format’ which contains the two leftmost buttons. Key things here are the “Sequence” (same deal as elsewhere) and the “Template” – this is a reference to a “GroupTemplate” element (which we’ll come onto shortly). In essence, this is the link which will tell the ribbon framework how to lay out the controls in this group.
  • Controls:
    • Fairly obvious, this is the parent node for any controls you want to add e.g. buttons, dropdowns etc etc. Note that each of your controls in here must have a “TemplateAlias” attribute – this tells the framework exactly where to place the individual control within the GroupTemplate which is referenced.
    • Controls expose various commands, via attributes – a Button simply has a “Command” attribute which fires when clicked, whereas a Dropdown has additional ones such as “PopulateQueryCommand” and “QueryCommand". These link to “CommandUIHandler” elements or code defined in a JavaScript page component.
  • GroupTemplate:
    • Similar to defining say, a HTML table, this section provides the actual layout of the controls, alignments, control sizes etc. Each control which is being declared needs a corresponding “ControlRef” element which will be matched to the control on the “TemplateAlias” value.
  • CommandUIHandler:
    • This is the where you get to define the JavaScript which executes when the basic “Command” is fired for a control (e.g. a button is clicked). The command name must match that defined on the Control element, and the “CommandAction” attribute contains the script for the basic command. You can also use the “EnabledScript” attribute to add some script which decides whether the control should be enabled or not – this is how my '’remove status’ buttons are only enabled when there is a message to remove.
    • Since all the JavaScript gets added to the same page, as you’ll see in my sample it is possible to declare variables which get used by other JavaScript provisioned by a different CommandUIHandler – again though, whilst the sequence is deterministic you cannot control where your script gets added into the overall page (at the start of the <body> tag), so if you need your code to run when the DOM is complete you’d have to take steps to get your code called at the appropriate time – more on this later in the series.

Hope you found this useful. Next time we’ll take a quick look at adding items to existing ribbon locations, before moving onto working with JavaScript and page components etc.

20 comments:

Steve said...

I think the complexity of the ribbon UI is going to be one of the major challenges of SP2010 for end users. It's one of the few risk factors for the success of this release. Great to see some of the leaders of the SharePoint community jumping on this issue early, providing solutions and options. Great content!

Peter Kneale said...

Great post, im trying to build some custom ribbon buttons that will allow us to insert links to our document management system. any chance you could remove the line numbers from your xml files (or just make them available for download). It would make experimenting with them a lot easier :)
I used your other article on Styles and Markup Styles and it worked perfectly - saved me a heap of time.
Thanks for the great blog.

Chris O'Brien said...

@Peter Kneale,

Good point, I guess my samples are 'optimized for reading' ;) I'll try and do something about the line numbers over the next day or two.

Chris.

Furqan Shaikh said...

Great introductory articles on ribbon customization.
I am working on SP 2010 beta version. element has only one element unlike your XML which has Groups as well. Am i missing something? Any help is appreciated.

Thanks,
Furqan

Chris O'Brien said...

@Furqan,

Don't forget you only need a 'Groups' element if you are defining new groups. If you are targeting an existing group (as per the 2nd article in my series - Adding ribbon items into existing tabs/groups), you wouldn't have a 'Groups' element.

Does that make sense?

Chris.

Toni Frankola said...

Chris,

this is awesome article, very helpful!

I run into some problems with the code, maybe cause I am using beta2?

1) I had to reorder sub-elements of the group element element and order them: MaxSize-MaxSize-MaxSize-Scale-Scale-Scale
2) Also the Remove status buttons are note enabled after status is posted, they stay in disable state all the time.

Chris O'Brien said...

@Toni,

Thanks for the kind words. Not sure why you had a couple of problems, though now I actually can't remember whether I wrote this sample on beta 2 or RC so could be that.

Suggest making sure you're clearing the browser cache after each change though - sometimes I was thrown for a loop and was thinking for a while a certain set of markup was wrong, turned out it was the caching fooling me again and when I cleared the cache things started working. A definite gotcha when working with the ribbon :)

Chris.

Jason Lochan said...

Thanks for pointing me to TEMPLATE\GLOBAL\XML\CMDUI.XML! Huge help

Andi Fandrich said...

Does anyone know if it is possible to add ribbon commands for a specific custom list template only?
I developed a custom feature with a custom list template and tried to apply a ribbon customization just for lists based on this template, but to no avail. Tried with RegistrationId=myID and tried with a custom content type. Ribbon customization for default list templates (Custom List etc.) works well.

My first thought was that this is a problem with the Beta, but it doesn't work in RTM as well. Any thoughts?

Mark said...

Thanks for the great post. I am using your code as a basis but have found that none of the images load when I deploy and test the ribbon. Has anyone else run into this? Is there an easy solution? Also is there an easy way to have the ribbon always displayed no matter which part of the site a user goes to?

Thanks,
Mark

Victor said...

Does this approach still allow the SP 2010 permissions to be applied by default to any new tabs or buttons ?

Chris O'Brien said...

@Victor,

I'm not sure I fully understand the question, but the implementor/developer is responsible for implementing any security-trimming of ribbon controls. As an example, for a button the EnabledScript attribute is used to point to some JavaScript which you write to decide whether the button should be enabled or not for the current user.

HTH,

Chris.

Shai Petel said...

Hi Chris!

Great post, only you have 2 bugs in the code you posted:

1. Your enable script will not get fired after adding status messages. You have to call "RefreshCommandUI();" in order to get SharePoint to reevaluate the button status.
Actually, you should call it instead of calling enableRemoveStatusButton();

2. Second one is more of a logical issue, the "latestId" should actually store an array of id's, so that once you remove latest one it will still have the prev. messages in your array.

Apart from that - Thanks for your great post. Really liked reading it.

Chris O'Brien said...

@Shai,

Useful feedback, thanks! On the 2nd point I guess I wasn't too worried about supporting multiple messages as it's not really a lifelike demo (and I wanted to keep it simple), but otherwise yes I agree.

I am definitely interested on the 1st point - I'm assuming RefreshCommandUI() would trigger the EnabledScript for *all* current ribbon elements, not just one? If so, I wonder - is it a good pattern to use this when you know only one element has changed? I know it's on the client, but still it's more processing than necessary no?

Or is the bug something bigger than my understanding?

Good discussion, thanks :)

Chris.

Shai Petel said...

Hi Chris,

The issue is that you want to click a ribbon button (add status message) and in that event you change the flag for enabling other ribbon buttons.

Thing is, the ribbon does not re-evaluate the button status in that time.

So, in the RTM build that i have the buttons stayed disabled all the time, unless I trigget the update (like by clicking on a web part).

The refresh function does not run on all of the ribbon, it does 2 things:
1. Show / Hide contextual tabs
2. Enable / Disable controls only within the current active tab

but I don't see anyway to make it more efficiant, as you can never know who else might be listening (other controls perhaps by another developer)

Chris O'Brien said...

@Shai,

Oh wow - the buttons were definitely behaving as expected when I did the development, but since that was in January 2010 this was obviously not on RTM. I guess something changed between releases.

In which case I'm even more grateful for your correction - I guess we conclude RefreshCommandUI() is required in these situations then.

Thanks,

Chris.

Luis Esteban Valencia said...

I have a warning on the xml file:

Warning 1 The element 'Scaling' in namespace 'http://schemas.microsoft.com/sharepoint/' has invalid child element 'MaxSize' in namespace 'http://schemas.microsoft.com/sharepoint/'. List of possible elements expected: 'Scale, LowScaleWarning' in namespace 'http://schemas.microsoft.com/sharepoint/'. K:\Users\Administrator\Documents\Visual Studio 2010\Projects\SlnSharepoint2010\EmptySharePointProject1\CustomRibbonElements\Elements.xml 19 16 EmptySharePointProject1

Any idea ?

Thank you

Chris O'Brien said...

@Luis,

Hmm that's pretty weird - if you take a look in CMDUI.XML you'll see that Microsoft themselves use have many 'MaxSize' elements in their ribbon XML (I've just checked on RTM).

Could it be something with namespaces used in your XML? Are you developing on the RTM version?

Thanks,

Chris.

Luis Esteban Valencia said...

Hello Chris, as somebody else said on the comments I fixed this by changing order,
MaxSize,MaxSize,MaxSize, Scaling, Scaling, Scaling

Yes, I am using RTM

Chris O'Brien said...

@Luis,

Great stuff - that's certainly the sequence Microsoft use for their elements.

Chris.