Pages

Thursday, March 12, 2009

Passing ID through QueryString in SharePoint Lists

The customer wanted a publishing site with a custom list for "news articles" and a "comment on this article" section. The Comments was a separate list displayed on that page that only displayed the comments for the article on the publishing page.
First, I modified the DispForm.aspx for the article list to put the "comments" list on it and filter out all of the comments that weren't associated with the article being displayed.
For the user to comment on an article, I had to pass the article ID through to a hidden field on the Comments list. I passed it through a query string when the user clicks on "make a comment", then have that value prefill a hidden field in the comment list. This is a fantastic post on this subject: http://geekswithblogs.net/SoYouKnow/archive/2008/12/24/creating-a-sharepoint-list-parent--child-relationship---out.aspx
The post was a great way to get the query string to pass through by modifying the dispForm.aspx, but I was having diffculty getting the script provided to prefill the item on NewForm.aspx.
Then, I found a this script to put on NewForm.aspx:
<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("fillDefaultValues");
var vals = new Object();
var navBarHelpOverrideKey = "wssmain";
function fillDefaultValues() {
var qs = location.search.substring(1, location.search.length);
var args = qs.split("&");

for (var i=0; i < args.length; i++) {
var nameVal = args[i].split("=");
var temp = unescape(nameVal[1]).split('+');
nameVal[1] = temp.join(' ');
vals[nameVal[0]] = nameVal[1];
}
setLookupFromFieldName("Title", vals["ArticleID"]);
}

// setLookupFromFieldName: Set a form field value using its
// fieldname to find it in the page
// Arguments:
// fieldName: The name of the list column
// value: Set the fieldName to this value
//
function setLookupFromFieldName(fieldName, value) {
if (value == undefined) return;
var theInput = getTagFromIdentifierAndTitle("input","",fieldName);
if(theInput != null) {
theInput.value = value;
}
}

// getTagFromIdentifierAndTitle: Find a form field object using its tagName,
// identifier, and title to find it in the page
// Arguments:
// tagName: The type of input field (input, select, etc.)
// identifier: The identifier for the instance of the fieldName
// (ff1, ff2, etc.)
// title: The title of the list column
//
function getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);

for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" ||
tempString.indexOf(identifier) == tempString.length - len)) {
return tags[i];
}
}
return null;
}

</script>(Source: http://roadburn.audioreload.com/tag/moss/)

No comments:

Post a Comment