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.

<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>

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

38 Comments 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

  10. I have a SP page which has list of products (ProdList) with 100+ products on that list. This list has a – ProdID, ProdName, ProdUrl.
    ProdUrl is autogenerated using SP workflow and has the following pattern :
    https://abc.sharepoint.com/sites/Mysitename/TestWikiPage/TestProductLandingPage.aspx?paramprodid=pd001

    This url takes the user to the landing page for that product. I have added query string based filtering {by adding Query string (url) filter} on this landing page, which filters more information about this particular product from various lists available. All those lists have a lookup field called ProdNum (lookup to ProdID in ProdList).

    Now, I want my users to have discussions on this product. Hence, I added a ‘Discussion Board App’. Apart from the regular fields in the discussion board, I have created one more lookup column ProdNum. I can filter my discussions based on this field on the landing page.

    Now, when a user is on a landing page of one product, and he wants to add a discussion on that product, he clicks ‘+ new discussions’. This takes him to a NewForm.aspx. On this page, I want the ProdNum lookup field to be autopopulated and non-editable (since there are 100+ items), based on the product from which user is coming. How can that be achieved?

    The NewForm.aspx url is something like this : https://abc.sharepoint.com/sites/Mysitename/Lists/testDiscussionBoard/NewForm.aspx?Source=https%3A%2F%2Fabc%2Esharepoint%2Ecom%2Fsites%2FMysitename%2Ftestwikipage%2FTestProductLandingPage%2Easpx%3Fparamprodid%3Dpd001

    I am working on SharePoint Online, can used SPD if required and also have admin privileges.

  11. You would need to use a function in the NewForm to pull down the value from the “paramprodid” key in the url and write it’s value to the field. If you are using DFFS you can add this code to your Custom JS in the config form NewFrom:

    var paramprodid = GetUrlKeyValue("paramprodid");
    setFieldValue("InternalNameOfYourTargetField",paramprodid);

    Alexander

    1. I am writing this code in the NewForm.aspx, but it is not working as expected.

      var query = window.location;
      var regex = /paramprodid%3D([^&=]+)/i;
      var match = regex.exec( query );
      if( match != null ) {
      document.getElementById(“mytestfield_c0197ad3-2e3f-4778-8afb-f864bac755a7_$TextField”).value= match[1];
      }

      I am sure that the regex is extracting the necessary id from the url. I tested that using ‘document.title= match[1];’ and it is setting the title correctly. But, I don’t know why it is not writing the same value to either a text field or a lookup field.
      Any suggestions?

      1. Hi,
        This is an old post. Use this instead:

        // assuming the URL key is "paramprodid"
        setTimeout(function(){
            var theValue = GetUrlKeyValue("paramprodid");
            document.getElementById("mytestfield_c0197ad3-2e3f-4778-8afb-f864bac755a7_$TextField").value = theValue;
        },250);

        The timeout is set to let the form finish loading. Please note that the ID you use for the field will change if you change the order of the fields in your list.

        I recommend you test DFFS: https://spjsblog.com/dffs/

        Alexander

  12. Hey there, this has served me well for YEARS. I probably have a post in here or near where I needed a little help, and my current form is using this setTimeout to add a small delay before it checks for the clientval parameter and puts whatever it found into the Title field of my form:

    setTimeout(function(){
    var clientValue = GetUrlKeyValue(“ClientVal”);
    if(clientValue!==””) {
    document.getElementById(“spjs_ac_Title”).value = clientValue;
    spjs.ac.hideHelp(“Title”);
    jQuery(“#spjs_ac_Title”).keyup();
    }
    },2500);

    I now have a need to add a few more parameters and I will likely just add a var and if-block to that same setTimeout function to accomplish it.

    But –
    I seem to remember, perhaps a lifetime ago, that there was a more generalized way to do this that allowed nearly any field on the form to be prefilled by URL query string. I believe by just using whatever “title” tag the html input element had. Is that no longer possible? I assume since this custom javascript is the suggestion here it’s likely the only way, perhaps the SPFF was for older generations of sharePoint?

  13. Hi,
    There is no built in functionality that can do this for you, but I think you might be right that it was supported in WSS 3.0.

    You can use something like this (using the DFFS functionality) to set the value:

    var clientValue = GetUrlKeyValue(“ClientVal”);
    setFieldValue("clientValue_field_internal_name", clientValue); 
    

    Replace “clientValue_field_internal_name” with the internal name of the field you want to set.

    Alexander

Leave a Reply

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