HomeDevelopment (Old) Add current user to person field default value with event receiver...

[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:        }
- Advertisement -

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

CONNECT FOR MORE CONTENT

DO NOT MISS THOSE ARTICLES

Recent Comments