Quick Win – Display attachments in list

win

Hello everyone,

Today, in the Quick Win series, I’ll talk about the possibility to view attachments in a list view.

By default, when you have one or more attachments to a list item, you see this

attachment1

If you open the properties of the item, you see the full list of attachments

attachment2

To display the full list of attachments in the view of your list, simply add the following JSLink (don’t forget to fix the path for the JQuery file)

(function () { 

// jQuery library is required
(window.jQuery || document.write('<script src="PATH/jquery.min.js"><\/script>'));
// Create object that have the context information about the field that we want to change it output render  

var linkFiledContext = {};
linkFiledContext.Templates = {};
linkFiledContext.Templates.Fields = {
"Attachments": { "View": AttachmentsFiledTemplate }
}; 

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(linkFiledContext); 

})(); 

// This function provides the rendering logic for list view
function AttachmentsFiledTemplate(ctx) {
var itemId = ctx.CurrentItem.ID;
var listName = ctx.ListTitle;
return getAttachments(listName, itemId);
} 

function getAttachments(listName,itemId) {
var url = _spPageContextInfo.webAbsoluteUrl;
var requestUri = url + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")/AttachmentFiles";
var str = "";
// execute AJAX request
$.ajax({
url: requestUri,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
async: false,
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
str += "<a href='" + data.d.results[i].ServerRelativeUrl + "'>" + data.d.results[i].FileName + "</a>";
if (i != data.d.results.length - 1) {
str += "
";
}
}
},
error: function (err) {
console.log(err)
}
});
return str;
}

Et voila!

attachment3

I wish I had the idea but I did not write this code, I found it on this msdn topic (Thanks Denis Guo)

Hoping this helps!

Christopher

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s