List all attachments when clicking the paperclip in a list view

Change log:

07.10.2011 A new version is published – you find it here.

23.09.2010 Moved the code to a server for direct download to make it easier for the users. You find the link below. The current stable version is 1.5.

13.09.2010 Fixed bug when ID column was not placed to the far right.

07.09.2010 Fixed bug when list view was not the topmost webpart.

30.08.2010 Added “one click open” if only one attachment is found.


I got this request from Chris:

…the challenge I’m currently trying to solve is to get the attachments paperclip in a listview clickable. Using a doclib and linking against the file is not an option since we are talking about a lot of files with the same name which should be stored with the list entry (one file per entry).

There’s a solution from Paul Grenier at EUSP, but that doesn’t work for large collections, so it’s not usable.

I thought of setting up the path ‘manually’, and displaying this entry, since I noticed that the attachment path is always like URL/site/lists/listname/attachments/list_item_id/filename. Though I might be able to come up with all the details up to the ID I have no idea on how to get the filename automatically.

Can you think of any other way to make the paperclip clickable to open the attachment?

Thanks,
Chris


Here we go:

This method uses the webservice lists.asmx and the operation GetAttachmentCollection.

It is tested in IE8, Chrome 5.0 and Firefox 3.6.8 in WSS3.0. It works in both standard list views, and grouped views.

It has briefly been tested in SP2010, but is only partially compatible (minor issue with the click on the paperclip selecting the row, and it only works in non-grouped views).

The only requirement for this solution to work is the ID column being in the view – it can be hidden by setting the variable hideIdColumn = true (default).

The CEWP code

[javascript]
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="/test/English/Javascript/previewAttachmentsOnClick.js" type="text/javascript"></script>
<script type="text/javascript">

hideIdColumn = true;
customListAttachments();

</script>
[/javascript]
Place the CEWP below the list view!

Download the file “previewAttachmentsOnClick.js” from this location

Note:

When new versions are released, they will be placed in a folder with the version number as label. Be sure to download the latest version.

If you are using a browser other than IE, right click the file and select “Save link as” or “Save linked content as…”.

As if anything is unclear.

Alexander

