SharePoint 2010 ECMAscript – Copy\Move files to another document library – Part 2

Follow Us :

This is the Part 2 of Copy documents example. In case you have missed Here is Part 1

Here is the complete code that needs to go in the elements.xml file –

<?xml version=”1.0″ encoding=”utf-8″?>
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”>
<CustomAction
Id=”CopyingFilesButton”
Location=”CommandUI.Ribbon”
RegistrationId=”101″
RegistrationType=”List”
Title=”Copy Documents”>
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location=”Ribbon.Documents.Manage.Controls._children”>
<Button Id=”Ribbon.Documents.Manage.CopyDocuments”
Command=”CopyDocumentsButtonCommand”
LabelText=”Copy Documents”
Image32by32=”/_layouts/1033/IMAGES/ImgCopy.bmp”
TemplateAlias=”o1″ />
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command=”CopyDocumentsButtonCommand”
CommandAction=”javascript:
var context = SP.ClientContext.get_current();
var web = context.get_web();
context.load(web);

var _destinationlib = web.get_lists().getByTitle(‘DestinationLibrary‘);
context.load(_destinationlib);
var notifyId;
var currentlibid = SP.ListOperation.Selection.getSelectedList();

var currentLib = web.get_lists().getById(currentlibid);

var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
var count = CountDictionary(selectedItems);

for(var i in selectedItems)
{
alert(‘Now copying ‘ + i);
var currentItem = currentLib.getItemById(selectedItems[i].id);
context.load(currentItem);

var File = currentItem.get_file();
context.load(File);

//Excecuting executeQueryAsync to get the loaded values
context.executeQueryAsync
(
function (sender, args) {
if(File != null) {

var _destinationlibUrl =  web.get_serverRelativeUrl() + _destinationlib.get_title() + ‘/’ +  File.get_name();

File.copyTo(_destinationlibUrl, true);
notifyId = SP.UI.Notify.addNotification(‘Moving file…’ + File.get_serverRelativeUrl() + ‘to’ + _destinationlibUrl, true);

//Excecuting executeQueryAsync to copy the file
context.executeQueryAsync(
function (sender, args) {
SP.UI.Notify.removeNotification(notifyId);

SP.UI.Notify.addNotification(‘File copied successfully’, false);
},
function (sender, args) {
SP.UI.Notify.addNotification(‘Error copying file’, false);
SP.UI.Notify.removeNotification(notifyId);
showError(args.get_message());
});
}
},
function (sender, args) {
alert(‘Error occured’ + args.get_message());
}
);
}
“/>
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>

</Elements>

Once done adding the code just hit f5 . Make sure you have the “DestinationLibrary” named library in your current site.

Test –

Select the document in the document library and click on the custom ribbon button

The User gets notified –

Final Notification after the file is copied –


Tags: SharePoint 2010