Prefill fields in NewForm from url query string

This one if based on a request from Charlie Epes:

Hi Alexander:
I need my users to click an “Add New” icon next to an item in a List View and have a NewForm pop-up with the same [Company Name] field already populated. Possible?

This request hat two sides, one for adding the clickable link in the list view, and one to populate the field in the NewForm.

Larry pointed to the Text to HTML script from Christophe for the first part.

You basically create a calculated field like this:
IMG

This formula gets the value from the “Title” field and wraps it as a link. Then you use the Text to HTML script to convert it into HTML.

The second part is about getting the value from the URL query string and into the Title field in the NewForm.

Place this code in a CEWP (read here how to do that) below the NewForm.aspx.

[javascript]
<script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Get all querystring parameters
var queryStr= getQueryParameters();

// Is the parameter "ClientVal" defined?
if(queryStr[‘ClientVal’]!=undefined){
var properVal = decodeURI(queryStr[‘ClientVal’]);
$(fields[‘Title’]).find(‘input’).val(properVal);
}

// Function to separate each url search string parameters
function getQueryParameters(){
qObj = {};
var urlSearch = window.location.search;
if(urlSearch.length>0){
var qpart = urlSearch.substring(1).split(‘&’);
$.each(qpart,function(i,item){
var splitAgain = item.split(‘=’);
qObj[splitAgain[0]] = splitAgain[1];
});
}
return qObj;
}

