vrijdag 28 januari 2011

Easy way to add document links to listitems

The task seems easy enough: Using Sharepoint 2010, attach documents to a listitem.

Sure, no problem. Sharepoint offers out of the box attachments for any type of list.

Done. One would say. At least, I said so.
No, the documents are already sitting and waiting in a document library. We don't want to add new documents, and we sure don't want to have the same document multiple times in our database.

First, when using default attachments, the document are "physically" uploaded for each listitem. 
Second, managing these attachments is, well, not the way one wants to manage documents.

We wanted to attach existing documents to multiple listitems and one place to manage those documents. That way new document revisions would be up to date for each listitem the document is linked to. 

Despite some great tools that could accomplish this task, we found these often to be too complicated when it comes to background management. The multiple lookup field also wasn't quite what we wanted.

We came up with a quick and dirty solution: Just add hyperlinks to a listitem's rich text field by clicking on the desired document.

How we did what:
  1. Add a rich text field to a list. For this example, call it MyAttachments
  2. In Sharepoint Designer, open the NewForm.aspx and EditForm.aspx of the list.
  3. In both these pages, add the desired document library at the bottom of the page: Insert -> DataView.
  4. Add a javascript reference to the latest jQuery.js to the PlaceHolderAdditionalPageHead section
  5. Add this script:
_spBodyOnLoadFunctionNames.push('SetDocumentSelector');

var LinksHTML = '';
var Fields = null;
var RtfField = null;
var RtfTextBox = null;

function SetDocumentSelector() {
// Get all fields of this list. 
Fields = init_fields();
// Get the contentfield of the rich text field and hide it.
RtfField = $(Fields['MyAttachments']).find('div[contenteditable]:first');
RtfField.parents('tr:first').hide();
// if the contentfield was found, get the hidden textbox where the plain input is stored.
if (RtfField.length>0 && typeof(RtfField.attr('inputfieldid'))!='undefined') {
RtfTextBox = $('#'+RtfField.attr('inputfieldid'));
}
// The textbox is present? 
if (RtfTextBox!=null && RtfTextBox.length>0) {
// process possible existing value.
if (RtfTextBox.val().length>0) {
SetStartupCheckboxes();
}
// Attach onclick event to the checkbox of each listitem in the documentlibrary.
$('tr.ms-itmhover, input:checkbox.s4-itm-cbx').click(ProcessSelection);
}
}

// Gather all document IDs stored in the id attribute in the hyperlinks in the rich text field.
function SetStartupCheckboxes() {
var reItemID = new RegExp('\\sid=\\d+','gi');
var reID = new RegExp('\\d+','g');
var ItemIDs = RtfTextBox.val().match(reItemID);
if (ItemIDs!=null && ItemIDs.length>0) {
ItemIDs = ItemIDs.join(',').match(reID);
while (ItemIDs!=null && ItemIDs.length>0) {
SetCheckbox(ItemIDs.pop());
}
}
}

// set the checkbox of a listitem in the documentlibrary.
function SetCheckbox(id) {
var DocumentLinks = $('tr.ms-itmhover div.itx[id='+id+']').parents('tr.ms-itmhover:first');
if (DocumentLinks.length>0) {
var Row = DocumentLinks.get(0);
ToggleItemRowSelection2(CtxFromRow(Row), Row, true, true );
}
}

// Find all checked documents and generate html hyperlinks to these documents.
function ProcessSelection() {
RtfField.empty();
var CheckedBoxes = $('input:checkbox.s4-itm-cbx:checked');
if (CheckedBoxes.length>0) {
var CheckedRows = CheckedBoxes.parents('tr.ms-itmhover');
var DocumentCell = CheckedRows.find('div.itx');
LinksHTML = '';
DocumentCell.each(ParseDocument);
RtfField.append(LinksHTML);
}
}

// Create HTML for a single hyperlink to a document.
function ParseDocument(index) {
var Cell = $(this);
var Link = Cell.children('a:first');
var DocumentID = Cell.attr('id');
var DocumentName = Link.text();
var DocumentLink = Link.attr('href');
var NewLink = '<a href="'.concat(DocumentLink,'" id="',DocumentID,'">',DocumentName,'</a><br/>');
LinksHTML = NewLink.concat(LinksHTML);
 }

// find all formfields. Quick and dirty. 
function init_fields() {  
var res = {};
$("td.ms-formbody").each(function(){  
var Local = $(this).html();
var FINindex = Local.indexOf('FieldInternalName="');
if(FINindex>=0) {  
var start = FINindex+19;  
var stop = Local.indexOf('FieldType="')-7;  
var nm = Local.substring(start,stop);  
res[nm] = this.parentNode; 
}
});  
return res;  
}

All you need to do is check one ore more documents which then will be added as a hyperlink to your listitem. Everytime these forms is loaded, the linked documents will already be checked in the document library on the page.

Looking at the picture below (it's Dutch, but as a sharepoint user, you'll understand), you will see an other nice side effect of the approach: while creating a new listitem, you can manage the library on the page itself.


Ofcourse, as stated before, it's quick and it's dirty: when a document is removed from the library, clicking on that hyperlink will result in a Not Found error. 

The HTML can be made into whatever form you want, but be aware that the rich text field won't allow just anything: if it doesn't like your input, it will remove or replace parts of it. 

Hope you can make some good use of it.

Regards,
Ruud.