Create Custom Save and Redirect Button On A SharePoint Form

Recently, I got a requirement, where I had to create a custom save button on a SharePoint Form and on the click of the button, I had to do some operation before triggering validation and ultimately save the item and redirect, so I would like to share my knowledge on it and the way of implementation.

Here, we will be learning the following.

  • How to create a custom save button on .ASPX page?
  • How to redirect on button click in .ASPX page?
  • How to call a custom function on button click in .ASPX page?
  • How can we pass a parameter in a redirection URL?

First, create an HTML input tag with type button on .ASPX page. Let’s say I have done it on EditForm.aspx.

  1. <input style="margin:0" id="customSave" type="button" value="custom Save" name="btnSave" onclick="if (!ExecuteThisFunctionBeforeSavingAndRedirecting()) return false; {ddwrt:GenFireServerEvent('__commit;__redirect={webAbsoluteUrl/Lists/ListName/NewForm.aspx?isCustomSaved=Yes}')}" />  

It is onclick, where we have to do some operations before saving so write and check if the function returns true to proceed and save, as shown below.

  1. onclick="if (!ExecuteThisFunctionBeforeSavingAndRedirecting()) return false;”  

If the function executes correctly and returns true, the form is saved, using the command given below. {ddwrt:GenFireServerEvent('__commit')}

Now, for committing and redirecting to another location, let’s say here that we are redirecting to the NewForm. We write - {ddwrt:GenFireServerEvent('__commit;__redirect={webAbsoluteUrl/Lists/ListName/NewForm.aspx}')}

After redirecting, when NewForm opens; it will be same as created on new item and not the redirected form, so for this, set a parameter in the redirection URL.

  1. __redirect={webAbsoluteUrl/Lists/ListName/NewForm.aspx?isCustomSaved=Yes}  

Second, the operation which you need to perform has to be coded somewhere. I have included that particular function in JavaScript file and gave the reference of the NewForm.js in the ScriptEditor Webpart inserted on EditForm.aspx.

NewForm.js 

  1. function ExecuteThisFunctionBeforeSavingAndRedirecting() {  
  2.     //Do Something  
  3.     if (!PreSaveItem()) return false;  
  4.     else return true;  
  5. }  
  6.   
  7. function PreSaveItem() {  
  8.     //Do Validation Code  
  9. }   

Here, once the operation is done, call for the PreSaveItem(); function where the code for validation is present.

If the PreSaveItem returns true, the forms saves successfully and redirects, else the form doesn’t save.