SharePoint Ribbon详细解析

 

1、使用jsom对象模型动态添加Ribbon

<script type="text/javascript">
        window.attachEvent("onload", CreateTab);
        function CreateTab() {
            SelectRibbonTab('Ribbon.Read', true);
            setTimeout(createMyTab, 1000);
        }

        function createMyTab() {
            var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
            if (ribbon !== null) {
                var tab = new CUI.Tab(ribbon, 'Sample.Tab', 'Sample', 'Tab description', 'Sample.Tab.Command', false, '', null, null);
                ribbon.addChild(tab);
                var group = new CUI.Group(ribbon, 'Sample.Tab.Group', 'Sample Group', 'Group Description', 'Sample.Group.Command', null);
                tab.addChild(group);
                var layout = new CUI.Layout(ribbon, 'Sample.Layout', 'The Layout');
                group.addChild(layout);
                var section = new CUI.Section(ribbon, 'Sample.Section', 2, 'Top'); //2==OneRow
                layout.addChild(section);
                var controlProperties = new CUI.ControlProperties();
                controlProperties.TemplateAlias = 'o1';
                controlProperties.ToolTipDescription = 'Use this button';
                controlProperties.Image32by32 = '_layouts/15/images/placeholder32x32.png';
                controlProperties.ToolTipTitle = 'A Button';
                controlProperties.LabelText = 'Something';
                var button = new CUI.Controls.Button(ribbon, 'Sample.Button', controlProperties);
                var controlComponent = button.createComponentForDisplayMode('Large');
                var row1 = section.getRow(1);
                row1.addChild(controlComponent);
                group.selectLayout('The Layout');
            }
        }

        function SelectTab(e) {
            setTimeout(function () { SelectRibbonTab('Sample.Tab', true); }, 1000);
            setTimeout(OverWriteEvents, 1500);
        }

        function OverWriteEvents() {
            var sampleButton = document.getElementById("Sample.Button-Large");
            sampleButton.classList.remove('ms-cui-disabled');
            sampleButton.onclick = function () { alert("Clicked Sample.Button"); };
        }

 </script>

 2、使用vs添加自定义Ribbon

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="Ribbon.CustomGroup" RegistrationId="101" RegistrationType="List" Title="MyCustomerRibbon" Location="CommandUI.Ribbon">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Documents.New.Controls._children">
          <Button Id="Ribbon.Documents.New.Submit"
          Command="Submit"
          Image32by32="/_layouts/15/images/SPjyjcsjkCustomeRibbon/submit2.png"
          Image16by16="/_layouts/15/images/SPjyjcsjkCustomeRibbon/submit1.png"
          LabelText="提交"
          TemplateAlias="o1" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
         
        <CommandUIHandler
        Command="Submit"
        CommandAction="javascript:SubmitDataUpdate()" EnabledScript="javascript:enableCustomRibbon();" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
  <CustomAction
    Id="Ribbon.Documents.New.Submit.Script"
    Location="ScriptLink"
    ScriptSrc ="/_layouts/15/SPjyjcsjkCustomeRibbon/ECMASubmit49.js" />
 
</Elements>

脚本代码如下:
/// <reference name="MicrosoftAjax.js" /> 
/// <reference path="file:///C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.core.debug.js" />
/// <reference path="file:///C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.debug.js" /> 
/// <reference path="file:///C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS/SP.Ribbon.debug.js" />
var context;
var web;
var user;
var item;
var username;
var isEnable = "true";
var isPass = "false";//能否提交选中项
ExecuteOrDelayUntilScriptLoaded(InitUser, "sp.js");
function InitUser() {
    context = SP.ClientContext.get_current();
    web = context.get_web();
    user = web.get_currentUser();
    context.load(user);
    context.executeQueryAsync(onUserSuccess, onFailed);
}
function SubmitDataUpdate() {
    isEnable = "false";
    RefreshCommandUI();
    item.set_item("CFPosted", "已提交");
    item.update();
    context.executeQueryAsync(onUpdateItemSuccess, onFailed)
    
}

