Wednesday 21 October 2020

Use Of PreSaveAction Function on List Forms In SharePoint 2013

 Introduction


PreSaveAction() is a JavaScript function that helps us to do something before the item will be saved. PreSaveAction function allows overriding functionality when the Save button is clicked. PreSaveAction function executes the code written for validation on the click of the save button. I just want to add one thing, you should override PreSaveItem - this is a SharePoint built in function. Instead, like mentioned above - override/create PreSaveAction.

Scenario

I have a default SharePoint list form with saving or cancel, I want the user to attach files while creating a new item. When the user clicks on save button, page post back happens and if validation fails, the validation message is displayed.

Solution

I used the following code with PreSaveAction function for validation to display messages on Save button click and Save button, attach runtime custom handler. Default Save button calls PreSaveItem method, which in turn calls PreSaveAction for any validations.

  1. $(document).ready(function ()  
  2. {  
  3.     ProducerReferral();  
  4.     attachEventHandlers(); // function for checking the duplication of files  
  5.     $('input[value=Save]').click(function ()  
  6.     {  
  7.         PreSaveTest();  
  8.     });  
  9. });  
  10.   
  11. function PreSaveTest()  
  12. {  
  13.     PreSaveAction();  
  14. }  
  15.   
  16. function PreSaveAction()  
  17. {  
  18.     if ($("#idAttachmentsRow").css("display") == "none")  
  19.     {  
  20.         $("#part1 > h4")[1].innerHTML += "<span style='margin-left: 40px;' class='ms-formvalidation ms-csrformvalidation'>Please Attach Files.</span>";  
  21.         returnVal = false;  
  22.     }  
  23.     else  
  24.     {  
  25.         return true;  
  26.     }  
  27. }  
This method is called when save button is clicked and messages are displayed in case of File not attached.

Title

Note: If you are using "$(document).ready" in your code, make sure PreSaveAction function is written outside this block, as in above code or else PreSaveAction method will not be called.

Reference

 

No comments:

Post a Comment

SharePoint 2013 - Uploading Multiple Attachments To The New Item On List Using JSOM And REST API

  Introduction In this article, we will explore how we can attach multiple attachments to the new item on list using JSOM and REST API. Ther...