In this post I will show how to create custom ribbon button in specific list for Sharepoint Online. Suppose that we have the following xml file with declaration of the ribbon button:
1: <UserCustomAction Location="CommandUI.Ribbon"
2: Sequence="5" Title="Get tasks">
3: <![CDATA[<CommandUIExtension>
4: <CommandUIDefinitions>
5: <CommandUIDefinition Location="Ribbon.Documents.Manage.Controls._children">
6: <Button Id="Ribbon.ListItem.Manage.GetTasks"
7: Alt="Get tasks"
8: Sequence="10001"
9: Command="Get tasks_Button"
10: Image32by32="/_layouts/images/rtrsendtoicon.png"
11: Image16by16="/_layouts/images/copy16.gif"
12: LabelText="Get tasks"
13: TemplateAlias="o1" />
14: </CommandUIDefinition>
15: </CommandUIDefinitions>
16: <CommandUIHandlers>
17: <CommandUIHandler Command="Get tasks_Button" CommandAction="javascript: GetTasks();" />
18: </CommandUIHandlers>
19: </CommandUIExtension>]]>
20: </UserCustomAction>
For more convenient work we create own class for that in order to be able to deserialize it from xml:
1: public class UserCustomActionEntity
2: {
3: [XmlAttribute("Location")]
4: public string Location;
5: [XmlAttribute("Sequence")]
6: public int Sequence;
7: [XmlAttribute("Title")]
8: public string Title;
9: [XmlText]
10: public string CommandUIExtension;
11: }
With these preparations ribbon button can be created using the following code:
1: var web = ...;
2: var list = ...;
3: var existingActions = list.UserCustomActions;
4: web.Context.Load(existingActions);
5: web.Context.ExecuteQueryRetry();
6:
7: bool exists = false;
8: foreach (var a in existingActions)
9: {
10: if (string.Compare(a.Title, ac.Title, false) == 0)
11: {
12: exists = true;
13: break;
14: }
15: }
16:
17: if (exists)
18: {
19: return;
20: }
21:
22: var action = existingActions.Add();
23: action.Location = ac.Location;
24: action.Sequence = ac.Sequence;
25: action.Title = ac.Title;
26: action.CommandUIExtension = ac.CommandUIExtension;
27: action.Update();
28: web.Context.ExecuteQuery();
Here we first check that same ribbon button is not added already by comparing titles (lines 7-20) and if not, add new custom ribbon button using data from xml declaration (lines 22-28).
No comments:
Post a Comment