function onUserSuccess() {
    username = user.get_title();
    
}
function onGetListItemSuccess() {
    var postedStatus = item.get_item("CFPosted");
    if (postedStatus == "已提交") {
       
        return;
    }
    var author = item.get_item("Author").get_lookupValue();
    if (author != username) {
      
        return;
    }
    isPass = "true";
    RefreshCommandUI();
}
function onUpdateItemSuccess() {
    setTimeout("reloadUrl()", 2000);
}
function reloadUrl() {
    window.location.reload();
}
function onFailed(sender, args) {
    alert('提交失败:' + args.get_message());
}
function enableCustomRibbon() {
    if (isEnable == "false") {//禁用ribbon
        return false;
    }
    var ctx = SP.ClientContext.get_current();
    var items = SP.ListOperation.Selection.getSelectedItems(context);
    if (items.length != 1) {
        isPass = "false";
       
    } else {
        if (isPass == 'false') {
            var currentLibId = SP.ListOperation.Selection.getSelectedList();
            var currentLib = web.get_lists().getById(currentLibId);
            item = currentLib.getItemById(items[0].id);
            context.load(item);
            context.executeQueryAsync(onGetListItemSuccess, onFailed);
        } else {
            
            isPass = 'false';
            return true;
        }
    }
   

}

Location定义在何处应用自定义项,详请见下图

 

When creating custom menu item, you will need this.

Value

Description

1200

Administrator tasks list

104

Announcements list

303

Blog Categories list

302

Blog Comments list

301

Blog Posts list

105

Contacts list

120

Custom grid for a list

118

Custom Workflow Process

130

Data Connection library

110

Data sources

108

Discussion board

101

Document library

106

Events list

150

Gantt Tasks list

100

Generic list

1100

Issue tracking

103

Links list

114

List template gallery

116

Master pages gallery

201

Meeting Agenda list

202

Meeting Attendees list

204

Meeting Decisions list

207

Meeting Objectives list

200

Meeting Series list

210

Meeting text box

211

Meeting Things To Bring list

212

Meeting Workspace Pages list

117

No-Code Workflows

2002

Personal document library

109

Picture library

300

Portal Sites list

2003

Private document library

111

Site template gallery

102

Survey

107

Tasks list

112

User Information list

113

Web Part gallery

119

Wiki Page library

140

Workflow History

115

XML Form library

3、禁用和启用Ribbon,参考,或参考2

http://www.cnblogs.com/wsdj-ITtech/archive/2012/06/18/2426787.html

4、在Ribbon中添加tab

本文参考自http://www.cnblogs.com/wsdj-ITtech/archive/2012/03/07/2279774.html

根据上述文章的内容自身实践后写的一些自己的理解,如有不同见解,望讨论!

先贴一段新建Tab的代码

