Wednesday, March 02, 2016

Part III: Examples of Ribbons Customization in SharePoint 2013

This article is a follow up from my Examples of Ribbons Customization in SharePoint Articles with a collection of Custom Ribbons Actions.
For this Article i provide 2 new Ribbon Custom Actions using JSOM call "Copy Document to another Folder" and "Copy ListItem with Metadata".

Examples of Ribbons Customization in SharePoint 2013
http://aaclage.blogspot.ch/2014/04/examples-of-customization-of-ribbons-in.html

Yes, i am aware of the new SharePoint 2016 JSOM for copy and move documents in SharePoint 2016 like reference in the following link, but my example uses the File Object to copy the file to their destination url with some nice tricks
Methods:
  • SP.MoveCopyUtil.copyFile
  • SP.MoveCopyUtil.copyFolder
  • SP.MoveCopyUtil.moveFile
  • SP.MoveCopyUtil.moveFolder
Here the collection and compilation of SharePoint Ribbon Custom Actions examples from my Articles:


All this Ribbons were made using the following tool "Processlynx Ribbon Manager"
http://aaclage.blogspot.ch/2014/06/sharepoint-app-processlynx-custom.html

Copy Document to another Folder using JSOM

This example provide a example on how we can use SharePoint JSOM to copy existing Document to another Folder in a Document Library, it's also possible to change the TargetPicker not only to document Library but to other Sites or Libraries.
Here a link where you can manage the TargetPicker for the different options:
Manage Site/Web/Lists/Folder Filter using Picker Tree Dialog
http://aaclage.blogspot.ch/2014/02/sharepoint-2013-manage-siteweb-lists.html

To copy a file the user needs to checks the file and the option "Copy Document" becomes enable to copy the selected file.
When the Copy Document Ribbon action is selected the TargetPicker appears to select the destination url of the Copied File.

After we selected the destination folder of the File, a popup appears to add the name to the copied file.

When the new file name is added to copied File the page redirected to the folder where the Document was created.

For the XML structure of the Ribbon Configuration you can use the following:
<CommandUIExtension xmlns=\"http://schemas.microsoft.com/sharepoint/\">\n<CommandUIDefinitions>\n<CommandUIDefinition Location=\"Ribbon.Documents.Copies.Controls._children\">\n<Button Id=\"Copy.Document\" LabelText=\"Copy Document\" Image32by32=\"/_layouts/15/1033/images/formatmap32x32.png?rev=33\" Image32by32Left=\"-439\" Image32by32Top=\"-204\" ToolTipTitle=\"Copy Document\" Command=\"Copy.Document.Command\" TemplateAlias=\"o1\" />\n</CommandUIDefinition>\n</CommandUIDefinitions>\n<CommandUIHandlers>\n<CommandUIHandler Command=\"Copy.Document.Command\" CommandAction="<code>" EnabledScript="<code>" />\n</CommandUIHandlers>\n</CommandUIExtension>

Code

This JavaScript code manage the copy of the document and destination of the Copied File.
CommandAction:

Javascript:
function CopyItem(SelectedFolder,SelectedItem,ListId,RootFolderList) {
     Items = SelectedItem;
    ListId.replace("{", "");
    ListId.replace("}", "");
    var targetListItem;
    var values = SP.ListOperation.Selection.getSelectedItems();
    var clientContext = new SP.ClientContext.get_current();
    var targetList = clientContext.get_web().get_lists().getById(ListId);
    targetListItem = targetList.getItemById(Items[0].id);
    clientContext.load(targetListItem,'File');
    clientContext.executeQueryAsync(function () {

    var NewFile = prompt("Copy File '"+ targetListItem.get_file().get_name().replace(/\.[^/.]+$/, "") +"' with new name?", targetListItem.get_file().get_name().replace(/\.[^/.]+$/, ""));
    if (NewFile != null) {
        if (SelectedFolder == "/")
        {
            copyFile(targetListItem.get_file().get_serverRelativeUrl(),RootFolderList.get_serverRelativeUrl()+ SelectedFolder+NewFile+"."+targetListItem.get_file().get_name().split('.').pop());
        }else{
            copyFile(targetListItem.get_file().get_serverRelativeUrl(),RootFolderList.get_serverRelativeUrl()+ SelectedFolder+ "/" +NewFile+"."+targetListItem.get_file().get_name().split('.').pop());
        }
    }
   },Function.createDelegate(this, this.onQueryFailed));
   }
   
   function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
function copyFile(sourceUrl, destinationUrl) {
    var clientContext, file;

    clientContext = SP.ClientContext.get_current();
    file = clientContext.get_web().getFileByServerRelativeUrl(sourceUrl);
    clientContext.load(file);
    SP.UI.Notify.addNotification('Copying file...', false);

    clientContext.executeQueryAsync(
        function (sender, args) {
            file.copyTo(destinationUrl, true);

            clientContext.executeQueryAsync(
                function (sender, args) {
                    window.location.href = destinationUrl.replace(/\/[^\/]+$/,"/");;
                },
                function (sender, args) {
                    alert(args.get_message());
                });
        },
        function (sender, args) {
            alert(args.get_message());
        });
}
function loadScript(url, callback){
    var script = document.createElement("script");
    script.type = "text/javascript";
    if (script.readyState){
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;callback();
            }};
    } else {
        script.onload = function(){callback();};
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
 getWebProperties();
}
function getWebProperties() {
        var ctx = new SP.ClientContext.get_current();
        var web = ctx.get_web();
        ctx.load(web,'Id');
        ctx.executeQueryAsync(function(){getListRootUrl(web.get_id(),'{ListId}')},Function.createDelegate(this, this.error));
    }