function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf(‘FieldInternalName="’)<0) return;
var start = $(this).html().indexOf(‘FieldInternalName="’)+19;
var stopp = $(this).html().indexOf(‘FieldType="’)-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>
[/javascript]

This code looks at the URL query string and finds the “ClientVal”. If it is defined, it prefills the “Title” field with the value from the query string.

Customized form?
How to use these scripts in a customized form

Ask if something is unclear!

Regards
Alexander

32 thoughts on “Prefill fields in NewForm from url query string”

  1. In my Service Request list I want to create a link to the NewForm.aspx form of my Service Task list and I want to pre populate the Parent SR column/field with the ID from the Service Request list, also the Service field, and Descriptio.

    How would I do that?
    Thanks.

    1. It is the exact same approach, only duplicate the “action” in line 8-11 for all the fields. You could also dynamically create this “Link” if a calculated column does not work (the field types cannot be used in a calculate column).

      Look at this article regarding getting an setting field values Get or Set value for SharePoint field in NewForm, EditForm and DispForm (Get only in DispForm)

      Also look at the vLookup type rollup for SharePoint and see the parameter “newItemLink:true”.

      Alexander

  2. This is a wonderful tip to get a value from Query String and insert into Title field. It worked the first time and solved a puzzle for me due next week as part of my project.

    Please though explain for a not-to-good JavaScript guy, using line number reference, the logic that finds the “Title” field and makes the assignment.

    The Post from PGD is also a target for me. I am not able to decipher where you’re setting up the field to look for, and where the value assignment is being made.

    1. Hi,
      In line 10 the Title is set. The object “fields” is created in line 3.

      To have a link with the item ID you must either use javascript in the list view to find the ID or use a workflow thet writest the ID to a text field. The reason for this is the fact that you cannot use the ID column in a calculated column.

      When using workflow and a calculated column, you build the link using the text to HTML solution from Christophe

      Alexander

  3. I’ve been looking for this for a long time. Thanks!

    Now that 2010 is here, can this be used if you have SharePoint gernerate customized InfoPath forms? The CEWP seems to be removed when you save the InfoPath customized form. The combination of the two would really enhance the user experiance.

    Thanks Again!
    Scott

    1. Hi,
      If you construct the link in a calculated column in list A (pulling the values from the columns in the list item into the URL) – and click it in DispForm of list A – then this link takes you to list B with the values in the URL – there are no “query” going back to the item in list A to pull the values, it’s the values in the URL that are put into the fields in list B.

      Here is an example:
      Put this calculated column in list A:

       ="<a href='/test/English/Lists/SetFieldValFromURL/NewForm.aspx?firstParameter="&Title&"&secondParameter="&AnotherField&"'>New item</a>"
      

      Then insert this code in a CEWP of your DispForm (list A):

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
       <script type="text/javascript">
      fields = init_fields_v2();
      
      // Converts the text in the field "MyLink" to HTML
      var myUrlField = $(fields['MyLink']).find('td.ms-formbody');
       myUrlField.html(myUrlField.text());
      
      function init_fields_v2(){
       var res = {};
       $("td.ms-formbody").each(function(){
       var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/); 
       if(myMatch!=null){
       // Display name
       var disp = myMatch[1];
       // FieldInternalName
       var fin = myMatch[2];
       // FieldType
       var type = myMatch[3];
       if(type=='SPFieldNote'){
       if($(this).find('script').length>0){
       type=type+"_HTML";
       }
       }
       if(type=='SPFieldLookup'){
       if($(this).find('input').length>0){
       type=type+"_Input";
       }
       }
       // Build object
       res[fin] = this.parentNode;
       $(res[fin]).attr('FieldDispName',disp);
       $(res[fin]).attr('FieldType',type);
       } 
       });
       return res;
      }
      </script>
      

      Change the name “MyLink” to match your FieldInternalName.

      A click on the link in list A’s DispForm will now take you to the NewForm of list B.

      Use this code for your NewForm in list B to pick up and insert the variables:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
       <script type="text/javascript">
      fields = init_fields_v2();
      
      var myFirstUrlKey = GetUrlKeyValue('firstParameter');
      $(fields['Title']).find('input').val(myFirstUrlKey);
      
      var mySecondUrlKey = GetUrlKeyValue('secondParameter');
      $(fields['AnotherField']).find('input').val(mySecondUrlKey);
      
      function init_fields_v2(){
       var res = {};
       $("td.ms-formbody").each(function(){
       var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/); 
       if(myMatch!=null){
       // Display name
       var disp = myMatch[1];
       // FieldInternalName
       var fin = myMatch[2];
       // FieldType
       var type = myMatch[3];
       if(type=='SPFieldNote'){
       if($(this).find('script').length>0){
       type=type+"_HTML";
       }
       }
       if(type=='SPFieldLookup'){
       if($(this).find('input').length>0){
       type=type+"_Input";
       }
       }
       // Build object
       res[fin] = this.parentNode;
       $(res[fin]).attr('FieldDispName',disp);
       $(res[fin]).attr('FieldType',type);
       } 
       });
       return res;
      }
      </script>
      

      Alexander

  4. I’m wanting to pull a parameter from a mySite where a discussion is added on each person’s page…I want the name from the URL to be input into a textfield/people picker for sharepoint 2010. This seems to be similar to what I want, but it’s not quite there. The URL is something like https://test.org/my/employee/Person.aspx?accountname=companyFirstName.LastName where I need to capture the Firstname.Lastname section and put it on a “To” field in the Newform…done anything like that/know how that might be done?

  5. Hi Alex,

    Does this work to pre-fill drop-down fields in NewForm?

    Also, how do you pass more than one variable to NewForm? Tried using the ‘&’ sign but it causes an error in the calculated column.

    1. Hi,
      The other way around: the query string starts with ?, the parameters are separated by &.

      /site/list/page.aspx?ID=22&myParameter1=something&myParameter2=SomtehingElse

      Alexander

  6. Trying to get this to autopopulate a “lookup” field with 100+ project name values in my child list. Not populating what am I missing? Do I need to reference the display name or the internal field name?

    1. It is the internal name you must refer. Try to set a text field to ensure the script functions. If this works, is it the ID value or the Text value of the lookup column you try to set, and is it a single or multi choice field?

      Alexander

  7. Hi,
    This code would really solve an issue I have but I can’t seem to get it working. I think it’s because I have SP2010? I have checked your link to updated init codes but it doesn’t seem to be the whole script and I’m not sure how to join it in to the one above. Is there any chance you could post an entire script for SP2010? Many thanks in advance!

    1. Hi,
      Sorry for the delay. This post is old and this approach will not work. Go here and get spjs-utility.js. Find jQuery here.Then add code like this to your NewForm (put it in a HTML Form web part BELOW the form web part):

      <scipt type="text/javascript" src="/yourpathto/jquery-1.11.2.min.js"></script><scipt type="text/javascript" src="/yourpathto/spjs-utility.js"></script>
      <scipt type="text/javascript">
      var fields = init_fields_v2();
      var yourQueryStringVal = GetUrlKeyValue("name_of_key");
      setFieldValue("InternalNameOfField",yourQueryStringVal);
      </script>

      Hope this helps,
      Alexander

      1. Hi Alex,

        Thanks for the speedy response, I have looked at so many different scripts to try to achieve an auto populate on a look up column in sp2010 and this is the only one where people seem to get it working. I however still cannot 🙁

        I have pasted the following into a form webpart (also tried a cewp referencing text file). I have placed it under the new item form (un customised) and still it doesn’t work even on a simple ‘Title’ column which I have tried first below to at least getting it working in principle!

        URL: http://team/sites/station/Lists/EquipmentDisposition/NewForm.aspx?myVal=Hello

        var fields = init_fields_v2();
        var yourQueryStringVal = GetUrlKeyValue(“name_of_key”);
        setFieldValue(“Title”,myVal);

        Is there some additional code I should be adding?

        Thanks Julie

      2. Hi,
        You have mixed it up a bit. The variable “yourQueryStringVal” is supposed to hold the value for the key “name_of_key”. This again means you must use “yourQueryStringVal” in the function “setFieldValue”. I have made a new code example using your example “keyName”:

        <script type="text/javascript" src="/SPJS/jquery-1.11.2.min.js"></script>
        <script type="text/javascript" src="/SPJS/SPJS-Utility/spjs-utility.js"></script>
        <script type="text/javascript">
        setTimeout(function(){
        	var myUrlKeyValue = GetUrlKeyValue("myVal");
        	setFieldValue("Title",myUrlKeyValue);
        },100);
        </script>

        Alexander

  8. Voila! The above works like a dream and thankfully doesn’t conflict with the Jquery for cascading columns that’s also on the form.

    This has seriously resolved a problem I had in trying to get round the issue of complex dropdowns, I now have a really fluid feeling form 🙂

    THANK YOU! Julie

      1. I hadn’t heard of it but at a quick glance it certainly seems worth looking into, amazing price too! Cheers, Julie

  9. hello Thomas
    I had this code working and now i receive this error
    uncaught referenceError: $ is not defined at
    spjs-utility.js:24

    here is my code:

    /*var fields = init_fields_v2();*/
    setTimeout(function(){
    var myUrlKeyValue = GetUrlKeyValue(“JobID”);
    setFieldValue(“Title”,myUrlKeyValue);

    },100);

    thanks

    1. This message mean you are missing jQuery. Either download it locally and refer it from your local path, or add this script to your CEWP:

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

      Alexander

Leave a Reply