Cannot get FileLeafRef property in SharePoint Rest API - rest

Hi we are trying to retrieve the link URL of page in Site Pages using REST API the problem is that we cannot find the Name FileLeafRef property value.FileLeafReaf = null.
function fn_getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return fn_executeJson(url,"POST",null,queryPayload);
}
function fn_getListViewItems(webUrl,listTitle,viewTitle)
{
var url = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return fn_executeJson(url).then(
function(data){
var viewQuery = data.d.ViewQuery;
return fn_getListItems(webUrl,listTitle,viewQuery);
});
}
function fn_executeJson(url,method,headers,payload)
{
method = method || 'GET';
headers = headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if (typeof payload != 'undefined') {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
Thanks.

SharePoint stores the full URL of a file in a hidden column EncodedAbsUrl.
So, you can request it explicitly as:
/_api/web/lists/getbytitle('Site Pages')/items?$select=*,EncodedAbsUrl
After that, you can directly use it somewhat as below, watch out for the quotes :
var items = data.d.results;
$.each(items, function(index, value) {
//Append results to DIV
$("#lstGlobalNews").append("<tr><td class='ms-vb2'><a href="+value.EncodedAbsUrl+" target='_blank'>"+value.Title+"</a></td><td class='ms-vb2' style='text-align: right;'>"+fn_FormatDate(value.Date_x0020_Posted)+"</td></tr>");
});

To retrieve FileLeafRef property, it needs to be explicitly specified in $select query option, for example:
/_api/web/lists/getbytitle('Site Pages')/items?$select=FileLeafRef
As alternative option it could also be retrieved via File resource, for example:
/_api/web/lists/getbytitle('Site Pages')/items?$select=File/Name&$expand=File

The FileLeafRef property only get the file name. If you want to get the file url, we need use ServerRelativeUrl property of file.
The REST API using this.
/_api/web/lists/getbytitle('Site%20Pages')/items?$select=File/ServerRelativeUrl&$expand=File

Related

upload file into document library in sharepoint with column value

Iam trying to upload file into document library but I can able to upload file but however column data was not reflecting into the column of document library.using rest Api every thing is working but my column value was not showing inside the column
here is my code
function createListItem() {
debugger;
var files = $("#attachment")[0].files;
if (files.length > 0) {
fileName = files[0].name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary = "MyDocumets";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
// Construct the Endpoint
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?#target='" + targetUrl + "'&$expand=ListItemAllFields";
uploadFileToFolder(files[0], url, function(data) {
var file = data.d;
DocFileName = file.Name;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type},
"DocumentType": $('#documenttype').val(),
"DocumentDescription": $("#Description").val(),
FileLeafRef: DocFileName //FileLeafRef --> Internal Name for Name Column
};
alert("File uploaded successfully!");
}, function(data) {
alert("File uploading failed");
});
} else {
alert("Kindly select a file to upload.!")
}
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileObj);
// Add the file to the SharePoint folder.
getFile.done(function(arrayBuffer) {
$.ajax({
url: apiUrl,//File Collection Endpoint
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function(data) {
success(data);
},
error: function(data) {
success(data);
}
});
});
}
// Get the local file as an array buffer.
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
i wanted to know how to enter value into the column and upload the document at the sane time

How to get items from SharePoint by Current User via REST or JSOM?

