Monday, December 15, 2014

Office 365/ SharePoint Online / SharePoint hosted App - Custom Action ScriptLink

Step1: Added button in Default.aspx page
    <input type="button" value="Add Custom Ribbon" title="Add" onclick="AddCustomAction();" />

Step2: Written the below script for "AddCustomAction" method
This method performs 2 operations
1) Add script link ie," test.js "
2) Add custom ribbon tab only for template type 10000

function AddCustomAction() {
    var context = new SP.ClientContext.get_current;
    this.oWebsite = context.get_web();
    var collUserCustomAction = this.oWebsite.get_userCustomActions();
    var scriptLink = collUserCustomAction.add();
    scriptLink.set_name('Welcomescriptlink');
    scriptLink.set_title('Welcome');
    scriptLink.set_description('Welcome to new custom script Link');
    scriptLink.set_location('ScriptLink');
    scriptLink.set_scriptSrc('~Site/Scripts/test.js');
    scriptLink.set_group('');
    scriptLink.update();

    var oUserCustomAction = collUserCustomAction.add();
    oUserCustomAction.set_name('Welcome');
    oUserCustomAction.set_title('Welcome Title');
    oUserCustomAction.set_description('Welcome to new custom Action');
    oUserCustomAction.set_location('CommandUI.Ribbon');
    oUserCustomAction.set_registrationId('10000');
    oUserCustomAction.set_registrationType(1);
    oUserCustomAction.set_group('');
    var ca = '<CommandUIExtension xmlns="http://schemas.microsoft.com/sharepoint/">' +
  '<CommandUIDefinitions>' +
    '<CommandUIDefinition Location="Ribbon.Tabs._children">' +
      '<Tab Id="Demo.Tab" Title="SLK Utilities" Description="SLK Utilities" Sequence="10000">' +
        '<Scaling Id="Demo.Tab.Scaling">' +
          '<MaxSize Id="Demo.Tab.Group.Scaling.MaxSize" GroupId="Demo.Tab.Group" Size="LargeLarge" />' +
          '<Scale Id="Demo.Tab.Group.Scaling.Scale" GroupId="Demo.Tab.Group" Size="LargeLarge" />' +
        '</Scaling>' +
        '<Groups Id="Demo.Tab.Groups">' +
          '<Group Id="Demo.Tab.Group" Title="Print" Description="Print the selected items" Template="Ribbon.Templates.Flexible2">' +
            '<Controls Id="Demo.Tab.Group.Controls">' +
              '<Button Id="DemoControlID" LabelText="" ToolTipTitle="Print" ToolTipDescription="Print the selected items" Command="DemoControlID.Command" TemplateAlias="o1" Image32by32="~site/images/printer.png" />' +
            '</Controls>' +
          '</Group>' +
        '</Groups>' +
      '</Tab>' +
    '</CommandUIDefinition>' +
    '<CommandUIDefinition Location="Ribbon.Templates._children">' +
      '<GroupTemplate Id="Ribbon.Templates.Flexible2">' +
       '<Layout Title="LargeLarge">' +
              '<OverflowSection Type="OneRow" TemplateAlias="o1" DisplayMode="Large"/>' +
              '<OverflowSection Type="OneRow" TemplateAlias="o2" DisplayMode="Large"/>' +
        '</Layout>' +
      '</GroupTemplate>' +
    '</CommandUIDefinition>' +
  '</CommandUIDefinitions>' +
  '<CommandUIHandlers>' +
    '<CommandUIHandler Command="DemoControlID.Command" CommandAction="javascript:SP.UI.ModalDialog.showModalDialog({url:\'{SiteUrl}/Pages/Demo.aspx?{StandardTokens}&amp;SPListItemId={ItemId}&amp;SPListId={ListId}\', title:\'Page Title\'});"/>' +
  '</CommandUIHandlers>' +
'</CommandUIExtension>';
    oUserCustomAction.set_commandUIExtension(ca)
    oUserCustomAction.update();
    context.load(this.oWebsite, 'Title', 'UserCustomActions');
    context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    alert('Custom action created for ' + this.oWebsite.get_title());
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


Step3: The below script i have written for " test.js " file.

var url = window.location.pathname;

if (url.toString().toLowerCase().indexOf("lists") > -1) {
    var path = url.substring(url.toString().toLowerCase().indexOf("lists"), url.length);
    var pathArray = path.split('/');
    var listName = pathArray[1];

    ExecuteOrDelayUntilScriptLoaded(retrieveWebSite, "sp.js");

    var oWebsite;
    var list;
    var viewCollection;

    function retrieveWebSite() {
        var clientContext = new SP.ClientContext.get_current();
        oWebsite = clientContext.get_web();
        list = oWebsite.get_lists().getByTitle(listName);
        viewCollection = list.get_views();
        clientContext.load(list);
        clientContext.load(viewCollection);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededs), Function.createDelegate(this, this.onQueryFaileds));
    }

    function onQuerySucceededs() {
        if (list.get_baseTemplate() == "10000") {
            var viewEnumerator = viewCollection.getEnumerator();
            while (viewEnumerator.moveNext()) {
                var currentView = viewEnumerator.get_current();
                if (currentView.get_serverRelativeUrl().toString().toLowerCase() == url.toString().toLowerCase()) {
                    SP.UI.Notify.addNotification("<span>List Title " + list.get_title() + "<\/span>");
                    var selection = SP.ListOperation.Selection.getSelectedItems(list.get_context());
                }
            }
        }
    }

    function onQueryFaileds(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
}

Question:

My question is, how i can optimize the above test.js script such a way that it will execute only for template type 10000 instead of doing so many if , while checks here and executing for other lists. I would like to know if there is any other way to implement this.

Basically my task is, onclick of button i have to register and enable the custom ribbon tab ( in app web )

No comments:

Post a Comment