May 23, 2007

MOSS: Populating User fields programmatically

Problem:
On a Content Type you have People Picker fields and you wish to set values to them programmatically. Trying to put user Active Directory account name or anything in the field may results in error: Invalid data has been used to update the list item. The field you are trying to update may be read only.

Thoughts:
User name string must be in form User Id + ";#" + User name. How to get the user id?

If the user doesn't exist on the site collection, you will get an error. What MOSS does when you add user to a User field using a browser is that it adds the user to the Site Collection level (All Users list), as described here. Apparently there is some sort of issue related to this, but it is unclear what _should_ be done in this case.

Solution:
In order to do it, as far as I know, is to do it like MOSS does it, even though it's possible that MS will change the functionality slightly as they repair the "problem".

So what you must do is to add the user to the site collection and after that you can query the user ID using the UserGroup.GetUserInfo web service or just directly from the All Users List.

siteCollection.RootWeb.AllowUnsafeUpdates = true;
siteCollection.RootWeb.AllUsers.Add(userLoginName, string.Empty, string.Empty, string.Empty);
siteCollection.RootWeb.AllowUnsafeUpdates = false;

int id = siteCollection.RootWeb.AllUsers[userLoginName].ID.ToString();

string userNameIdString = id + ";#" + userLoginName;

No comments:

Post a Comment