function getListRootUrl(WebID,ListId){
  ListId.replace("{", "");
  ListId.replace("}", "");
  var ctx = new SP.ClientContext.get_current();
        var targetList = ctx.get_web().get_lists().getById(ListId);
  var RootFolderList = targetList.get_rootFolder();
        ctx.load(RootFolderList, 'ServerRelativeUrl');  ctx.executeQueryAsync(function(){LaunchTargetPicker(WebID,ListId,RootFolderList)},Function.createDelegate(this, this.error));
}
function LaunchTargetPicker(WebId,ListId,RootFolderList) {
    var values = SP.ListOperation.Selection.getSelectedItems();
    var callback = function (dest) {
        if (dest !== null && dest !== undefined && dest[3] !== null) {
            CopyItem(dest[3],values,ListId,RootFolderList);
            
        }
    };
    ListId.replace("{", "");
    ListId.replace("}", "");
    var iconUrl = "/_layouts/15/images/smt_icon.gif?rev=32";
 SP.SOD.executeFunc('pickertreedialog.js', 'LaunchPickerTreeDialogSelectUrl', function () {
     var waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait...", "Please wait...", 100, 300);
        LaunchPickerTreeDialogSelectUrl('CbqPickerSelectListTitle', 'CbqPickerSelectListText', 'websListsFolders', 'SPList:'+ListId+'?SPWeb:'+WebId+':', _spPageContextInfo.siteAbsoluteUrl, '', '', '', iconUrl, '', callback, 'true', '');
        waitDialog.close(SP.UI.DialogResult.OK);
 });
}

 loadScript(_spPageContextInfo.webAbsoluteUrl+"/_layouts/15/pickertreedialog.js", function(){});  

EnableScript (Validate if one file is selected)

javascript: var EnableDisableItem = function() 
    {   
        this.clientContext = SP.ClientContext.get_current();  
        this.selectedItems = SP.ListOperation.Selection.getSelectedItems(this.clientContext);  
        if (selectedItems.length==1)  {  
            if (selectedItems[0].fsObjType == 0)  
                {return true;}  
                else   
                    {return false;}  
        }  
        if (selectedItems.length!=1)  
            {return false;}  
    };

    EnableDisableItem();  


The Ribbon Manager Interface provides existing Ribbons and the creation of new Ribbons such us "Copy Document".

Code associated in the Ribbon Action Copy Document.




Copy ListItem with Metadata

This Custom Action Creates a new ListItem and copy the Metadata from the selected Item and includes in the New ListItem. 




For the XML structure of the Ribbon Configuration you can use the following:
<CommandUIExtension xmlns=\"http://schemas.microsoft.com/sharepoint/\">\n<CommandUIDefinitions>\n<CommandUIDefinition Location=\"Ribbon.ListItem.Manage.Controls._children\">\n<Button Id=\"Copy.Item\" LabelText=\"Copy Item\" Image16by16=\"/_layouts/15/1033/images/formatmap16x16.png?rev=33\" Image16by16Left=\"-270\" Image16by16Top=\"-107\" Image32by32=\"/_layouts/1033/images/formatmap32x32.png\" Image32by32Left=\"-382\" Image32by32Top=\"-190\" ToolTipTitle=\"Copy Item\" Command=\"Copy.Item.Command\" TemplateAlias=\"o1\" />\n</CommandUIDefinition>\n</CommandUIDefinitions>\n<CommandUIHandlers>\n<CommandUIHandler Command=\"Copy.Item.Command\" CommandAction=\"<Code>" EnabledScript=\"<Code>" />\n</CommandUIHandlers>\n</CommandUIExtension> 


Code

This JavaScript code create a new ListItem with Metadata from the selected item.
CommandAction:

Javascript:

function runCode(ListId) {

    ListId.replace("{", "");

    ListId.replace("}", "");

    var targetListItem;
    var values = SP.ListOperation.Selection.getSelectedItems();
    var clientContext = new SP.ClientContext.get_current();
    var targetList = clientContext.get_web().get_lists().getById(ListId);
    targetListItem = targetList.getItemById(values[0].id);
    clientContext.load(targetListItem);
    clientContext.executeQueryAsync(function () {
        var itemCreateInfo = new SP.ListItemCreationInformation();
        var oListItem = targetList.addItem(itemCreateInfo); 
        oListItem.set_item('Title', targetListItem.get_item('Title'));  
        oListItem.update();
        clientContext.load(oListItem); 
        clientContext.executeQueryAsync(function(){
            SP.UI.Notify.addNotification("Item created!", false);
            SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
       },Function.createDelegate(this, this.onQueryFailed));
    
   },Function.createDelegate(this, this.onQueryFailed));
   }
   
   function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
runCode('{ListId}');

EnableScript (Validate if one Item is selected)

javascript: var EnableDisableItem = function() 
    {   
        this.clientContext = SP.ClientContext.get_current();  
        this.selectedItems = SP.ListOperation.Selection.getSelectedItems(this.clientContext);  
        if (selectedItems.length==1)  {  
            if (selectedItems[0].fsObjType == 0)  
                {return true;}  
                else   
                    {return false;}  
        }  
        if (selectedItems.length!=1)  
            {return false;}  
    };
    EnableDisableItem();  


As you can see, very easy. :)
I hope you like this article,

Best regards, 
André Lage
Post a Comment