locked
Save and update list item from custom DispForm.aspx RRS feed

  • Question

  • For a custom list on SharePoint Online, I have created a custom DisplayForm. I have added an additional button by modifying the .aspx page in SharePoint Designer - here is the additional button:

    <td class="ms-toolbar" nowrap="nowrap">
      <input style="margin:0" id="customSave" type="button" value="Confirm" name="btnSave" onclick="if (!ExecuteThisFunctionBeforeSavingAndRedirecting()) return false; {ddwrt:GenFireServerEvent('__commit;__redirect={https://tenant.sharepoint.com/teams/site/subsite/Lists/ListName/AllItems.aspx}')}" />  
    </td>

    The custom DisplayForm contains an CEWP with a link to a JavaScript file, which contains the following code:

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" id="ShowHideConfirmButton">
    
    function DoIt() {
    		console.log("DoIt was called");
    	// will hide button based on value of a field
    
    }
    
    _spBodyOnLoadFunctionNames.push("DoIt");
    
    function ExecuteThisFunctionBeforeSavingAndRedirecting() { 
    
    	console.log("Confirm has been clicked");
    	return true;
    		
    }
    
    </script>

    What I would like to do, is for the DoIt function to hide my new button based on the value of a dropdown.

    The problem I have at present however, is upon clicking Confirm, a) the list item doesn't save and b) I don't know how I can change the value of a field (choice) of the list item. The intention was to do this in the ExecuteThisFunctionBeforeSAvingAndRedirecting function.

    I had done something similar on a custom EditForm and I was hoping to follow the same route on my custom DispForm page; but I don't have the form fields to retrieve from the DOM that can be easily manipulated.

    Please let me know if this is possible, and preferably with JavaScript. At the end of the day this is to save the user from having to click "Edit Item", for which I'm willing to do a bit of JavaScript, but nothing too heavy.

    Friday, January 26, 2018 12:59 PM

Answers

  • Hi,

    Here is my tested script which works in my local for your reference.

     <input id="btn_myUpdate" onclick="myUpdate()" type="button" value="myUpdate" />
        <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script type="text/javascript">
            function myUpdate() {
                $.ajax({
                    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Staff recruitment')/items(1)",
                    type: "POST",
                    data: JSON.stringify({
                        '__metadata': { 'type': 'SP.Data.Staff_x0020_recruitmentListItem' },
                        'Title': 'update'
                    }),
                    headers: {
                        "Accept": "application/json;odata=verbose",
                        "content-type": "application/json; odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                        "X-HTTP-Method": "MERGE",
                        "If-Match": "*"
                    },
                    success: function (data) {
                        alert("Item updated successfully!");
                    },
                    error: function (err) {
                        alert("Error while updating item: " + JSON.stringify(err));
                    }
    
                });
            }
        </script>

    Best Regards,

    Lee


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


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    • Marked as answer by PetyrBaelish Friday, February 9, 2018 11:53 AM
    Thursday, February 8, 2018 1:41 AM