复制代码
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
     Id="MyCustomRibbonTab"
     Location="CommandUI.Ribbon.ListView"
     RegistrationId="0x0101010045E25FD930B6D74DB794CC4D2D7D029D"
     RegistrationType="ContentType">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Tabs._children">
          <Tab
            Id="Ribbon.CustomTabExample"
            Title="My Custom Tab"
            Description="This holds my custom commands!"
            Sequence="1001">
            <Scaling
              Id="Ribbon.CustomTabExample.Scaling">
              <MaxSize
                Id="Ribbon.CustomTabExample.MaxSize"
                GroupId="Ribbon.CustomTabExample.CustomGroupExample"
                Size="OneLargeTwoMedium"/>
              <Scale
                Id="Ribbon.CustomTabExample.Scaling.CustomTabScaling"
                GroupId="Ribbon.CustomTabExample.CustomGroupExample"
                Size="OneLargeTwoMedium" />
            </Scaling>
            <Groups Id="Ribbon.CustomTabExample.Groups">
              <Group
                Id="Ribbon.CustomTabExample.CustomGroupExample"
                Description="This is a custom group!"
                Title="Custom Group"
                Sequence="52"
                Template="Ribbon.Templates.CustomTemplateExample">
                <Controls Id="Ribbon.CustomTabExample.CustomGroupExample.Controls">
                  <Button
                    Id="Ribbon.CustomTabExample.CustomGroupExample.HelloWorld"
                    Command="CustomTabExample.HelloWorldCommand"
                    Sequence="15"
                    Description="Says hello to the World!"
                    LabelText="Hello, World!"
                    TemplateAlias="cust1"/>
                  <Button
                    Id="Ribbon.CustomTabExample.CustomGroupExample.GoodbyeWorld"
                    Command="CustomTabExample.GoodbyeWorldCommand"
                    Sequence="17"
                    Description="Says good-bye to the World!"
                    LabelText="Good-bye, World!"
                    TemplateAlias="cust2"/>
                  <Button
                    Id="Ribbon.CustomTabExample.CustomGroupExample.LoveWorld"
                    Command="CustomTabExample.LoveWorldCommand"
                    Sequence="19"
                    Description="Says I love the World!"
                    LabelText="I love you, World!"
                    TemplateAlias="cust3"/>
                </Controls>
              </Group>
            </Groups>
          </Tab>
        </CommandUIDefinition>
        <CommandUIDefinition Location="Ribbon.Templates._children">
          <GroupTemplate Id="Ribbon.Templates.CustomTemplateExample">
            <Layout
              Title="OneLargeTwoMedium"
              LayoutTitle="OneLargeTwoMedium">
              <Section Alignment="Top" Type="OneRow">
                <Row>
                  <ControlRef DisplayMode="Large" TemplateAlias="cust1" />
                </Row>
              </Section>
              <Section Alignment="Top" Type="TwoRow">
                <Row>
                  <ControlRef DisplayMode="Medium" TemplateAlias="cust2" />
                </Row>
                <Row>
                  <ControlRef DisplayMode="Medium" TemplateAlias="cust3" />
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="CustomTabExample.HelloWorldCommand"
          CommandAction="javascript:alert('Hello, world!');" />
        <CommandUIHandler
          Command="CustomTabExample.GoodbyeWorldCommand"
          CommandAction="javascript:alert('Good-bye, world!');" />
        <CommandUIHandler
          Command="CustomTabExample.LoveWorldCommand"
          CommandAction="javascript:alert('I love you, world!');" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
</Elements>
复制代码

接下来对每个部分进行剖析

复制代码
<?xml version="1.0" encoding="utf-8"?>
 <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
     <CustomAction
       Id="MyCustomRibbonTab"                   
       Location="CommandUI.Ribbon.ListView"                                                //自定义项显示的位置(列表、编辑表单、新建表单等)
       RegistrationId="101"                                                                //在什么结构下显示(文档库、通用列表、表单库、日历等)
       RegistrationType="List">                                                            //注册类型(ContentType,FileType,List,ProgId)
复制代码

Location定义在何处应用自定义项,详请见下图

在做到这步的时候对RegistrationId和 RegistrationType有些疑问,进一步研究后,发现两者共同作用于Tab显示时机

例:

RegistrationId="101"    RegistrationType="List"    在文档库下显示
RegistrationId="115"    RegistrationType="List"    在表单库下显示
RegistrationId="100"    RegistrationType="List"    在列表下显示
RegistrationId="0x0101010045E25FD930B6D74DB794CC4D2D7D029RegistrationType="ContentType"    在内容类型ID为RegistrationId时显示

一篇国外的博客在这方面写的很好: http://blog.alexboev.com/2011/12/registrationtype-registrationid-in.html

接下来定义Tab

