Create a copy of document in SharePoint 2010 document library using JavaScript - javascript

I want to create a copy of document in the SharePoint document library.
Basically let us assume there is a template and every user will open the document by clicking on it. I want to create a copy of file user has clicked and open that file for editting.
I have tried using JavaScript Client Object model of SharePoint. But the examples are for manipulating list items but not for document library.
Can any one please point to any sources that I can use to manipulate the files in document library
One restriction being I need to use JavaScript object model or web services to achive this functionality. i.e., NO server side code
Following is the code I got till now
The approach I am planning to use is copy the existing file object
Rename it and
Save it to other document library
Please ignore formatting as I am not able to do it properly and this is under development code
<script type="text/javascript">
var clientContext = null;
var web = null;
var meetingItems = null;
var filePath = null;
var file = null;
debugger;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize() {
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.list = web.get_lists().getByTitle("Documents");
clientContext.load(list, 'Title', 'Id');
var queryStart = "<View>"+ "<Query>"+ "<Where>"+ "<Eq>"+ "<FieldRef Name='Title'/>" + "<Value Type='Text'>";
var queryEnd = "</Value>"+ "</Eq>"+ "</Where>"+ "</Query>"+ "</View>";
camlQuery = new SP.CamlQuery();
queryMeeting = queryStart + 'DevCookbook'+ queryEnd;
camlQuery.set_viewXml(queryMeeting);
meetingItems = list.getItems(camlQuery);
clientContext.load(meetingItems);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onListLoadSuccess), Function.createDelegate(this, this.onQueryFailed));
}
function onListLoadSuccess(sender, args) {
filePath = meetingItems.get_item(0).get_path();
file = meetingItems.get_item(0);
debugger;
clientContext.load(file);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onFileLoadSuccess), Function.createDelegate(this, this.onFileFailed));
// alert("List title : " + this.list.get_title() + "; List ID : " + this.list.get_id());
// doclist();
}
function doclist()
{
var path = file.get_title();
path = meetingItems.get_item(0).get_file().get_title();
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
function onFileLoadSuccess(sender, args) {
debugger;
alert("List title : " + this.list.get_title() + "; List ID : " + this.list.get_id());
}
function onFileFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

I used copy webservice to do the functionality.
Approach is combination of Object Model and JavaScript functions
Copy the file from templates library.
Check out file using "CheckoutDocument" function
Add metadata in background
Show edits metadata pop up to user using
var oDialog = {
url: "../Library/Forms/Edit.aspx?ID=" + itemID,
title: "Create a new document"
};
SP.UI.ModalDialog.showModalDialog(oDialog)
After user input check in the document

Related

Edit Reply Message (comment) to a Discussion - SharePoint Online JavaScript

I need to do this in JavaScript since the entire solution is current in JavaScript and this is the last part.
I need to be able to update a reply message (comment) to an existing discussion. I am able to change the discussion fields but not the message fields. I know the message and the discussion are two different content types and that the reply messages are under a folder for the discussion but I don't know how to edit the reply message. (There is a utility to add the reply message but not to edit it).
This is a sample of the discussion (in the list) in which you can see there are 5 replies, I want to change the body text of one of the replies via JavaScript.
Image of the Discussion Showing Replies I would like to update
And for example, I want to change the message below:
Image of Replies that I want to change the body text
I have tried to update using this code, but it only changes the discussion and not the message.
I have a feeling I need to tell the system to go into that folder to find the message and change its body text, but I am not sure how to do this and after a 2 day search on the interwebs, I can't find an answer.
Code that does not work:
function aeditListItem() {
var clientContext = new SP.ClientContext();
var oList = clientContext.get_web().get_lists().getById('40b2fbd4-4f87-d92fb05f8044'); //ID changed to protect client
this.oListItem = oList.getItemById(getParameterByName('commentid'));
oListItem.set_item('Body', document.getElementById("ideaDetails").value.replace(/\r?\n/g, '<br />'));
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded() {
alert('Item Updated: ' + oListItem.get_id());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
Many Many THANKS!
Apparently at the line:
this.oListItem = oList.getItemById(getParameterByName('commentid'));
getParameterByName('commentid') does not return the proper message id, make sure the message list item id is specified.
As a proof of concept the following example shows how to:
find a message by body
replace the message with a new body
Example
var listTitle = "Discussions";
var oldMessageBody = "";
var newMessageBody = "";
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var items = list.getItems(createMessageFindQuery('Body',oldMessageBody));
ctx.load(items);
ctx.executeQueryAsync(
function(){
if(items.get_count() == 1){
var foundItem = items.getItemAtIndex(0);
foundItem.set_item('Body',newMessageBody);
foundItem.update();
ctx.executeQueryAsync(
function(){
console.log("Updated");
},
function(sender,args){
console.log(args.get_message());
});
}
else
console.log('Not found or multiple items are found')
},
function(sender,args){
console.log(args.get_message());
});
});
function createMessageFindQuery(fieldName,fieldVal){
var qry = new SP.CamlQuery;
qry.set_viewXml(String.format('<View Scope="RecursiveAll"><Query><Where><Contains><FieldRef Name="{0}" /><Value Type="Text">{1}</Value></Contains></Where></Query></View>',fieldName,fieldVal));
return qry;
}

How to get active directory user name without domain name?

I am getting this in my SharePoint output in script editor. executions as follows:
i:0#.w|iscsharepoint\administrator
The code for this is as follows for this
<script type="text/javascript">
function GetLoggedInUserName()
{
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
this.currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args)
{
alert(currentUser.get_loginName());
}
function onQueryFailed(sender, args)
{
alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}
</script>
Now I am trying to get it this excution.
"Hi Administrator"
You can parse the username manually, like so:
var name = currentUser.get_loginName().split("\\")[1];
alert("Hi " + name);
You can also retrieve the user's actual name instead of their login name:
var name = currentUser.get_title();
alert("Hi " + name);

WinJS forward custom object to print function

I use WinJS in my application and try to print some content. Made my printer class according to this tutorial https://dzone.com/articles/windows-8-print-contract-%E2%80%93.
function registerForPrintContract(participiantData) {
var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
printManager.addEventListener("printtaskrequested", onPrintTaskRequested, false);
}
function onPrintTaskRequested(printEvent) {
var printTask = printEvent.request.createPrintTask("Print Example", function (args) {
printCurrentPage(args);
printTask.oncompleted = onPrintTaskCompleted;
});
}
function printCurrentPage(args) {
var docHtml = document.createDocumentFragment();
docHtml.appendChild(createDocumentContent());
args.setSource(MSApp.getHtmlPrintDocumentSource(docHtml));
}
function createDocumentContent() {
var container = document.createElement("div");
container.innerHTML = "<h2>" + firstname + " " + lastname + "</h2>" +
"<h4>" + emailaddress1 + "<h4>";
return container;
}
function showPrintUI() {
Windows.Graphics.Printing.PrintManager.showPrintUIAsync();
}
My problem is that I do not know how to forward some object data to createDocumentContent() function. In this example I put firstname, lastname and email. Those data I cannot get from html page I need to send them on print button click.
All examples I saw are about printing current page or making new content from data which we can get from HTML page by querying DOM, no example where I can send custom object.
What is the best way to do this ?
My problem is that I do not know how to forward some object data to createDocumentContent() function. In this example I put firstname, lastname and email. Those data I cannot get from html page I need to send them on print button click.
Do you mean you want to put the html output of "<h2>"+firstname + " " +lastname+"</h2>"+"<h4>" + emailaddress1 + "<h4>" to your print page?
The behavior of innerHTML has changed in Windows Store App Development.
see HTML and DOM API changes list innerHTML section:
Content is filtered as through it was processed by the toStaticHTML method
But WinJS offers a method that you can utilize to inject HTML.
Here is the link to documentation of this method: WinJS.Utilities.insertAdjacentHTML
Here is a code snippet that shows a simple use this method:
function createDocumentContent() {
var obj = {
firstname: "winffee",
lastname: "xia",
emailaddress1:"test#126.com"
}
var htmlString = "<h2>" + obj.firstname + " " + obj.lastname + "</h2>" +
"<h4>" + obj.emailaddress1 + "<h4>";
var container = document.createElement("div");
WinJS.Utilities.insertAdjacentHTML(container, "beforeend", htmlString);
return container;
}

child links in quick launch navigation in sharepoint

https://msdn.microsoft.com/en-us/library/office/jj247080.aspx
based on example on this site for getting quick lunch url and quick lunch title
we have something like this
while (nodeEnumerator.moveNext()) {
var node = nodeEnumerator.get_current();
nodeInfo += '{"title":"' + node.get_title() + '",' + '"link":"' + node.get_url() + '"},';
}
but if any of those navigation urls have any childs I don't know how to get that
so how to get that?
Use SP.NavigationNode.children property to get the collection of child nodes of the navigation node.
Note: SP.NavigationNode.children property needs to be requested
explicitly in query, this is why in the below example it is specified via Include expression:
ctx.load(quickLaunchNodes,'Include(Title,Url,Children)');
Example
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var quickLaunchNodes = web.get_navigation().get_quickLaunch();
ctx.load(quickLaunchNodes,'Include(Title,Url,Children)');
ctx.executeQueryAsync(function() {
printNodesInfo(quickLaunchNodes);
},
function(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
});
function printNodesInfo(nodes){
nodes.get_data().forEach(function(node){
var childNodes = node.get_children();
console.log(String.format('{0} child nodes:',node.get_title()));
childNodes.get_data().forEach(function(childNode){
console.log(String.format('Title: {0} Url: {1}',childNode.get_title(),childNode.get_url()));
});
});
}

Query SharePoint List Using JavaScript

I'm trying to obtain values from a SharePoint 2010 list. The List name is "SitesList" at the URL of "servername/sites/dev/Lists/SitesList/AllItems.aspx". The Columns that I would like to print on the alert message "Title" and "URL."
Once I run everything, the page loads but nothing happens at all. I can see that my web part is there and I even switched out the code to something simple like an alert message and it works. What am I doing wrong?
<script type="text/javascript">
var siteUrl = '/sites/dev/';
function retrieveListItems() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('SitesList');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Geq><FieldRef Name=\'ID\'/>" + "<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>");
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() +
'\nTitle: ' + oListItem.get_item('Title') +
'\nURL: ' + oListItem.get_item('URL');
}
alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
It looks like you're never actually triggering the retrieveListItems function.
Try adding this at the top of you script, after the var siteUrl:
<script type="text/javascript">
var siteUrl = '/sites/dev/';
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
function retrieveListItems() {
...
}
...
</script>
This is SharePoint specific and will wait for SP.JS to load before executing the retrieveListItems function.
This is typically a more recommended approach than jQuery's document.ready function, or native JS's self executing functions as many things happen behind the scenes with SharePoint apps after the page loads.
Hope this helps!

Categories

Resources