What

Summary: this post will show some scenario’s and scripts on how to prefill, verify and update data in a default form of a default SharePoint Item List.

Why

As a Power User, I have spent many hours of searching the outer limits of the internet for some of these scenario’s. All I wanted was a post like this where I could copy, paste and make some small changes so that a default SharePoint Item Form would do as I wanted without the help of a system administrator, any third party solutions, advanced JavaScript or advanced JQuery. After many searches, trial & errors and failed attempts, I would always end up stopping my attempt and blaming the SharePoint Farm for wrong settings…

As one of the Portiva team, I asked a colleaugue (Peter Weij) to take a look and within one day he wrote me these scripts that worked in a SharePoint 2013 Foundation Farm where the Admins would never allow any third party application or even a configuration change!

How

Let’s have a look at my scenario’s and scripts.
Note that these scripts should work when you have the Content Editor Web Part and paste the code in the Edit Source section. I however always recommend that you use the Content Editor Web Part and link that web part in the Web Part Properties to a .txt file containing the code and that you save the file in a library where Version history is enabled. This way:

  • you can change the scripting / coding and always revert back to a previous version if needed
  • use the same script in multiple lists
  • change the script once for multiple lists

Break off very long field names / column names after a desired separator

In my case I wanted to create forms that would support multiple languages.
When a field or column is long in text, SharePoint just reserves more data for the label, moving the fill-in fields to the right. In case of very long names, the form becomes very ugly, unreadable or even containing horizontal scroll bars:

I wanted to break off the line at every new language. The double pipeline || was chosen as a separator because I almost never see two of them in normal text.

The script =

<script language="javascript" type="text/javascript">

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
	breakNlEnLines();
});

function breakNlEnLines(){
var myElements = document.querySelectorAll("nobr");
for (var i = 0; i < myElements.length; i++) {

		var html = myElements[i].innerHTML.toString();
		html =	html.split("<span")[0]
		
		var substring1 = ""
		var substring2 = ""
		
		if(html.indexOf("||") > 0){
			substring1 = html.split("||")[0];
			substring2 = html.split("||")[1];
		    html = substring1 + "</br>" + substring2
		}
		var spanElement = myElements[i].firstElementChild		
		if(spanElement != null && spanElement.outerHTML.length > 10){
			html += spanElement.outerHTML;
		}
		myElements[i].innerHTML = html;		
	
}
var myElements = document.querySelectorAll("nobr");
var maxLength = 150;
for (var i = 0; i < myElements.length; i++) {
	if(myElements[i].innerText.length > maxLength){		
		myElements[i].style.whiteSpace ="normal";
	}
}
}
(function()
{
  if( window.localStorage )
  {
    if( !localStorage.getItem('firstLoad') )
    {
      localStorage['firstLoad'] = true;
      window.location.reload();
    }  
    else
      localStorage.removeItem('firstLoad');
  }
})();
</script>

The result (the last part of the script is a fail-safe for certain browser versions) =

Stop the form from being saved if no attachment is added

As every power user should, I explained the business that this validation has no added value in terms of validation because I could add any attachment and then the form would save but it may be useful as a reminder. Note that the alert will be a popup on web page that users have to agree with.

The script =

<script type="text/javascript" language="javascript">
 function PreSaveAction() {

         var atch = document.getElementById("idAttachmentsTable");
          if (atch == null || atch.rows.length == 0)
 {
              document.getElementById("idAttachmentsRow").style.display='none';

alert("Graag de gevraagde bijlage(n) toevoegen. \n\n---\n\nPlease add the requested attachment(s).");
return false ; 
} 
else { return true ;} 
} 
</script>

The result =

Populate or pre-fill a people picker field with the current user upon opening

I don’t think that this scenario needs any explanation but let me explain the full scenario because this script combines multiple scripts so you can see how these can be combined:

  1. First it checks (function = checkEmailAdress) if the current user has an email address. If an email address is present, a popup notifies the user of which address will be used. If no email address is known, a popup notifies the user that no email address is known, that the user should take action and last but not least it hides the form.
  2. Secondly it populates (function = preFillUserData) two fields: a people picker with the current user account and a single line of text field with the current user login account stripped of any letters and starting zeros (note that the variables id1 and id2 are the database names of the fields / columns so you can change the display names)
  3. Thirdly it breaks (function = breakNlEnLines) the (display) names of the field by replacing the double pipe lines with a line break