复制代码
<CommandUIExtension>
      <CommandUIDefinitions>
           <CommandUIDefinition                        
               Location="Ribbon.Tabs._children">                     //定义呈现的位置,当前呈现在Tabs集合中
                 <Tab
                    Id="Ribbon.CustomTabExample"
                    Title="My Custom Tab"
                    Description="This holds my custom commands!"
                    Sequence="501">                                  //定义相对其他Tabs的位置,sharepoint默认是用100的倍数,所以最好使用非100倍数的数字。 
                                                                     //数字越大,位置越靠右
复制代码

在创建Tab是需要定义控件的缩放:

复制代码
<Scaling                                                                  //定义控件的缩放                           
Id="Ribbon.CustomTabExample.Scaling">      <MaxSize //组中控件的最大大小       Id="Ribbon.CustomTabExample.MaxSize"       GroupId="Ribbon.CustomTabExample.CustomGroupExample"       Size="OneLargeTwoMedium"/>       <Scale //组在不同的情况下进行缩放       Id="Ribbon.CustomTabExample.Scaling.CustomTabScaling"       GroupId="Ribbon.CustomTabExample.CustomGroupExample" //绑定缩放的group       Size="OneLargeTwoMedium" /> //有GroupTemplate中的Layout元素定义 </Scaling>
复制代码

对Tab定义后,进一步对Group定义

复制代码
                       <Groups Id="Ribbon.CustomTabExample.Groups">                                       //定义Group                             
<Group                                Id="Ribbon.CustomTabExample.CustomGroupExample"                                Description="This is a custom group!"                                Title="Custom Group"                                Sequence="52" //sharepoint默认是10的倍数                                Template="Ribbon.Templates.CustomTemplateExample"> //每个Group都需要对应一个Template                                  <Controls Id="Ribbon.CustomTabExample.CustomGroupExample.Controls">                                      <Button                                        Id="Ribbon.CustomTabExample.CustomGroupExample.HelloWorld"                                        Command="CustomTabExample.HelloWorldCommand"                                        Sequence="15"                                        Description="Says hello to the World!"                                        LabelText="Hello, World!"                                        TemplateAlias="cust1"/>
复制代码

注意:sharepoint规定每一个Group都要有Template与之对应,Sequence属性与上面的作用一样,用来确定与其他Group的位置。

复制代码
                 <CommandUIDefinition Location="Ribbon.Templates._children">
                     <GroupTemplate Id="Ribbon.Templates.CustomTemplateExample">                      //定义组显示结构
                         <Layout
                           Title="OneLargeTwoMedium"                                                  //对应MaxSize和Scale中的Size属性
                           LayoutTitle="OneLargeTwoMedium">
                             <Section Alignment="Top" Type="OneRow">
                                 <Row>
                                     <ControlRef DisplayMode="Large" TemplateAlias="cust1" />         //‘cust1’与control中的 TemplateAlias对应
                                 </Row>
                             </Section>
                             <Section Alignment="Top" Type="TwoRow">
                                 <Row>
                                     <ControlRef DisplayMode="Medium" TemplateAlias="cust2" />        
                                 </Row>
                                 <Row>
                                     <ControlRef DisplayMode="Medium" TemplateAlias="cust3" />        //用来定义显示的样式
                                 </Row>
                             </Section>
                         </Layout>
                     </GroupTemplate>
                 </CommandUIDefinition>
             </CommandUIDefinitions>
复制代码

最后是CommandUIHandlers 元素的定义,用来相应用户的操作

复制代码
             <CommandUIHandlers>                                                              //定义如何响应用户操作,对应控件Command属性                 
<CommandUIHandler                    Command="CustomTabExample.HelloWorldCommand"                    CommandAction="javascript:alert('Hello, world!');" />                  <CommandUIHandler                    Command="CustomTabExample.GoodbyeWorldCommand"                    CommandAction="javascript:alert('Good-bye, world!');" />                  <CommandUIHandler                    Command="CustomTabExample.LoveWorldCommand"                    CommandAction="javascript:alert('I love you, world!');" />              </CommandUIHandlers>
复制代码
这样,定义的过程就完成了,部署后查看效果



