Orchard CMS: Right way to get field value from view?
Asked Answered
P

1

5

I have ContainerWidget and custom container type with ShowAllLinkCaption field. Now I have only one solution, and it's looks ugly. What is the right way to get this field value on a Container Widget View?

@*Latest news widget*@
@using Orchard.ContentManagement
@using Orchard.Utility.Extensions
@{
    var contentId = (int)Model.ContentItem.ContainerWidgetPart.Record.ContainerId;
    IContentManager contentManager = WorkContext.Resolve<IContentManager>();    
    var customListContentItem = contentManager.Get(contentId);
    var showAllLinkCaptionField = customListContentItem.Parts.SelectMany(p => p.Fields).First(f => f.Name == "ShowAllLinkCaption");
    var showAllLinkCaptionText = showAllLinkCaptionField.Storage.Get<string>(null);   
}
@Display(Model.Content)
@Html.Link(showAllLinkCaptionText, Url.ItemDisplayUrl(customListContentItem))
Pfosi answered 24/5, 2012 at 11:24 Comment(0)
P
13

ContentItem is a dynamic object that allows direct access to parts and fields without having to use those ugly Lambdas. You just need to know the name of the part that has the field, and you can do:

someContentItem.ThePartThatHasTheField.TheField.TheNameOfThePropertyYouWantToAccess
Pemphigus answered 24/5, 2012 at 17:5 Comment(4)
More excellent help from Bertrand... I wonder how it would be possible to figure this out without his help!Guardian
Bertrand has given a great anwser which was exactly what I was looking for! Sort of a "Holy Grail" of Orchard and what makes Orchard so great... But you knew there was a "but" coming, didn't you? ;) I have this : currentUser.UserCulturePart.Fields[0].Value; And it is working great. I have also a foreach loop which loops through fields of this content part and lists it's names. It is only 1 field with name "Culture". But if I try to access it like this: currentUser.UserCulturePart.Culture.Value it throws out an error that it doesn't contain Culture... Any ideas?Bilander
Regarding my last comment. I had .WithField("Culture ") in my migrations.cs... maybe a good thing to note, to put .Trim() when saving them? As this is very hard to debug and using field names which have spaces in them is impossible. I've already managed to break some code with spaces in fields names.Bilander
Good catch.Please file a bug.Pemphigus

© 2022 - 2024 — McMap. All rights reserved.