The script =

<script language="javascript" type="text/javascript">

function preFillUserData(field1,field2){
	var clientContext = new SP.ClientContext.get_current();
	var web = clientContext.get_web();
	var currentUser = web.get_currentUser();
	clientContext.load(currentUser);
	clientContext.executeQueryAsync(function(){
		var userLogin = currentUser.get_loginName();
		var peoplePickerDiv = field1 
		var peoplePickerEditor = peoplePickerDiv.children[0]
		var spPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv.id]; 
		field1.children[5].value = userLogin;
		spPeoplePicker.AddUnresolvedUserFromEditor(true);  
		//spPeoplePicker.SetEnabledState(false);
		userLogin= userLogin.split('\\')[1]
		var persNr = userLogin.match(/\d+\.?\d*/)[0];
	  
		while(persNr[0] == "0"){
			persNr = persNr.substring(1)			
		}
		field2.value = persNr
  });
  
}
function checkEmailAdress(){
  var clientContext = new SP.ClientContext.get_current();
  var web = clientContext.get_web();
  var currentUser = web.get_currentUser();
  clientContext.load(currentUser);
  clientContext.executeQueryAsync(function(){	
		var email = currentUser.get_email();
  
	  if(email == "" || email == null){
		alert("Het account waaronder je bent ingelogd heeft geen e-mailadres en kan daarom geen formulieren invullen. Als je zeker weten bent ingelogd onder je eigen account, neem dan contact op met IT om dit te corrigeren of log anders in onder je eigen account. \n\n---\n\nThe account you have logged on with does not have an email address and therefore cannot submit a form. If you are certain that you are logged on with your own account, please contact IT to get this corrected or otherwise logon with your own account.");
		 window.history.back()
		document.getElementById("DeltaPlaceHolderMain").style.display = "none"
	  } else {alert("Het account waaronder je bent ingelogd heeft het emailadres "+email+" waarop je dus e-mails omtrent deze aanvraag gaat ontvangen. Als dit e-mailadres niet correct is, log dan in met het goede account. \n\n---\n\nThe account you have logged on with has the email address "+email+" which will receive emails concerning this request. If this email address is not correct, please log on with your correct account.");}
	  console.log("checked email");
  });
  
}
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
 checkEmailAdress();
});
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
	var id1 = "mlNameApplicant"
	var id2 = "mlNumberEmployee"
	
	var fieldId1 = document.querySelector('[id^="'+id1+'"]').id;
	var field1 = document.getElementById(fieldId1)
	
	var fieldId2 = document.querySelector('[id^="'+id2+'"]').id;
	var field2 = document.getElementById(fieldId2)
	
	preFillUserData(field1, field2);
	breakNlEnLines();
});

function breakNlEnLines(){
var myElements = document.querySelectorAll("nobr");
for (var i = 0; i < myElements.length; i++) {

		var html = myElements[i].innerHTML.toString();
		html =	html.split("<span")[0]
		
		var substring1 = ""
		var substring2 = ""
		
		if(html.indexOf("||") > 0){
			substring1 = html.split("||")[0];
			substring2 = html.split("||")[1];
		    html = substring1 + "</br>" + substring2
		}
		var spanElement = myElements[i].firstElementChild		
		if(spanElement != null && spanElement.outerHTML.length > 10){
			html += spanElement.outerHTML;
		}
		myElements[i].innerHTML = html;		
	
}
var myElements = document.querySelectorAll("nobr");
var maxLength = 150;
for (var i = 0; i < myElements.length; i++) {
	if(myElements[i].innerText.length > maxLength){		
		myElements[i].style.whiteSpace ="normal";
	}
}
}
(function()
{
  if( window.localStorage )
  {
    if( !localStorage.getItem('firstLoad') )
    {
      localStorage['firstLoad'] = true;
      window.location.reload();
    }  
    else
      localStorage.removeItem('firstLoad');
  }
})();
</script>

The result =

first a popup:

then the pre-populated line-broken fields:

I hope these scripts will help you out as much as they did for me!

Neem contact op

Coltbaan 4E
3439 NG Nieuwegein

+31 (0)85 - 489 1008

Meer informatie?

[gravityform id="1" title="false" description="false"]