SharePoint | Properly parse users from multi user field
Problem:
Value retrieved from a SharePoint multi-user field is:
"44;#Tiago Duarte;#133;#Project ..."
However, do know that there is a way better solution.
SPFieldUserValueCollection will take the web and the field value and properly contain a list of the web's users contained in the provided field.
Solution:
Thanks to:
http://stackoverflow.com/questions/404024/how-best-to-convert-a-sharepoint-multi-user-field-string-into-an-array-of-spuser
Value retrieved from a SharePoint multi-user field is:
"44;#Tiago Duarte;#133;#Project ..."
- User names (starting with #)
- User ID (which if you remove # you will find a digit)
However, do know that there is a way better solution.
SPFieldUserValueCollection will take the web and the field value and properly contain a list of the web's users contained in the provided field.
Solution:
private void ProcessUsers(SPListItem item, string fieldName) { string fieldValue = item[fieldName] as string; SPFieldUserValueCollection users = new SPFieldUserValueCollection(item.Web, fieldValue); foreach(SPFieldUserValue uv in users) { SPUser user = uv.User; // Process user } }
Thanks to:
http://stackoverflow.com/questions/404024/how-best-to-convert-a-sharepoint-multi-user-field-string-into-an-array-of-spuser
What about if you aren't running in a context? I.E you are using SP list web services?
ReplyDeleteThis is not parsing a user string field, it's using objects which you can't do if you're workign with Services.
we'll if we have a list of users and we want to do something for each of them, I call that parsing. I tend to believe that we should take advantage of these strong types instead of messing around with string concatenation and splits. there should be classes for both server side and client side. if there is no alternative (could be the case), I guess we'll have to really master the type formats, specially dates (e.g. 2014-05-01T00:00:00Z) and single (-1;#LABEL|GUID) or multi-value MMS fields (-1;#LABEL1|GUID1 ;# -1#LABEL2|GUID2 ;# -1#LABEL3|GUID3). there are so many apis now that it also depends on what we are using.
ReplyDelete