This project is read-only.

Accessing custom fields from code (and ViewModels)

Oct 21, 2010 at 2:27 AM

I wanted to extend the User content type to have a "FullName" field, but when I get back a list of users the "Fields" property always has a count of 0. I couldn't find any existing samples to learn from, so I simply tried user.Get(typeof(string), "FullName). This always returned null. When checking user.Fields it was always empty.

I dug deeper and found that the user.ContentItem.Parts seems to have 2 "User" parts of type ContentPart, one of which has my field. Unfortunately user.As<ContentPart>() gave me the first one that has a fields count of zero, not the 2nd one that has my custom field.

All I really want to do is create a page to list users showing their full names (from the custom field), once I have that worknig I'll add extra fields and try to make them searchable and have details pages.

Oct 21, 2010 at 4:13 AM

For a TextField this is this one:

var location = ((ContentItem)Model.ContentItem).Parts.SelectMany(p => p.Fields).Where(f => f.Name == "Location").First().Storage.Get<string>(null);

Replace "Location" by whatever your field name is. And get the ContentItem from the available source, depending on your context.

Oct 21, 2010 at 5:51 AM

Yeah, one should point out that there will eventually be a simpler way of doing that: this is a little crazy. Then again, it should be easy to create a small helper method for that...