We can't directly set default values for People picker fields in Sharepoint. We can achieve it using SPServices.
Below is the sample code to set logged in user name as default value for a People picker field
Access this link to know more about the SPServices method 'SPFindPeoplePicker' used to set people picker
Don't forget to check if the field value is empty before you set, as the end user might have changed the name and when the user clicks on Submit, if there are any validation errors, page reloads and the script gets executed.
Below is the sample code to set logged in user name as default value for a People picker field
<script src="../../Style Library/scripts/jquery.min.js" type="text/javascript"></script>
<script src="../../Style Library/scripts/jquery.SPServices-0.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$( document ).ready(function() {
//To set logged in user name as default value in a people picker field with display name, "Requested by"
//People Picker Field Display Name
var fieldName = 'Requested By';
//Check if the field is empty. As, this script gets executed each time the page loads(Could be during validations)
if(($().SPFindPeoplePicker({peoplePickerDisplayName: fieldName}).currentValue).trim() == '')
{
//Get current Logged in User
var currentUser = $().SPServices.SPGetCurrentUser({
fieldName: "Name",
debug: false
});
//Set logged in user name to the people picker
$().SPFindPeoplePicker({
peoplePickerDisplayName: fieldName,
valueToSet: currentUser,
checkNames: true
});
}
});
</script>
Access this link to know more about the SPServices method 'SPFindPeoplePicker' used to set people picker
Don't forget to check if the field value is empty before you set, as the end user might have changed the name and when the user clicks on Submit, if there are any validation errors, page reloads and the script gets executed.
No comments:
Post a Comment