Monday, April 7, 2014

Assign default value to person field in out of the box list forms

Boy its been more than a year since I last posted. But here's the latest on my learnings...

Have you ever had a need where you are asked if you can default a person field with current logged in user? I am sure a lot of you may have, and many have went the route of InfoPath forms / 3rd party components & many may have written custom JavaScript to achieve it.

I went ahead and wrote a custom jQuery plugin that i plan to use it for this requirement moving forward. Here's the link to the plugin. In order to get it to work do the following

  1. Open your default new item form in edit mode. 
  2. Add a content editor webpart 
  3. Add content using HTML Markup by click on the content editor web part & clicking on the below options
  4.  on the HTML markup editor  add the below mentioned script
<script src="{relativesiteurl}/scripts/framework/jquery-1.10.2.min.js" type="text/javascript"></script><script src="{relativesiteurl}/scripts/framework/jQuery.commonFunctions.js" type="text/javascript"></script>


<script type="text/javascript">

$(document).ready(function () {


$().assignDefaultUserToPeoplePicker({fieldDisplayName: "Submitted by", loginName:"{loginname}"});

});

</script>

Here the
  • {relativesiteurl} is the relative path to your site collection.
  • scripts is a document library where the jQuery plugin and my custom plugin has been uploaded
  • framework is the folder inside the scripts document library that houses the js files
  • {loginname} is the network user name.

If you don't want it to default to a specific user name and would like to default to current logged in user's loginname do the  following

$().assignDefaultUserToPeoplePicker({fieldDisplayName: "Submitted by"});

I have tested the code in both SP2010 and SP2013 and it works as expected. If any of you run into issues feel free to comment here and I will get back to you as soon as i can.

SP 2010 Test - Screenshot

SP 2013 Test - Screenshot

The way this plugin works is by searching the display name that is being passed to the plugin, and assigning the people picker div the login name that is either passed to the plugin or retrieved using client side object model. It would then invoke the checknames action manually to ensure the login name assigned resolved properly and the assignment is seamless to users.

No comments:

Post a Comment