64 thoughts on “List all attachments when clicking the paperclip in a list view”

  1. Hi Alex,

    thanks for this solution, works very good! Would it be possible to have the attachment open on first click though if there is only one, without the additional field showing up with the name of the attachment?

    Chris

  2. For IE
    line 140
    content = [];
    should be replaced with:
    var content = [];

    Also in some cases
    line 024
    $(“div[id^=’WebPartWPQ’]”).each(function(){
    should be changed in to:
    $(“div[id^=’WebPartWPQ2′]”).each(function(){

    1. Hi,
      Yes, var content = []; would be correct, but did it interfere with some other scripts?

      Your other note is a bit confusing as the line

      $(“div[id^='WebPartWPQ']“).each(function(){
      

      iterates trough all divs with an ID starting with WebPartWPQ.

      Alexander

    2. with var content = [];
      i had errors in script and the div was not populated with document names.

      as soon as I have added var it started working correctly.

      as for WebPartWPQ, as my page is branded and has lots of customizations, SharePoint used id WebPartWPQ2 for my view web parts.
      The last option I have mentioned just in case someone has similar issues.

  3. Hi Alex,

    thanks for the modification, one small remark though, in the scripts you are referring to “customListAttachents()” which might lead to confusion due to the missing “m”.

    Chris

  4. Hi Alex, nice coding but it isn´t working at all for our site unlike your “old” script. do we have to change something within the code or in our SP definitions?

    KF

  5. Hi Chris,
    1. I add the ID column in the view,
    2. I put the jquery-min.js file into a document library.
    3. I put the code in a CEWP below the list.

    Nothing happens when I click on the paperclip and the ID column is not hidden.

    Did I forget anything?

    Thanks again.

    1. Hi Guigoss,

      first, to clarify, I’ve had troubles getting the CEWP/Script version to run so I’m using the “all in one” version.

      Make sure that you
      – changed line 1 in the single CEWP code according to your doc-lib path, if you are not sure about the correct string just copy the shortcut to the file and insert it.
      – if you have more than one WebPart on the page check line 25 of the CEWP. I had to specifically enter the ID of my WebPart to get it working – also see comment from Jurgis
      You can check your WebPart ID by looking at the source of the page, search for “Add a new item to this list.” The WebPartID will be in the paragraph above this text (td id=”MSOZoneCell_WebPartWPQx…)

  6. Hi Chris,
    Thanks a lot. It is fixed now.
    I forgot to modify the WEB PART ID. It ‘s great!!

    Just one note: It doesn’t work when you choose the collapsed view by default. Maybe I’m doing something wrong.

    1. Hi,
      I’m glad you got it working, but i have some questions.

      What is the ID of the webpart you are addressing? – the line

      $("div[id^='WebPartWPQ']").each(function(){
      

      Iterates trough ALL webparts with an ID starting with WebPartWPQ

      It will pick up WebPartWPQ1, WebPartWPQ2 and all others starting with WebPartWPQ.

      Did you put the CEWP below the list view?

      Regarding grouped views: It is tested to work with both initially expanded and initially collapsed views. Is your view modified in some other way (SPD or using another scripts?).l

      Alexander

    2. Hi Alexander,

      although the quoted line is supposed to iterate through all webparts I haven’t been able to get it to work. I had to specifically give the “list” webpart at this place to make the script work at all. As far as I remember there was only one working exception, that was when the “list” webpart was the topmost webpart on the page, with all the others below it.

      Currently I have a “print this list” webpart above the “list” and with this I have to change the line to the WebPartWPQ_ID of the “list” itself.

      Chris

      1. Hi, Thank you for this clarification. I have recreated the bug and will fix it shortly.

        Alexander

  7. Hello Alex, Chris,

    I am very excited about implementing this script (people at work have been asking for something like this for time now). I am also very new to all this, so bear with me. Mind you, I am an end-user with some design control, so I am a bit limited.

    Before the 9/7/10 update, nothing worked (ID column did not hide, paperclip was not clickable), in a list by itself nor a multi-webpart page.

    With the update, on single webpart/list pages, the ID column hides (finally) but hovering over/clicking the paperclip still does not do anything. The attachment I am testing is a jpg and a local file type.

    If I am on our multi-webpart page, a few odd things happen:
    1) The “ID column must be in the view” error comes up, I think because it is checking for it on all web-parts. Setting the ID to the specific webpart fixes this, but if there is a way to check for an attachments column in the view first before checking for an ID column, it can preemptively avoid the error message.

    2) The ID column does not disappear. Instead, the column header along the length of the table “shifts” to the left: ID column header is replaced by the next column header (in this case the Attachment column header). This shifting propogates through the columns until the last column in the list view has no header at all. I am trying this on the same list as mentioned above (which worked with hiding the ID column, clicking attachment did nothing) and I have two other jquery/javascript scripts running (one to make webparts printer friendly and the other to set up a picture slide show). Disabling the other scripts does not help. also, the paperclip does not appear clickable either.

    Not sure if this is reproducible at all.

    1) As an end-user with design priveledges, are any other permissions required for me to get this working?

    2) Seems like a silly question but why is it best to store the jquery.min.js locally?

  8. Alrighty, that seemed to fix the problem in the general case. I tried the script on another page with multiple web parts and it works very well. Thank you much. If the attachment is an excel file, it opens in excel 2007 saying a title property (within the metadata) is missing, but we can deal with that for now.

    For the other page where I had the odd column behavior, the script may be interacting with something. I will try to investigate a bit, but aside from that, things are good.

    Thank you again.

    1. Hi,
      The missing Title property has nothing to do with this solution – to fix it you might want to look at the Title field’s “required” property. If it is not set to “required”, it can be related to the template originating from another SharePoint library. In that case – go to “advanced properties” in Excel and delete the “Title” property from the “Custom properties”.

      Please let me know if you find out more in your problem.

      Alexander

  9. If I open the list attachment from the DispForm for the item (normal method), no metadata errors, opens in edit mode (small warning about viruses, etc, courtesy of IE). Opening using a direct link to the file, however, apparently treats it differently. I thought it might have to do with the method of opening the file (e.g., not using Office 2007 activeX method). After some searching I tried to implement the following event for the attachment links:

    onclick=’DispDocItemEx(this,’FALSE’,’FALSE’,’FALSE’,’SharePoint.OpenDocuments.3′)

    I put this where you generate the links (wrapBuffer.push), but have not been successful so far (the file continues to open through the direct link).

    Adding src=core.js at the top didnt help; I often get a syntax error in IE after I attempt to open a file (bottom left corner). Also tried it with EditDocumentWithProgID2, but also didnt work. I am not familiar enough with this yet.

    As far as the column header shifting over, I deleted the list view webpart and re-made it. this seemed to fix the problem. So, yay.

    1. Trikes,
      if you find a method to have the direct link display the SP warning for opening the file in read-only or edit mode I’d be happy to know about it. Right now direct linked files (view or doc-lib doesn’t matter) open directly in Office 2007 as read-only files and can not be saved back to sharepoint (the doc-lib files in this case).

      Chris

  10. 🙂

    You almost had it…I combined the two onclick events into one line, separated by a semi-colon:

    onclick=’customHideMenu(true);DispDocItem(this,”SharePoint.OpenDocuments.3″)’

    This got it working. Congrats!

    (it still gives an ‘undefined is null or not an object’ error after you open a file; i dont know how to debug that kind of stuff in IE)

    next step: stopping it from refreshing the entire page after it opens a file.
    I tried enclosing the CustomListAttachments function with

    g_varSkipRefreshOnFocus = true;
    g_varSkipRefreshOnFocus = false;

    and this seemed to stop the page from refreshing after you click a file, but it was very tempermental (sometimes it seemed to break the entire code). I’m not sure how these switches work properly, as the page seems to retain the non-refresh even if I removed these from the code after.

    Another bug I just noticed: If you put 2 CEWP for this script because you have two zones where there are attachments, clicking a paperclip causes the file to try to open ‘twice’ (you get the prompt, click OK to open, it opens another prompt after). I think the two scripts may be interfering, so for now, ill just control the webpartWPQ value.

    1. What other scripts do you have on the page? Is it some of my solutions?

      The error you get – does it refer a specific line in the file “previewAttachmentsOnClick.js”?

      This release intended to stop the page from refreshing when you open documents – did it?

      Alexander

  11. Alright, forgive my idiocy with this; I was not sure what you tried to fix with this release (as Lastmod was still ‘open with native sharepoint function’). The error no longer occurs. The page also does not refresh after opening the file. So well done on that.

    Just so you know how i do this: I paste your js file into a txt file and add the “script” parameters and customlistattachment function call to the top. I wasnt sure how to run a js file otherwise in a CEWP.

    As far as the attachment trying to open twice:
    This seems to be an odd very local problem. I tried to duplicate it with other lists with attachments and was not able to. I noticed something though: if I put the your script in the left zone, it will not change lists/paperclips on the right zone. However, if I add your script to the right zone, it changes it for both left and right zones. This only happened in a particular page and may be why it was causing the double-opening. When I put your script only in the right zone, it all worked. i’m going to scratch my head on this one and probably ignore it.

    1. Hi,
      Not at all, i forgot to tell you what was fixed, no wonder you didn’t know!

      I’m glad to get help removing any bugs remaining.

      The behavior you describe with putting the CEWP to the bottom right is due to the fact that the bottom right corner of the page renders last. Due to the script loading “with the page”, it has to be placed below the list view.

      You might want to save the file as a .js file and upload it to a document library (where ALL users have read permission) and use the method for referring a “a centralized file”.

      Alexander

  12. Just wanted to say everything seems to be going well with this latest version of the script, version 1.5. Haven’t hit a bug (yet) but I will stay vigilant.

    Again, very well done. I hope you update the page above with the new script; I’m sure others will not see this version unless they had sifted through the comments.

  13. Sigh. I always find something 🙂

    For multiple attachments, after the little window opens up, you can right-click the link and save target as.

    For single attachments, this isn’t available. Save target as/copy shortcut, etc, are greyed out. It treats the paperclip as a picture instead of a link.

    1. Hi,
      Due to how this script works, this is not possible. The image has no “href” attribute before you click the button and therefore you get no option to “save as” when you right click.

      The reason for this behavior is that the attachments are “linked” upon click and not on page load. This to reduce the load time in lists with many elements.

      Alexander

  14. Thanks a million this is brilliant for my forms library. Jquery is really lovely and this added the polish I needed to my simplified end-user solution. A real pleasure, 3 minutes and it was fixed for me.

  15. Hello Alexander,

    today I found your script and use it with a minor modification: I disable the Autoload function if there is only one attachment, I prefer to get the list of attachment(s).

    Just one open wish is remaining: Would it be possible to change from mouseclick to mousehover for displaying the small attahcment box?

    May I ask for a code example?

    Kind regards

    Michael

    1. Hi,
      Like this – cut from a “prototype” i made earlier:

      thisRow.find(">td[cellIndex="+AttcolIndex+"]").find('img').css('cursor','wait').attr('title','').hover(function(){
      	thisClip = $(this).parent();
      	thisClip.data({'hover':'1'});
      	setTimeout(function(){	
      		if(thisClip.data('hover')=='1'){
      		var allAtt = getAllAttachments(thisListCTX.listName,thisItemID);
      			$("#customAttPreviewWrapper").remove();
      			var attBuffer = [];
      				attBuffer.push("<div id='customAttPreviewWrapper' style='padding:10px;background-color:white;border:1px silver solid;position:absolute' ");
      				attBuffer.push("onmouseout='customMouseOutHideMenu(event)'>"+allAtt+"</div>");								
      			thisClip.prepend(attBuffer.join(''));
      		}
      	},750);
      },function(){
      	thisClip.data({'hover':'0'});		
      });
      

      You will have to do some modifications, but this is an example…

      Alexander

    2. HI 🙂

      I would like to invite you of a Beer or two 🙂

      Works…and works not.
      Have added (substituted) the onclick with onhover at the original script. Hover shows a box, but
      box contains only [Object,Object] and is not clickable to open anything.

      What about this wrapBuff.push code part (approx Line 76 and following at original script)?

      Can you give me an additional hint?
      Kind regards
      Michael

    3. Hi,
      I’m not sure, but if the contents i [object Object] you might need to convert an array to a string before inserting it into the DOM?

      If your “buffer” is an array (using [ and ]), you must convert it to a string using buffer.join(“”) before inserting it into the htnl.

      Alexander

    4. Hi,
      I puzzled some code lines together, mostly cut and paste out of your OnClick.js. It works as I need it.

      I will send it to you by mail, so that you can put it in here or somewhere else, maybe only the changed lines, as another example.

      Kind regards
      Michael

    5. Hi Alexander,

      I am back again, please excuse newbies stupidity.

      As mentioned above, the “showAttachmentonMouseHover” works as discussed with you and your helpful mailings.

      Usually I use it at long List where the list items can have an attachment. MousHover shows popub box containing clickable link for attachment(s).

      Today I like to group such a list a liitle bit to one of the columns.

      It only show after opening the group a blank box with no link inside.

      On a other page, where I use more than this code snippet (e.g. floating the View button to right, collapse long text, toggle quick launch) nothing did work, when I start grouping.

      Can you give an advise how to solve this?
      Kind regards,
      Michael

      (If necessary I will mail sreenshots and code snippets)

      Thanks a lot again!

    6. Hi Michael,
      When combining multiple scripts there can be interference. One possible issue is that you load jQuery multiple times.

      I’m afraid you will have to tweak them in each case.

      When it comes to grouping items, the scripts i have made rely on the function “ExpGroupRenderData” at the bottom of the script. This is the original SharePoint function – the only thing i have added is the call to “this” script at the bottom.

      When combining multiple scripts that uses this same method of “hiking” with the function “ExpGroupRenderData”, you must add all calls to your custom functions to one instance of the function “ExpGroupRenderData”.

      Alexander

    7. Hi Alex, also Thank you for this post. I understand what you are saying, but I did not know how to do. I “solved” the issue using Filters instead of grouping.

      Your call to ExpGroupRenderData is at the parameter view different from Paul Greniers, which will be found here: http://www.endusersharepoint.com/2009/02/20/jquery-for-everyone-collapse-text-in-list-view/

      in others word: I am to stupid to slice and dice the differences and to understand them.

      Thank you for being patient with me and your help.

      Kind Regards
      Michael

  16. Hi Alexander,
    The script is not working in my environment. Only I could able to hide ID column. My envi details are SPS2010 & IE8. can you please suggest how to use the above code?

    Vamsi

  17. Hey Alex… Some how I could able to get all attachments to be displayed. Is it possible to show icons to respective file extensions? I curious to know baout it..

    Thanks,
    Vamsi

  18. Hi,
    I have used the above script in sharepoint 2007 but this script is not working for internet facing site. my development enviorement it is working fine but i am added it on production environment where site is making internet facing in that site the script is not working it is retuning null value please help me figure out the issue.
    Tahnks
    Rohit

  19. Is there a way to use part of the same script to display a link to the attachment in a column instead of “on hover” ? Which part of the script pulls the filename?

      1. Hi michael, I could use a calculated column but I don’t know how to call the [filename] attribute. What would the concatenate formula look like?

        Thanks in advance!

  20. I tried the script but didn’t work for me.
    I instead created a site column called Attachment (of type Hyperlink), later added this site column to my custom list. As I add new items the Attachment field creates an upload kind of control in my form. I click this control to navigate to a document library where my attachments exists. Give it a name and it even allows you to open the attachment in a new window, which is an added bonus. Please note that I tried this in a site where Publishing feature is activated. I haven’t tested it in a Team site environment though.
    I hope this will help someone looking for a similar functionality.

    1. What version of SharePoint are you using. I tried this in SP 2007 but the Attachment column I created does not allow user to browse to files in a library it only allows user to insert a url to the document which they wouldn’t know.

Leave a Reply