Orchard CMS: Conditional Field Rendering

18 March 2013

Following the theme of "wow, that should be easy, but it's not as fast or easy as you'd think", here's my post / answer to the question "How can I show / hide a field on a content type based on the value of another field"?

If you've read about shapes in Orchard, and how they combine with the placement.info file to generate the output of your page, you'll quickly realise that what you really want to find out is how to access content fields from within your .cshtml / shapes. (If you haven't read about them, I'll wait here while you do, the links are here and also here...absorb it slowly) And once you understand how Orchard renders things normally, you can then throw in how it can render alternate shapes, if you so desire. Once we can do that, we can pretty much do it all with good old Razor syntax and we're good to go.

Example time! Let's say you have a Content Type called MyContentType, with a field named Message, and you want another field called SecretMessage to only appear if Message has not been specified. How I managed something like this was to create an alternate in my module for SecretMessage, in Views\Fields\Common.Text-MyContentType-SecretMessage.cshtml (alternates can happily live in your Theme as well, it's up to you). Within your alternate, you can then access Model.ContentItem.MyContentType (if you'll remember from my previous post, fields are added to a hidden part with the same name as the content type) which will by the magic of .NET 4.0 / dynamic objects / the Clay library also have a property called Message you can test for. So it'll kind of look like:

@if (HasText(name) && HasText(Model.Value) && !HasText(Model.ContentItem.MyContentType.Message.Value)) {
    <p class="text-field"><span class="name">@name:</span> <span class="value">@(new MvcHtmlString(Html.Encode((HtmlString) Model.Value).ReplaceNewLinesWith("<br />$1")))</span></p>

Simple, right? It is, once you find out how. (Perhaps Orchard just needs a list of common things that developers would like to do, and the recommended ways to do them - due to the speed of its development and the lack of clarity with the documentation, I'm not actually sure what I'm posting about here is the 'right' way, but it works, so I'm sticking with it until told otherwise.)

Enabling the Shape Tracing module will really help you out here, as well as with most other layout / rendering tasks - at first sight, it seems really involved for such a trivial task, but it's really all in service of Orchard being crazily customizable and flexible. Good luck!

Tags: alternates, fields, shapes, Orchard

Add a Comment

No Comments