Tuesday, November 27, 2012

Programmatically obtain an SPUser object from a SharePoint "Person or Group" field

Within a document library that's contained in our custom Team Site template, we have defined a custom content type (i.e. called Enterprise Document) in which we've specified a "Person or Group" field called "Owner" to store the person who has overall responsibility of the document and may be different from the person who created or last modified the document. The value of this field is set by the user who uploads the document to the library. Naturally, I would like to put this field to use and obtain information about the user that is defined in this field in one of our custom workflows.  In this sample case, I'm going to obtain the owner's email address:

SPList docLibrary = web.Lists["Enterprise Documents"];
SPQuery query = new SPQuery();
query.Query = "<where><eq><fieldref name="ContentType"><value type="Text">Enterpise Document</value></fieldref></eq></where>";
SPListItemCollection documents = docLibrary.GetItems(query);
foreach (SPListItem doc in documents)
{
    if (doc.Fields["Owner"] != null)
    {
        SPFieldUser ownerField = doc.Fields.GetField("Owner") as SPFieldUser;
        SPFieldUserValue ownerValue = ownerField.GetFieldValue(doc[ownerField.Id].ToString()) as SPFieldUserValue;
        SPUser owner = ownerValue.User;
        string ownersEmail = owner.Email;
        ...

Because we have multiple content types in this library, I added code to make certain that the content type of the document under review is based on our custom "Enterprise Document" content type since only that content type contains the "Owner" field mentioned above.  Anyway, I thought this might be useful to share since it took me several iterations before I figured it out.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.