Friday, May 15, 2009

Redirect User After Submission of New or EDIT List Form in SharePoint

I recently had the requirement to redirected uses back to a MOSS sites main page after creating a new list item or editing an existing one.  The default behavior in MOSS is to you are redirect back to the list.  Thankfully MOSS embeds the URL that will be used after clicking the OK button in the URL of the new or edit form.  This URL parameter is called Source.  Knowing this it was possible to write a JavaScript function that could be added to the ASPX page to either update or insert this value associated with the parameter.

Here is the function originally written by another RDA Consultant Viktor Dolezel and modified by myself to work in additional cases. 

<script type="text/javascript">

_spBodyOnLoadFunctionNames.push("redirectAfterSave");

function redirectAfterSave() {
var newUrl = "%2Fsite%2Fdefault%2Easpx";

//parse the form action query string into a map
var qs = document.forms[0].action.substring(1, document.forms[0].action.length);
var args = qs.split("&");
var vals = new Object();
for (var i=0; i < args.length; i++) {
var nameVal = args[i].split("=");
vals[nameVal[0].toLowerCase()] = nameVal[1].toLowerCase();
}

//if source doesn't exists in the original form action string, add it,
//otherwise replace it
if (!vals["source"]) {

if(args.length > 1) {
document.forms[0].action+= "&";
} else {
document.forms[0].action+= "?";
}
document.forms[0].action += "Source=" + newUrl;

} else {
document.forms[0].action = document.forms[0].action.toLowerCase().replace(
"source=" + vals["source"],
"Source=" + newUrl );
}
}
</script>




I manually replaced the characters / and . in my URL with %2F and %2E respectively.  Also I did not have to provide the full URL just the name of the site and MOSS filled in the remainder of the URL



On word of caution, it is against best practices to directly edit the ASPX pages for out of the box list.  So use this post at your own risk in those cases.  In my case we had created custom list definitions so this did not apply to us.

No comments: