[SharePoint 2010 – Developpement] Add current user to person field default value with event receiver ItemAdding–SharePoint 2010

I wanted to set a person field default value with my current user, but that doesnt exist in sharepoint.
What i did is :

  • I created an event receiver
  • I checked if it was my library
  • Then i set the person value thanks to the ItemAdding event firing
   1: /// <summary>
   2:        /// An item is being added.
   3:        /// </summary>
   4:        public override void ItemAdding(SPItemEventProperties properties)
   5:        {
   6:            SPSecurity.RunWithElevatedPrivileges(delegate()
   7:            {
   8:                try
   9:                {
  10:                    this.EventFiringEnabled = false;
  11:                    base.ItemAdded(properties);
  12:                    if (properties.List.RootFolder.Name == "libraryInternalName")
  13:                    {
  14:                        SPWeb web = properties.List.ParentWeb;
  15:                        SPList List = properties.List;
  16:                        //replace the id by your person colomn
  17:                        SPField fld = List.Fields[new Guid("03457d42-31a3-4088-b9af-4e3f2e368545")];
  18:                        SPUser usr = web.CurrentUser;
  19:                        SPFieldUserValue defValue = new SPFieldUserValue();
  20:                        defValue.LookupId = usr.ID;
  21:                        fld.DefaultValue = defValue.ToString();
  22:                        fld.Update();
  23:                        List.Update();
  24:                    }
  25:  
  26:                }
  27:                catch (Exception)
  28:                {
  29:                }
  30:                finally
  31:                {
  32:                    this.EventFiringEnabled = true;
  33:                }
  34:            });
  35:        }
Advertisements

One thought on “[SharePoint 2010 – Developpement] Add current user to person field default value with event receiver ItemAdding–SharePoint 2010

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s