All replies

  • Hi,

    In display form,you could call REST api to update list item, ddwrt:GenFireServerEvent used for New/Edit forms.

    Sample code:

    var industryVal = $("#Industry").val();
            $.ajax
            ({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('companyInfo')/items(7)", // list item ID  
                type: "POST",
                data: JSON.stringify
                ({
                    __metadata:
                    {
                        type: "SP.Data.TestListItem"
                    },
                    Industry: industryVal
                }),
                headers:
                {
                    "Accept": "application/json;odata=verbose",
                    "Content-Type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "IF-MATCH": "*",
                    "X-HTTP-Method": "MERGE"
                },
                success: function (data, status, xhr) {
                    retriveListItem();
                },
                error: function (xhr, status, error) {
                    $("#ResultDiv").empty().text(data.responseJSON.error);
                }
            });

    You could check below links for samples.

    http://www.c-sharpcorner.com/article/crud-operation-on-list-items-using-rest-api-services-in-shar/

    http://pointofint.blogspot.sg/2015/08/how-to-set-any-spfield-value-with-rest.html

    For URL redirecting, you could call

    window.location.replace("your url”);

    Best Regards,

    Lee


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


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Monday, January 29, 2018 2:22 AM
  • Thanks for your help I have the above code working, i'm now trying to use REST to read the value of the current list item and return the value of a column "Workflow status", but I'm struggling to use it in a way that I can assign the result of this to a variable:

    	var urlToAppend = "/_api/web/lists/GetByTitle('Staff recruitment')/items("+itemID+")?$select=Workflow_x0020_status"              
    	
    	// function to retreive the Workflow Status of the current list item
    	function getItems(urlToAppend) {
    		$.ajax({
    			url: _spPageContextInfo.webAbsoluteUrl + urlToAppend,
    			type: "GET",
    			headers: {
    				"accept": "application/json;odata=verbose",
    			},
    			success: function (data) {
    				var result = data.d.results.Workflow_x0020_status;
    			},
    			error: function (error) {
                alert(JSON.stringify(error));
    			}
    	});
    	
    	// assign result of function to variable
    	var itemWorkflowStatus =  getItems(urlToAppend)
    }
    
    // print variable - shows wrong result - it isn't updated by the function above
    console.log("WFStatus: " +itemWorkflowStatus)
    	
    	
    // put IF statement here, based on the value of itemWorkflowStatus
    	SetHidden();

    I've confirmed that itemID successfully contains the correct ID of the list item.

    Tuesday, January 30, 2018 2:27 PM
  • Further to my above post, here's the XML that the REST endpoint is querying:

      <?xml version="1.0" encoding="utf-8" ?> 
    
    
    - <entry xml:base="https://tenant/sitecol/site/_api/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml" m:etag=""6"">
    
    
    
      <id>0d2a45b3-db0b-4354-ad67-5338d1192251</id> 
    
    
      <category  term="SP.Data.Staff_x0020_recruitmentListItem" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /> 
    
    
      <link  rel="edit" href="Web/Lists(guid'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')/Items(265)" /> 
    
    
      <title  /> 
    
    
      <updated>2018-01-30T14:53:19Z</updated> 
    
    
    - <author>
    
    
    
      <name  /> 
    
      </author>
    
    
    - <content type="application/xml">
    
    
    
    - <m:properties>
    
    
    
      <d:Workflow_x0020_status>Status B</d:Workflow_x0020_status> 
    
      </m:properties>
    
      </content>
    
      </entry>

    Tuesday, January 30, 2018 2:58 PM
  • Hi,

    Try to update your script as below:

    data.d.results.Workflow_x0020_status;

    To

    data.d.Workflow_x0020_status;

    You could use developer tool(F12) to debug JavaScript if you can’t confirm the value actually.


    Best Regards,

    Lee


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


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Wednesday, January 31, 2018 2:09 AM
  • Thanks again, I have updated the script, and made some changes because of the asycnhronous behaviour of the script. But now that my Ajax 'read' call is working, the 'merge' call has stopped working.

    Here's my whole script:

    			dataType: "json",
    			headers: {
    				"accept": "application/json;odata=verbose",
    				"cache-control": "no-cache",
    			},
    			success: function (data) {
    				
    				//return result;
    				callback(data.d.Workflow_x0020_status);
    			},
    			error: function (error) {
                alert(JSON.stringify(error));
    			}
    				
    		});
    		
    	}
    	
    	getItems(urlToAppend, function(itemWorkflowStatus){
    			console.log("itemWFS: "+itemWorkflowStatus);
    		
    		if (itemWorkflowStatus == "Document folder created") {
    			console.log("WFS is Doc Folder Created, Confirm button will show");
    		} else {
    			console.log("WFS is NOT Doc Folder Created, Confirm button will hide");
    			SetHidden();
    		}
    			
    	});
    	
    	}
    	_spBodyOnLoadFunctionNames.push("DoIt");
    
    	// runs when the COnfirm button is clicked
    	function ExecuteThisFunctionBeforeSavingAndRedirecting() { 	
    		console.log("Confirm has been clicked");
    		
    		var urlAppend = "/_api/web/lists/GetByTitle('Staff recruitment')/items("+itemID+")";
    		
    		var Confirmed = "Confirmed";
    		$.ajax
            ({
                url: _spPageContextInfo.webAbsoluteUrl + urlAppend, // list item ID  
                type: "POST",
                data: JSON.stringify
                ({
                    __metadata:
                    {
                        type: "SP.Data.TestConfirmListItem"
                    },
                    WorkflowStatus: Confirmed
                }),
                headers:
                {
                    "Accept": "application/json;odata=verbose",
                    "Content-Type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "IF-MATCH": "*",
                    "X-HTTP-Method": "MERGE"
                },
                success: function (data, status, xhr) {
                    retrieveListItem();
    		console.log("Successfully Updated");
    	     location.replace="https://tenant/sitecol/site/Lists/Staff%20recruitment/AllItems.aspx";
    				
                },
                error: function (xhr, status, error) {
                    $("#ResultDiv").empty().text(data.responseJSON.error);
                }
            });
    		
    		return true;
    		
    	}
    
    </script>

    This generates an error in the console that 'data' is undefined for the line:

     $("#ResultDiv").empty().text(data.responseJSON.error);

    I'm not sure why this has suddenly stopped working. It was also the case that this call would result in success, not in error

    Wednesday, January 31, 2018 4:58 PM
  • Hi,

    Your ajax call returned error so you get 'data' is undefined, try to check the url is construct correctly.

    You could get the error message by below code also.

    error: function(xhr, status, error) {

      var err = eval("(" + xhr.responseText + ")");

      alert(err.Message);

    }

     

    Best Regards,

    Lee


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


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    • Proposed as answer by Dennis Guo Monday, February 5, 2018 7:42 AM
    Thursday, February 1, 2018 9:07 AM
  • Hi,

    I am checking to see how things are going there on this issue. Please let us know if you would like further assistance.

    You can mark the helpful post as answer to help other community members find the helpful information quickly.

    You can also share your own solution here and mark it as answer, and we can learn from each other.

    Best Regards,

    Lee


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


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Tuesday, February 6, 2018 6:57 AM
  • I believe the URL is constructed properly, here's a truncated screenshot of what I get when entering it directly in the browser:

    I was also wondering if the following line is correct as my list name has a space in it:

    ({
                    __metadata:
                    {
                        type: "SP.Data.Staff recruitmentListItem"
                    },
                    WorkflowStatus: Confirmed
    })

    But here's the list's properties:

    Adding the following log statements results in the following:

    console.log("XHR: "+xhr);
    console.log("Status: "+status);
    console.log("Error: "+error);

    Results:

    XHR: [object Object]

    Status: error

    Error: Bad Request

    I'm not familiar with IE11's debugging tools - but will try to have a go to get more information.

    Tuesday, February 6, 2018 5:03 PM
  • Hi,

    You could follow below steps to check the metadata type value.

    Go to IE settings, turn off feed reading.


    Go to browser, request /_api/web/lists/getbytitle('Staff%20recruitment')/items.


    Best Regards,

    Lee


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


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    Wednesday, February 7, 2018 1:36 AM
  • I have checked and "Turn on feed reading view" is not checked.

    I have also changed my call as per below, but still get the same error "data is not defined"

    ({
              __metadata:
              {
               type: "SP.Data.Staff_x0020_recruitmentListItem"
               },
               WorkflowStatus: Confirmed
    })

    Wednesday, February 7, 2018 4:54 PM
  • Hi,

    Here is my tested script which works in my local for your reference.

     <input id="btn_myUpdate" onclick="myUpdate()" type="button" value="myUpdate" />
        <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script type="text/javascript">
            function myUpdate() {
                $.ajax({
                    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Staff recruitment')/items(1)",
                    type: "POST",
                    data: JSON.stringify({
                        '__metadata': { 'type': 'SP.Data.Staff_x0020_recruitmentListItem' },
                        'Title': 'update'
                    }),
                    headers: {
                        "Accept": "application/json;odata=verbose",
                        "content-type": "application/json; odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                        "X-HTTP-Method": "MERGE",
                        "If-Match": "*"
                    },
                    success: function (data) {
                        alert("Item updated successfully!");
                    },
                    error: function (err) {
                        alert("Error while updating item: " + JSON.stringify(err));
                    }
    
                });
            }
        </script>

    Best Regards,

    Lee


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


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    • Marked as answer by PetyrBaelish Friday, February 9, 2018 11:53 AM
    Thursday, February 8, 2018 1:41 AM