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. The above script will not find the form field when there are fewer than 20 items or when viewed in FF. 

    Example:
    <TD valign="top" class="ms-formbody" width="400px">
    <!– FieldName="somecolumn"
    FieldInternalName="somecolumn"
    FieldType="SPFieldLookup"
    –>
    <span dir="none"><select name=In that scenario, the field is a Select, not Input.  See the original code here.

  2. Fair enough, AutoSponge.  I’m not sure I understand what you mean when you talk about fewer than 20 items or viewed in FF, though.
     
    In any case, I was trying to answer a specific question for someone, and I goofed by not providing the original link to that article you show below and explaining that this would only work in those cases where the column that you want to set is an ‘input’ column.  Sorry about the lack of attribution; I’ve added the original link as part of my post above.

  3. hi…

    thanks for the great solution… i need it in many of my applications, but i tried the script above and it didn’t work with me.. my lookup values are not more than 20 i actually created a two lists (parent and child) with on lookup column in “child” picking up the parent title

    i’m passing the “parent” “title” through a hyperlink to the newform.aspx that contains your script
    example lists/child/newform.aspx?title=hello

    but nothing happens and the lookup dropdown doesn’t pickup the value i passed through the link :S

    any clue or advice on how to make this work

    thanks

      1. hi

        i was referring to the exact example you have in this post “query string” i managed to make it working, the problem was with the cut and paste code from the browser as the double quote were slide quotes

        but now my other lookup which has values more than 20 is not working  any extra script I have to add here .. I read online that if you have a lookup with more than 20 values this script will not work, did you get around this problem by any chance

        thanks

        1. Tia:

          When you have 20+ options in a dropdown, SharePoint uses a hybrid input/select to make finding options easier. You’ll need to set the differently in your JavaScript by setting the input’s value attribute to your value.

          M.

          1. Thanks… it’s working fine with Lookup more than 20 values :) … my second question is how to make this script workable for more than one query string ? my parent list has two columns as the primery key

            i tried to add setLookupFromFieldName(“ProjectID”, vals[“ProjectID”]); twice with changing the function name and values but it didn’t work …

            any hint :)

            Thanks a lot

            1. You’ll need a line like this for each Query String/column:
              setLookupFromFieldName(“columnName1”, vals[“QScolumnName1”]);
              setLookupFromFieldName(“columnName2”, vals[“QScolumnName2”]);

              M.

              1. Do i need to change or add to the setLookupFromFieldName function because i have one lookup and one dropdown list so the identifier is different in both cases

  4. Hi Marc,

    Thanks for a wonderful blog. It was very useful.

    I am trying to create template for “NewItem” form in sharepoint.
    It will allow the user to use already submitted item to create a new item for the list.

    That is, the NewItem form will have all prefilled values for a particular request.
    And the user is able to edit that item and then submit it as a new request to the list.

    Please provide me insights regarding this.

    Thank You,
    Vaishnavi

    1. Vaishnavi:

      You won’t be able to do this without writing some code of one sort or another. How are you expecting the user to choose the item they wish to “clone”? What I might try is to call the Lists Web Service, GetListItems operation to get the details for the item and populate the NewForm.aspx with jQuery. Take a look at my jQuery Library for SharePoint Web Services.

      M.

  5. Hi Marc,

    Thanks for your reply.
    I have created a column which will provide a link to use for the user.
    When the user clicks on the link it should open a template for that particular item in list with all values pre-filled and allows user to edit the request.
    After the Edit is done, user will be able to submit the request as a new item.
    Meanwhile I will try your jQuery for SP web services.

    Please let me know.

    Thanks.

  6. Hi Marc,
    I want to populate the field “FileID” in a DataFormWebPart with the ID value in the query string. I am not sure where to post this code in the DataFormWebPart however this would solve so many problems for me.

    I am pasting the code for my webpart, can you show me where to insert your code.
    PS. I am a network guy so I am pretty naive when it comes to coding. Thanks!

    @Title,Title;@FileID,FileID;@Count_x0028_s_x0029_,Count(s);@Charge,Charge;@Status,Status;@ID,ID;@ContentType,Content Type;@Modified,Modified;@Created,Created;@Author,Created By;@Editor,Modified By;@_UIVersionString,Version;@Attachments,Attachments;@File_x0020_Type,File Type;@FileLeafRef,Name (for use in forms);@FileDirRef,Path;@FSObjType,Item Type;@_HasCopyDestinations,Has Copy Destinations;@_CopySource,Copy Source;@ContentTypeId,Content Type ID;@_ModerationStatus,Approval Status;@_UIVersion,UI Version;@Created_x0020_Date,Created;@FileRef,URL Path;

    '
    {22EF0A4D-2898-41C6-A2CB-F85F8EAD692B}

    1

    Table

    Count(s)
    Charge
    StatusFileID

    1

    1

    ms-alternating

    ID

    view

    ID

    edit

    save

    cancel

    save

    cancel

    edit
    delete

    _new

    ID

    insert

    insert

    There are no charges listed on this file.

    1. Gerald:

      You’re posting this everywhere! You’ll want to put the script in the page so that it runs on the client side. You’ll have the DVWP just rendering things on the server side, and the script will pick up the Query String values on the client side.

      M.

  7. Any ideas for sharepoint 2010 related lists?
    When we add a new child list item,we get a new item popup…but the lookup field of the parent selected is not defaulted…

    1. It sounds like you just don’t have the right script to set a dropdown vs. an input field. The modal window is still the NewForm.aspx.

      M.

  8. hi,

    Thanks for the reply..I am using the” Parent Child Webparts sharepoint 2010″ connected via “insert related list” which has an inbuilt “Add new item” hyperlink for both parent and child list webparts.

    In sharepoint designer, the webpart has its “Add new item” link.
    Can you please tell me how can I find the link for “Add new item ” and add the querystring.
    or shoul I create a new link and not use the webpart?

    Thanks for the help.

    1. I don’t think that you can get at the link with anything other than script unless you write your own Custome Web Part. With script, you can add the Query String parameters to the href.

      M.

Leave a Reply to Marc Cancel 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.