I had a UserMulti type field declared in my solution, and needed to read and write to it via an application page.
The field declaration:
<Field ID="{084A686D-60CA-4E95-AB4D-55D8B1DF1602}" DisplayName="APTN" Name="ictRiskAPTN" StaticName="ictRiskAPTN" Group="Ince Risk" List="UserInfo" ShowField="ImnName" Required="FALSE" Type="UserMulti" Description="By default... (omitted)" UserSelectionMode="PeopleOnly" UserSelectionScope="0" AllowMultiVote="TRUE" />
To read from the field:
[Note: Fields.AdditionalPeopleToNotify.Id is a property of a helper class that contains all the Ids, Displaynames and static names of my declared fields)]
var additionalRecipients = i[Fields.AdditionalPeopleToNotify.Id] as SPFieldUserValueCollection;
if (additionalRecipients != null)
{
if (additionalRecipients.Count > 0)
{
foreach (SPFieldUserValue uservalue in additionalRecipients)
{
//Do something with your user
}
}
}
To set the value of the field:
var i = listItems[0];
SPFieldUserValueCollection users = new SPFieldUserValueCollection();
SPPrincipal pr = web.EnsureUser("domain\\username") as SPPrincipal;
users.Add(new SPFieldUserValue(i.Web, pr.ID, pr.Name));
i[Fields.AdditionalPeopleToNotify.Id] = users;
i.SystemUpdate();
Or, for a more realistic example, set the value of the field based on a list of users or groups selected from a PeoplePicker control:
var i = listItems[0];
SPFieldUserValueCollection users = new SPFieldUserValueCollection();
if (peoplePicker.Entities.Count > 0)
{
foreach (PickerEntity entity in peoplePicker.Entities)
{
SPPrincipal pr = null;
if (entity.EntityData.ContainsKey("PrincipalType"))
{
var pT = entity.EntityData["PrincipalType"] as String;
if (pT != null)
{
switch (pT)
{
case "SharePointGroup":
pr = web.SiteGroups[entity.Key] as SPPrincipal;
break;
case "User":
pr = web.EnsureUser(entity.Key) as SPPrincipal;
break;
case "SecurityGroup":
pr = web.EnsureUser(entity.Key) as SPPrincipal;
break;
default:
break;
}
}
}
if (pr != null)
{
users.Add(new SPFieldUserValue(item.Web, pr.ID, pr.Name));
}
}
}
i[Fields.AdditionalPeopleToNotify.Id] = users;
i.SystemUpdate();
No comments:
Post a Comment