Freigeben über


Create Custom Ribbon and launch application page from it in SharePoint 2010

One of the features which is extensively used with SharePoint 2010 is Ribbons controls. In this post we would be creating a custom ribbon and open up a application page when ribbon is clicked using client object model using javascript

//// Creating Ribbon XML

<CustomAction
   Id="CustomRibbonButton" /// Represent Unique Id of custom action
   Location="CommandUI.Ribbon.ListView" // Represent Location where Ribbon will be visible( I have kept it at List View, for other options you can try out "https://msdn.microsoft.com/en-us/library/bb802730.aspx"
   RegistrationId="0x01003E510038825141608FE2D66FF6804EDD" // Guid of Element specified in Registration type, make sure it is all capital letters, i have seen issues with lowercase letters"
   Rights="EditListItems" // Represent security rights i.e. users who has edit list items will only see this ribbon
   RegistrationType="ContentType"> // Type for which ribbon is attached for e.g. list,content type
    <CommandUIExtension> // Tag for user Interface
      <CommandUIDefinitions> // Represent commands for user interface
        <CommandUIDefinition
         Location="Ribbon.ListItem.Actions.Controls._children"> // Location of RIbbon Tab{ For this example it is under actions tab of list item}
          <Button
           Id="Ribbon.ListItem.Manage.Controls.TestButton"
           Command="ShowAlert" // The command to execute When Button is clicked
           LabelText="Sample Ribbon"// The label to be shown under ribbon
           Image32by32="/_layouts/images/menupersonalize.gif"//The image to shown as ribbon icon
           TemplateAlias="o2" //The TemplateAlias attribute is used to size and position controls within a group when a template is applied to the group. This is used when we have created Group tab and sections for showing ribbons
           Sequence="501" /> // Represent order of placement among other ribbons
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers> // Represent Commands
        <CommandUIHandler
          Command="ShowAlert" // Name should match Command attribute of Button
          CommandAction ="javascript:CustomCommandAction('{SiteUrl}', 'mybutton');" // Javascript function to execute when command(click event of button in this case as defined in button control)
          EnabledScript="javascript:EnableOnSingleItemSelection();" > // Javascript function to execute to enable/disable the ribbon
        </CommandUIHandler>
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>

// Custom Action to Specify the JS File
<CustomAction
    Id="CustomRibbonButton.Script"
    Location="ScriptLink"
    ScriptSrc ="/_layouts/SampleFolder/js/CustomRibbon.js"/>
</Elements>

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Javascript functions in CustomRibbon.js

var listItem;
var buttonpressed;
var siteURL;

function EnableOnSingleItemSelection() {
    var items = SP.ListOperation.Selection.getSelectedItems();
    var itemsCount = CountDictionary(items);
    return (itemsCount == 1)
}

function CustomCommandAction(siteurl, buttonpressed) {
this.buttonpressed = buttonpressed;  
this.currentSiteUrl = siteurl;
var ctx = SP.ClientContext.get_current();// get client context
    var web = context.get_web();
    var selectedItems = SP.ListOperation.Selection.getSelectedItems(); // Get selected List items
     var listItm = selectedItems[0]; // this will only return ID of list item, to get list object server call has to be mad
      this.listItem = sdlist.getItemById(listItm.id);
        this.spContext.load(this.listItem);// Load listitem in spcontext to fetch all properties of listitem
        this.spContext.load(this.spContext.get_site());// To fetch site properties
        this.spContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

/// spContext.executeQueryAsync make asyncronous call to server and return the requested objects, two delegates are attached to handle success(onQuerySucceeded) and faliure(onQueryFailed) operations

function onQuerySucceeded(sender, args) {

 
    var title = this.listItem.get_item('Title');    // get the selected item title
    var options = SP.UI.$create_DialogOptions();
    var siteguid = spContext.get_site().get_id(); // get current site guid
    var itemid = this.listItem.get_item('ID'); // get the selected item id
    var appUrl;  
    appUrl = this.currentSiteUrl + "/_layouts/SampleFolder/SamplePage.aspx?title=" + title + "&siteguid=" + siteguid;// To redirect to SamplePage.aspx with query string parameter as selected item title and current siteguid
  

    options.url = appUrl;
    options.height = 600;
    options.width = 800;  
    options.dialogReturnValueCallback=Function.createDelegate(null, DialogClosedCallback);
    SP.UI.ModalDialog.showModalDialog(options); // To Open Page in Model Dialogue
}
function DialogClosedCallback() {SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);} // To refresh the parent page after model dialogue closes

function onQueryFailed(sender, args) {
    alert('failed ' + args.toString());
}