CommandAction定义的操作可以是ECMAScript(JavaScript、JScript)、URL 或 UrlAction 元素中以前包含的任意内容。
这里我给出一个ECMAScript的例子:
复制代码
 <CommandUIHandlers>
        <CommandUIHandler
         Command="emailContacts"
         CommandAction="javascript:
           function getItemIds()
           {
             var itemIds = '';
             var items = SP.ListOperation.Selection.getSelectedItems();
             var item;
             for(var i in items)
             {
               item = items[i];
               if(itemIds != '')
               {
                 itemIds = itemIds + ',';
               }
               itemIds = itemIds + item.id;
             }
             return itemIds;
           }
           function handleReadyStateChange()
           {
             if (client.readyState == 4)
             {
               if (client.status == 200) 
               {
                 // client.responseText is mailto string
                 window.location = ('mailto:' + client.responseText);
               }
             }
           }
           function invokeEmailContacts()
           {
             var params = 'itemids=' + getItemIds(); 
             // Posting to EmailContacts.ashx to get the mailto string
             var site='{SiteUrl}'; 
             var url = site + '/_layouts/emailcontacts.ashx?listId={ListId}';
             client = null;
             client = new XMLHttpRequest();
             client.onreadystatechange =  handleReadyStateChange;
             client.open('POST', url, true);         
             client.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
             client.setRequestHeader('Content-length', params.length);
             client.send(params);
           }      
           invokeEmailContacts();"
         
      EnabledScript="javascript:
           function enableEmailContacts()
           {
             var items = SP.ListOperation.Selection.getSelectedItems();
             return (items.length > 0);
           }
           enableEmailContacts();"/>
      </CommandUIHandlers>
复制代码

 

 

5、Ribbon权限控制

http://www.cnblogs.com/splover/archive/2011/05/23/2054305.html

右键点击项,添加一个Module, 打开Elements.xml 添加以下代码:

权限说明

EmptyMask = 0,
        //
        // Summary:
        //     View items in lists, documents in document libraries, and view Web discussion
        //     comments.
        ViewListItems = 1,
        //
        // Summary:
        //     Add items to lists, add documents to document libraries, and add Web discussion
        //     comments.
        AddListItems = 2,
        //
        // Summary:
        //     Edit items in lists, edit documents in document libraries, edit Web discussion
        //     comments in documents, and customize Web Part Pages in document libraries.
        EditListItems = 4,
        //
        // Summary:
        //     Delete items from a list, documents from a document library, and Web discussion
        //     comments in documents.
        DeleteListItems = 8,
        //
        // Summary:
        //     Approve a minor version of a list item or document.
        ApproveItems = 16,
        //
        // Summary:
        //     View the source of documents with server-side file handlers.
        OpenItems = 32,
        //
        // Summary:
        //     View past versions of a list item or document.
        ViewVersions = 64,
        //
        // Summary:
        //     Delete past versions of a list item or document.
        DeleteVersions = 128,
        //
        // Summary:
        //     Discard or check in a document which is checked out to another user.
        CancelCheckout = 256,
        //
        // Summary:
        //     Create, change, and delete personal views of lists.
        ManagePersonalViews = 512,
        //
        // Summary:
        //     Create and delete lists, add or remove columns in a list, and add or remove
        //     public views of a list.
        ManageLists = 2048,
        //
        // Summary:
        //     View forms, views, and application pages, and enumerate lists.
        ViewFormPages = 4096,
        //
        // Summary:
        //     Allow users to open a Web site, list, or folder to access items inside that
        //     container.
        Open = 65536,
        //
        // Summary:
        //     View pages in a Web site.
        ViewPages = 131072,
        //
        // Summary:
        //     Add, change, or delete HTML pages or Web Part Pages, and edit the Web site
        //     using a Windows SharePoint Services–compatible editor.
        AddAndCustomizePages = 262144,
        //
        // Summary:
        //     Apply a theme or borders to the entire Web site.
        ApplyThemeAndBorder = 524288,
        //
        // Summary:
        //     Apply a style sheet (.css file) to the Web site.
        ApplyStyleSheets = 1048576,
        //
        // Summary:
        //     View reports on Web site usage.
        ViewUsageData = 2097152,
        //
        // Summary:
        //     Create a Web site using Self-Service Site Creation.
        CreateSSCSite = 4194304,
        //
        // Summary:
        //     Create subsites such as team sites, Meeting Workspace sites, and Document
        //     Workspace sites.
        ManageSubwebs = 8388608,
        //
        // Summary:
        //     Create a group of users that can be used anywhere within the site collection.
        CreateGroups = 16777216,
        //
        // Summary:
        //     Create and change permission levels on the Web site and assign permissions
        //     to users and groups.
        ManagePermissions = 33554432,
        //
        // Summary:
        //     Enumerate files and folders in a Web site using Microsoft Office SharePoint
        //     Designer 2007 and WebDAV interfaces.
        BrowseDirectories = 67108864,
        //
        // Summary:
        //     View information about users of the Web site.
        BrowseUserInfo = 134217728,
        //
        // Summary:
        //     Add or remove personal Web Parts on a Web Part Page.
        AddDelPrivateWebParts = 268435456,
        //
        // Summary:
        //     Update Web Parts to display personalized information.
        UpdatePersonalWebParts = 536870912,
        //
        // Summary:
        //     Grant the ability to perform all administration tasks for the Web site as
        //     well as manage content. Activate, deactivate, or edit properties of Web site
        //     scoped Features through the object model or through the user interface (UI).
        //     When granted on the root Web site of a site collection, activate, deactivate,
        //     or edit properties of site collection scoped Features through the object
        //     model. To browse to the Site Collection Features page and activate or deactivate
        //     site collection scoped Features through the UI, you must be a site collection
        //     administrator.
        ManageWeb = 1073741824,
        //
        // Summary:
        //     Use features that launch client applications; otherwise, users must work
        //     on documents locally and upload changes.
        UseClientIntegration = 68719476736,
        //
        // Summary:
        //     Use SOAP, WebDAV, or Microsoft Office SharePoint Designer 2007 interfaces
        //     to access the Web site.
        UseRemoteAPIs = 137438953472,
        //
        // Summary:
        //     Manage alerts for all users of the Web site.
        ManageAlerts = 274877906944,
        //
        // Summary:
        //     Create e-mail alerts.
        CreateAlerts = 549755813888,
        //
        // Summary:
        //     Allows a user to change his or her user information, such as adding a picture.
        EditMyUserInfo = 1099511627776,
        //
        // Summary:
        //     Enumerate permissions on the Web site, list, folder, document, or list item.
        EnumeratePermissions = 4611686018427387904,
        //
        // Summary:
        //     Has all permissions on the Web site. Not available through the user interface.
        FullMask = 9223372036854775807,

 

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
  Id="viewSiteManager"
  GroupId="SiteActions"
  Location="Microsoft.SharePoint.StandardMenu"
  Sequence="1000"
   Title="Owner Menu" Description="control menu with user permission"
  ImageUrl="colleagues_16.png"
   Rights="ManagePermissions">
    <UrlAction Url="~site/_layouts/sitemanager.aspx"/>
  </CustomAction>
</Elements>
代码中的红色部分是比较重要的属性,GroupId 和Location请参阅SDK,这里重点关注Rights, Rights属性的值,就是我们上面的SPbasePermission
的枚举值,可以用逗号隔开,比如 Rights= “ViewListItems,ManagePermissions”.

posted on 2015-05-27 22:42  !无名之辈  阅读(600)  评论(0)    收藏  举报