locked
Open list form and populate fields with values RRS feed

  • Question

  • Using SharePoint Online, I have two lists, a timeslots list and an appointments list. The user is to navigate to the timeslots list and then select a list item. Upon opening the display form for the timeslots list, there is a CEWP with a content link to a script, I need the script to ...

    1. Capture information from the list item that was selected (2 fields - timeslot & location)
    2. Redirect the user to the new item form of the appointments list (this works)
    3. Populate two fields on this form with the info gathered in step 1 (the names of the fields are the same as the timeslots list - timeslot/location - timeslot is a lookup field to its namesake, location is a free text field)

    My script is currently as follows:

    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script> 
    <script type="text/javascript" src="https ://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
      
    (function () {  
      
      console.log("Hello World");
         
       window.location = "https ://tenant/sitecollection/site/Lists/Appts/NewForm.aspx"
       console.log("Hello World 2");

      
    })();  
    </script>

    (Spaces in URLs above are deliberate as I can't add a link on this forum).

    I feel I have exhausted my googling abilities and have attempted to utilise many scripts containing code around the command

    SP.ClientContext.get_current();

    I am a newbie to client side rendering. Any help would be much appreciated, thanks.

    PS. the console.log statements are successful.

    Tuesday, November 14, 2017 5:00 PM

Answers

  • This was a long conversation but to provide an answer:

    The 3 steps in my script needed to be separated into 2 locations, with steps 1 & 2 on the initial form, then once this script redirects the user, the page they are redirected to needs its own script containing step 3.

    The code that successfully populated the fields was:

    $("input[title='Location']").val("test value");

    Thank you to Lee_li for the help - you got me to the answer.

    • Marked as answer by PetyrBaelish Wednesday, January 3, 2018 10:59 AM
    Wednesday, January 3, 2018 10:59 AM

All replies

  • Hi,

    Here is sample script to get selected item id(s) and redirect to another list from.

    You could get selected item id in appointments list form and load the timeslots list item by jsom so you could do pre-init.

    <input id="Button1" onclick="GetSelectedSPItem()" type="button" value="button" />
        <script type="text/javascript" src="https ://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script type="text/javascript">
    
            function GetSelectedSPItem() {
                var ctx = SP.ClientContext.get_current();
    
                var items = SP.ListOperation.Selection.getSelectedItems(ctx);
    
                var mySeletedItems = '';
    
                var targetUrl = _spPageContextInfo.webAbsoluteUrl + "/Lists/Appointments/NewForm.aspx?Source=" + _spPageContextInfo.listUrl + "";
                var i;
                if (items.length > 0) {
                    for (i = 0; i < items.length; i++) {
                        if (i == 0)
                            mySeletedItems += items[i].id;
                        else
                            mySeletedItems += '|' + items[i].id;
                    }
                    targetUrl += '&timeslotId=' + mySeletedItems;
    
                    window.location = targetUrl;
                }
                else {
                    alert('no selected item');
                }
            }
        </script>

    Get url parameter:

    function getQueryStringParameter(urlParameterKey,fullURL) {
                var params = fullURL.split('?')[1].split('&');
                var strParams = '';
                for (var i = 0; i < params.length; i = i + 1) {
                    var singleParam = params[i].split('=');
                    if (singleParam[0] == urlParameterKey)
                        return decodeURIComponent(singleParam[1]);
                }
            }

    Get list item by ID.

    http://melick-rajee.blogspot.sg/2013/10/get-list-item-by-id-with-specified.html

     

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Proposed as answer by Dennis Guo Thursday, November 16, 2017 8:29 AM
    Wednesday, November 15, 2017 2:46 AM
  • Thanks for your help, I have developed my script to the point where it successfully retreives the information from the list item that was selected (added to variables), and redirects the user to the newform.aspx of the other list (Appointments)

    What I'm now struggling to do is pre-populate two fields on newform.aspx with the variables.

    My script so far is as follows:

    		<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
      		<script type="text/javascript" src="/_layouts/15/sp.js"></script> 
    		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    		<script type="text/javascript">
    		
    (function () {		
    		
    		console.log("Hello World");
    
    		
    // Step 1 - retreive information from selected timeslot		
    		
    		function getQS(key) {
    			var regex=new RegExp('[\\?&amp;]'+key+'=([^&amp;#]*)');
    			var qs=regex.exec(window.location.href);
    			return qs[1];
    		}
    
    		var itemID = getQS('ID');
    		
    		console.log("ID: "+itemID);
    				
    		var ctx = new SP.ClientContext.get_current();
    		var web = ctx.get_web();
    
    		//Geting reference to the list
    		var olist = web.get_lists().getByTitle('Timeslots');
    		var oitem = olist.getItemById(itemID); //need to replace the static ID
    		//get appropriate fields
    		ctx.load(oitem, "Location", "Id", "Title");
    		ctx.executeQueryAsync(function () {
     
    			var Location = (oitem.get_item("Location"));
    			var Title = (oitem.get_item("Title"));
    	
    			console.log("Location: "+Location);
    			console.log("Title: "+Title);
     
    		}, function (a, b) {
    			alert(b.get_message());
    		});
    
    // Step 2 - Redirect user		
    
    			window.location = "https://tenant/sitecol/site/Lists/Appts/NewForm.aspx?"
    			console.log("Hello World 2");
    
    // Step 3 - Populate form fields with variables	
    
    })();		
    		</script>	
    I've tried various solutions proposed on the web but haven't got any working.

    Friday, December 1, 2017 1:18 PM
  • Hi,

    You could pre-inint control value by jQuery usually.

    For example:

    $( "#single" ).val( "Single2" );

    http://api.jquery.com/val/

    For people picker field, you may check below thread.

    https://sharepoint.stackexchange.com/questions/129947/how-to-set-the-people-picker-field-using-jquery-in-sharepoint-2013-to-current-us

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Monday, December 4, 2017 8:53 AM
  • I've tried the following options, directly after the //Step 3 line in my code above but none of them have worked, with no error messages. The Location field renders but the text box is blank (it's a single line of text field).

    Attempt 1:

    $( "#Location" ).val( "Single2" );

    Attempt 2:

    $("input[value='Location']").val( Location );

    I also tried the code below, adapted from this page, but that didn't work either, with an error message:

    	var newctx = {};
       			newctx.Templates = {};
       			newctx.Templates.Fields = {
           			'Location': { 'NewForm': renderLocation }
       			}
    
       			SPClientTemplates.TemplateManager.RegisterTemplateOverrides(newctx);
    
    		function renderLocation(newctx) {
    			newctx.CurrentFieldValue = "Single2";
    			return SPFieldText_Edit(newctx);
    		}

    On attempting to run the above I got an error that "SPClientTemplates is undefined" - but I couldn't figure out how to reference this library in SarePoint Online (plenty of options were provided for SP2013 on-prem) so I couldn't get past this error.

    From the Developer Tools, here's the information on my Location field. It's name and internal name is "Location" so I believe I am referencing the correct form field - although it seems to me that's where the problem is:

    		<td valign="top" width="350px" class="ms-formbody">
    		<!-- FieldName="Location"
    			 FieldInternalName="Location"
    			 FieldType="SPFieldText"
    		  -->
    			<span id='WPQ1b6450101-bde6-4c21-8659-37dc99988920Location' data-sp-control='SPFieldText' data-sp-options='{&quot;mode&quot;:3,&quot;source&quot;:&quot;Location&quot;}'></span>	
    		</td>

    Once I've got this field working, the second field is a lookup field, for which I need to do the same.

    Thanks for your help.

    Thursday, December 7, 2017 12:59 PM
  • Hi,

    I would suggest you go through below guideline as I think none of your selector is correct( the selector is based on rendered DOM, not designing html).

    https://www.w3schools.com/jquery/jquery_ref_selectors.asp

    You could use developer tool(IE->F12) to check the html control attributes.

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Monday, December 11, 2017 9:03 AM
  • Hi Lee, you're right, I was using the Debugger and going through the HTML. When going through the DOM explorer I found the relevant text box:

    DOM Explorer

    Unfortunately, using the title (already tried that) or the id didn't work:

    $( "#Location_51111111-1111-1111-1111-11114f643fc9_$TextField" ).val( "Single2" );

    I get the following error message:

    Syntax error, unrecognized expression: #Location_51111111-1111-1111-1111-11114f643fc9_$TextField

    If I use the title ... $( "#Location" ).val( "Single2" ); ... I don't get any error message but the text box does not become populated.

    I also tried putting the above line plus a console.log statement in a document.ready then a window.load function but in both cases the console.log never happened.

    Thursday, December 14, 2017 4:35 PM
  • Hi,

    Try this:

    $( "input[id^='Location']" ).val( "Single2" );
    https://api.jquery.com/attribute-starts-with-selector/

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Friday, December 15, 2017 1:38 AM
  • I crated an additional form (newform2.aspx) on the same list and managed to use the following code to set the value of the Location field:

    $("input[title='Location']").val("test value");
    console.log("This worked");

    Unfortunately, when I copied this line into step 3 of the above script, the Location field isn't set.

    I tried putting the above line (and a console.log) into a window.load function, but that didn't work - and the console.log statement didn't run (without the window.load function the console.log statement would run).

    //$(window).load(function() {
    	$("input[title='Location']").val("your get value 2");
    	console.log("This worked");
    //});
    So I now believe I have the correct field, and that the line of code above will work, it's just something about the redirect that is stopping it from working correctly.
    Monday, December 18, 2017 3:21 PM
  • Hi,

    Make sure the jQuery library is loaded(IE developer tool F12).

    And, try to debug your script by developer tool, for example:

    Here is my test script for your reference.

        <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script type="text/javascript">
            $(window).load(function() {
                $("input[title='Location']").val("your get value 2");
                alert("window load");
            });
        </script>

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Tuesday, December 19, 2017 1:41 AM
  • The problem I was experiencing was that I was trying to redirect the user in step 2, and the code I was adding in step 3 needs to be on a different script by adding a CEWP to the form I am redirecting the user to. I am now separating step 3 into its own script and passing the variables via query string.

    I still haven't got it all working, but as the problem has changed I'll post different questions on each scpecific problem

    Wednesday, January 3, 2018 10:56 AM
  • This was a long conversation but to provide an answer:

    The 3 steps in my script needed to be separated into 2 locations, with steps 1 & 2 on the initial form, then once this script redirects the user, the page they are redirected to needs its own script containing step 3.

    The code that successfully populated the fields was:

    $("input[title='Location']").val("test value");

    Thank you to Lee_li for the help - you got me to the answer.

    • Marked as answer by PetyrBaelish Wednesday, January 3, 2018 10:59 AM
    Wednesday, January 3, 2018 10:59 AM