Using Query String Variables to Populate SharePoint Form Fields

If you have a parent/child relationship between two lists, you will undoubtedly want your users to be able to create child items without having to type in the common key or ID.  I’m not going to go into the full architecture of this here, but here’s an important part of the process.

Let’s say that you’ve built a nice custom page which lists your parent items, perhaps a list of projects, and you have a links next to each projects to ‘Add Status’.  This link points to the page where you provide the user with a form to add an item to the project status list (the child list).  This link probably will look something like this:

http://[servername]/Shared%20Documents/NewProjectStatus.aspx?ProjectID=[n]

Wouldn’t it be great to be able to grab that ProjectID from the Query String and populate the ProjectID column on the child (Project Status) list?  No problem; a little JavaScript will do it.

Open the NewProjectStatus.aspx page in SharePoint Designer, and add the following JavaScript (If you aren’t sure where it goes, try looking for where the script: var navBarHelpOverrideKey = “wssmain”; lives):

_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("ProjectID", vals["ProjectID"]);
}
// 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;
}

The form field named ‘ProjectID’ (in this case) will be set to the value passed in on the Query String.  See some of my previous posts showing the JavaScript needed to set other types of form fields like a People Picker.

NOTE (July 12): AutoSponge pointed out a few deficiencies in this post, which I thank him for (see below).  I also should have referenced this post as the original source for this approach.

Similar Posts

37 Comments

  1. Dude,
    You just made my day. Thanks again for all your hard work!

    I’m building a chat feature embedded into a project and this was exactly what I needed to link it up.

    Thanks again!
    Mark

    1. Mark:

      You are certainly welcome. These days, I do most of this type of work with jQuery (as it is easier to write), but there is an overhead with it. Your mileage may vary, but you should consider jQuery if it will bring you other benefits.

      M.

  2. Marc,

    I admit… I am trying to hack my way through this, but I am not very successful. Below is the code from designer that comes up. I have a project list that has tasks assigned to it from a task list. When I click add new item I want the project name to populate with the project name from the parent list. Where does the code go. HELP!

    '

    0

    ListForm

    &nbsp;

    &nbsp;

    Task *

    Predecessors

    Priority

    Status

    % Complete

    Assigned To

    Description

    Start Date

    Due Date

    Project Name

    IssueID

    var elm = document.getElementById("idAttachmentsTable");
    if (elm == null || elm.rows.length == 0)
    document.getElementById("idAttachmentsRow").style.display='none';

    1. Daine:

      Code doesn’t come through in WordPress comments very well; most of it gets stripped out.

      You might want to take a look at my SPServices library, which has a function to parse the Query String for you. This post is very old, and while still valid, is a bit kludgier. If you have further questions, you could post them in the SPServices Discussions.

      M.

  3. Hey marc,
    Not work for me.. :(
    I just wanna retrieve user input from people picker, i tried to show it in
    But it getting null

    1. Darius:

      Since you haven’t posted your script, I have no idea what’s going wrong. However, I’ve got quite a few posts that talk about working with the People Picker with script. One or more of them should help you do what you want.

      M.

  4. I am looking to display the related lookup column of the ID in a new form. I have been following a solution found http://geekswithblogs.net/SoYouKnow/archive/2010/12/16/creating-a-sharepoint-parentchild-list-relationshipndash-sharepoint-2010-edition.aspx which works well, however, when I create a new entry the only reference to the parent item is the ID. I would like to also display in the new form the parent title along with the parent ID. While I’ve tried hacking the code to add a new tablerow for the title, the code broke the page. Any suggestions? I’d like to have the ID and Title both be labels, but right now the ID is inside a text box.

    1. Alex:

      If you have a lookup column in a NewForm, is the goal to show something about the lookup value when a selection is made? If so, take a look at SPDisplayRelatedInfo in SPServices. It might be an easy way to do what you want.

      M.

      1. Yes, Marc, that’s exactly my goal. I am passing data from a parent list form to a child list form and displaying the itemID of the selected parent item in the child form. The issue is I also want to display the related title of that ID. Let me examine further your suggestion and get back to you once more testing has been completed. Thanks for your input. :)

  5. Hi Marc,

    Your solution is wonderful, However I am stuck at a point.

    I dont know where to put the script ?? i cannot find<> in my Newitem from.
    Is there any way i can put it in CEWP and make it work?

    I am using SPD 2007

    Thanks
    Nirav

    1. Nirav:

      Boy, this is an old post! I’d undoubtedly use jQuery these days. There is plenty of documentation on how to add script into SharePoint page on the Web. A CEWP woulds certainly work, but use the Content Link to post to the script in a file.

      M.

      1. Hi Marc,

        Many Many thaks for the reply, I have figured it out from your post that how to pass & use information from one to another page. It was an old post but still you reply to it so i appreciate a lot..

        Warm Regards,
        Nirav

  6. All these posts and so-called solutions for what should be possible out of the box further re-affirms the failing Microsoft products base. Sharepoint is many years old and is as worthless an application as any.

  7. Old thread, but I just put this into practice and discovered something that may be of use to others. I was sending a query string for a “Project” field along with a ContentTypeId querystring. When certain content types were selected, the “Project” value was failing to set. I finally realized that the “Project” field was optional in some content types but required in others in the same list, and the field’s “title” value, referenced by this script, was not the same for all content types. It was “Project” in the content types where it was optional; it was “Project Required Field” in content types where it was required.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.