MODX Quick Tip: Try Multiple Content Blocks Fields for Content

#MODX Quick Tip: Fallback Fields for Content Blocks "cbGetFieldContent" Snippet

Oct 11, 2015

The Problem

Content Blocks for MODX ("CB") is amazing. If you use it, you've probably run into the included Snippet cgGetFieldContent. It gives you access to fetch the content from a specific CB field that may (or may not) be used on the Resource. This is very handy, for example to pluck out a "featured" image, or grab a video embed from somewhere on the page and show it in a different view.

However, out-of-the-box the Snippet only accepts a single field ID. On some occassions, you may want to specify one or more fallback fields for content, in case the highest priority field isn't set, on a given Resource.

For example, on a listing view, I wanted to show a video if the Resource had the oEmbed field , but otherwise I'd be happy with one of the image fields. I could call the Snippet multiple times, each with different values in the &field property, but what if the Resource has more than one of the fields set? Instead of using unsightly conditionals in the template, I opted for this:

The Solution

[[cbGetFieldContentCustom? 
    &field=`5,3` 
    &resource=`[[+id]]`
]]

Break it down:

  1. &fields=`5,3` This is the only special bit. In my customized snippet, I check for a comma-separated value in the &field property, and test for a count of each one, in the order they appear. The first match breaks the loop and is used for the output.
  2. &resource=`[[+id]]` This just pulls the content from the currently-iterated Resource, in my listing view.

The Snippet

I tried to make as few changes as possible in the Snippet, and spent some time ensuring the variables were kept in-line with the original, so as not to break anything. I've yet to have a test fail, but there may be edge cases where this version of the Snippet breaks things. Test it thoroughly in your implementation before using it in production. Here's the code:

Check out the code comments to see what I did. There's a block on lines 53 and 74 where I handle the comma-separated values. That's it—everything else is identical to the original. Have fun with it!

P.S. You need Content Blocks installed for this Snippet to do anything. You can get it here.