I have a SharePoint list with two columns:
users (type people, multiple values allowed)
responsible_department (type string)
I want to get the items from this list where the current user is in the ùsers` field. The field can have multiple users (multiple users allowed)!
I am currently able to get the current user:
var currentUser;
function init() {
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
console.log(currentUser.get_loginName());
}
function onQueryFailed(sender, args) {
console.log('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
No i need to query the mutli user field in my list for all items where my current user is part of the people field. I dont know how to query for this.
Can someone help me out?
I found a solution on MSDN and this works for me:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var siteURL = _spPageContextInfo.webAbsoluteUrl;
var listname = "CustomList";
var currentUserId=_spPageContextInfo.userId;
var url = siteURL + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Title,PeopleField/ID&$filter=substringof('"+currentUserId+"',PeopleField/ID)&$expand=PeopleField/ID";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
var item=items[i];
console.log(item.Title);
}
},
error: function (data) {
}
});
});
</script>

Post reply on SharePoint online discussion board using REST API

I am trying to post reply on a particular discussion of SharePoint online discussion board through REST API but unable to do it. I don't want to use SP.utilities as this REST API will be called from Android App.
Below is the code which I am implementing:
$.ajax({
url:"../_api/web/Lists/getbytitle(listname)/items?$filter=ParentItemID eq 40",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: function (data) {
alert("Successfully posted!!");
},
error: function (error) {
alert("error");
console.log(JSON.stringify(error));
}
});
Instead of creating reply inside discussion, it is creating a new discussion item.
Any help will be highly appreciated.
For creating a message item (reply) in Discussion Board the following properties needs to be specified:
FileSystemObjectType for a message items needs to be set to 0
ContentTypeId- content type Id of message item
ParentItemID - discussion item (container for messages) id
Regarding ParentItemID property
ParentItemID property could not be specified via message payload since it is a read only property, it means the following query for creating a message item fails:
Url /_api/web/lists/getbytitle('Discussions')/items
Method POST
Data {
'__metadata': { "type": "SP.Data.DiscussionsListItem" },
'Body': "Message text goes here",
'FileSystemObjectType': 0,
'ContentTypeId': '<MessageContentTypeId>',
'ParentItemID': <DiscussionItemId>
}
Solution
The following example demonstrates how to to create a message (reply) in Discussion Board via SharePoint REST API.
For creating a message under a discussion item (folder) the following
approach is used: once message item is created, it's getting moved
under a discussion item
var listTitle = "Discussions"; //Discussions Board title
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var messagePayload = {
'__metadata': { "type": "SP.Data.DiscussionsListItem" }, //set DiscussionBoard entity type name
'Body': "Message text goes here", //message Body
'FileSystemObjectType': 0, //set to 0 to make sure Message Item is created
'ContentTypeId': '0x0107008822E9328717EB48B3B665EE2266388E', //set Message content type
'ParentItemID': 123 //set Discussion item (topic) Id
};
createNewDiscussionReply(webUrl,listTitle,messagePayload)
.done(function(item)
{
console.log('Message(reply) has been sent');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
where
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("data" in options) {
ajaxOptions.data = JSON.stringify(options.data);
}
return $.ajax(ajaxOptions);
}
function createListItem(webUrl,listTitle,payload){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"data": payload
});
}
function moveListItem(webUrl,listTitle,itemId,folderUrl){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")?$select=FileDirRef,FileRef";
return executeJson({
"url" :url
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
return executeJson({
"url" :url,
"method": 'POST'
});
});
}
function getParentTopic(webUrl,listTitle,itemId){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")/Folder";
return executeJson({
"url" :url,
});
}
function createNewDiscussionReply(webUrl,listTitle, messagePayload){
var topicUrl = null;
return getParentTopic(webUrl,listTitle,messagePayload.ParentItemID)
.then(function(result){
topicUrl = result.d.ServerRelativeUrl;
return createListItem(webUrl,listTitle,messagePayload);
})
.then(function(result){
var itemId = result.d.Id;
return moveListItem(webUrl,listTitle,itemId,topicUrl);
});
}

Using REST to fetch SharePoint View Items

I am trying to construct the correct URL to return the items in a SharePoint View using the REST api.
Using my browser and the following URL I can return the items in the list.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Items
And I can get the view definition using the following URL.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Views/getbytitle('Latest News')/
But I cannot figure out what I need to put at the end of that URL to actually get the items that are returned by the the View.
SP.View object does not contain any methods for manipulating list items. But SP.View object contains SP.View.viewQuery property that specifies the query that is used by the list view. That means the following approach could be used for retrieving list items for view:
perform the first request to get CAML Query for List View using SP.View.viewQuery property
perform the second request to retrieve List Items by specifying CAML Query
How to return list items for a List View using REST API using JavaScript
function getJson(url)
{
return $.ajax({
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return $.ajax({
url: url,
method: "POST",
data: JSON.stringify(queryPayload),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose"
}
});
}
function getListItemsForView(webUrl,listTitle,viewTitle)
{
var viewQueryUrl = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return getJson(viewQueryUrl).then(
function(data){
var viewQuery = data.d.ViewQuery;
return getListItems(webUrl,listTitle,viewQuery);
});
}
Usage
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'Announcements','Latest News')
.done(function(data)
{
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
console.log(items[i].Title);
}
})
.fail(
function(error){
console.log(JSON.stringify(error));
});

JQuery ajax form submit works when debugging but not without

I've got a form that is loaded on to a page using ajax. The form is then submitted using the malsup jquery form plugin.
Strangely the form works when I add a firebug breakpoint line or an alert into this method, but when I remove the alert or debug, the submit code never runs.
function addAttachment(attachmentType, path){
var typeSplit = attachmentType.split(":");
if(path == null){
path = "";
}
var url = "/add/" + typeSplit[0] + "/" + typeSplit[1];
addOverlayDivs(); //adds div to load the form into
// load the form
var snippet = $('#overlay').load(url, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#overlay").html(msg + xhr.status + " " + xhr.statusText);
}
});
var prefix = typeSplit[0];
var type = typeSplit[1];
//this alert will cause the submit form to work
alert("bind overlay called");//if I comment this out the formsubmit doesn't work
var options = {
target: null, // target element(s) to be updated with server response
beforeSubmit: showRequest,
success: showResponse,
url: "/add/" + prefix + "/" + type,
type: "POST",
dataType: "json"
};
$('#overlayForm').submit(function() {
$(this).ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});}
I've tried with and without using $(document).ready and that doesn't make a difference.
Any ideas?
May be you need to call later part of your function after load completed,Try this
$(document).ready(function(){
function addAttachment(attachmentType, path){
var typeSplit = attachmentType.split(":");
if(path == null){
path = "";
}
var url = "/add/" + typeSplit[0] + "/" + typeSplit[1];
addOverlayDivs(); //adds div to load the form into
// load the form
var snippet = $('#overlay').load(url, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#overlay").html(msg + xhr.status + " " + xhr.statusText);
}
Dowork();//function call after load complete
});
}
function Dowork(){
var prefix = typeSplit[0];
var type = typeSplit[1];
//this alert will cause the submit form to work
var options = {
target: null, // target element(s) to be updated with server response
beforeSubmit: showRequest,
success: showResponse,
url: "/add/" + prefix + "/" + type,
type: "POST",
dataType: "json"
};
$('#overlayForm').submit(function() {
$(this).ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
}
});