How do I get the ContentParts for the detail view?

Topics: Customizing Orchard, General, Writing themes
Feb 21, 2011 at 4:47 PM

So I want to get the field content parts for the detail view of a content type and I was able to do so under the summary view using the following:

@{
    Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
    foreach (var content in Model.Content)
    {
        Orchard.ContentManagement.ContentPart contentPart = content.ContentPart;
        fields = contentPart.GetFields(fields);
        if(!fields.ContainsKey("body") && !String.IsNullOrEmpty(content.Html.ToString()))
        {
           fields["body"] = content.Html.ToString();
        }
     }
}

public static Dictionary GetFields(this ContentPart part, Dictionary fields = null) {
   var dictionary = fields ?? new Dictionary(StringComparer.InvariantCultureIgnoreCase);
   foreach(var field in part.Fields)
   {
      dictionary[field.Name] = field.Storage.Get();
   }
   return dictionary;
}

but this doesn't work for the Details view (either Content-{type}.Details.cshtml or Content-{type}.cshtml). With Clay, its kind of hard to dive in and see whats going on.

Thanks
Feb 21, 2011 at 4:50 PM

Just as a sidenote, using the above under Summary was producing 2 lists of fields (i'm guessing for each major part?). One of the lists had the field names but the values were null.

(hence the need to loop and add to the dictionary)

Feb 21, 2011 at 5:16 PM

Nevermind, it looks like some of the Content items do not have a ContentPart. Solved this by adding some null checks.

Incase anyone else is interested, here is the code that works:

Extension method:

        public static Dictionary<string, string> GetFields(this ContentPart part, Dictionary<string,string> fields = null) {
            var dictionary = fields ?? new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
            if(part.Fields!=null) {
                foreach (var field in part.Fields) {
                    if(field != null && field.Storage != null) {
                        var fieldValue = field.Storage.Get<string>();
                        if(!string.IsNullOrWhiteSpace(fieldValue))
                            dictionary[field.Name] = fieldValue;
                    }
                }
            }
            return dictionary;
        }

View code:

@{
    Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
    foreach (var content in Model.Content)
    {
        Orchard.ContentManagement.ContentPart contentPart = content.ContentPart;
        if(contentPart != null){
            fields = contentPart.GetFields(fields);
            if (!fields.ContainsKey("body") && !String.IsNullOrEmpty(content.Html.ToString()))
            {
                fields["body"] = content.Html.ToString();
            }
        }
     }
}