Tuesday, July 10, 2018

Replace SharePoint attachment icons with hyperlink names in list view webpart

Many times we allow users to upload attachment to the list items.

However if you add the "Attachments" column to your list views, you get a column that only shows a icon (see below) if there are any attachments.

fig 1.1

Clicking that paperclip also won’t open any attachment or the list item to open the document in new window. It’s strictly an image. Here’s a way to replace that icon on each row with the actual name of your attachment linked to the actual attachment. If there are more than 1 document attached then it displays all documents links with name and link to open it.

Download this below code, or copy and paste it into a new file in your Site Assest folder as ShowAttachments.js:

(function () {

    // Create object that have the context information about the field that we want to change it output render  

    var attachmentsFiledContext = {};

    attachmentsFiledContext.Templates = {};

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

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(attachmentsFiledContext);

})();


// 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);
}

//get attachments field properties
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 += "" + data.d.results[i].FileName + "";
                if (i != data.d.results.length - 1) {
                    str += "
";
                }                
            }          
        },
        error: function (err) {
            //alert(err);
        }
    });
    return str;
}

Edit the List view page on which you want to add above functionality.

Edit the list view webpart > miscellaneous > Js Link

If you have already refer "jquery-1.11.1.min.js" in your master page then just refer ShowAttachments.js else Add following URL into the JS Link text box.

~site/SiteAssets/jquery-1.11.1.min.js|~site/SiteAssets/showAttachments.js
Final result will be this:



1 comment:

Anonymous said...

I’d like to export the list metadata and attachment names to excel, but the file name doesn’t export. Any ideas on how to do this?

Thank you,
Stacy