Wrap (notempty) MODX Fields

Wrap MODX fields in custom HTML with only one line of code

Apr 23, 2014

Have you ever wanted to wrap a MODX tag in some HTML, and render it only if the value was not empty? If so, you might recognize something like this:

[[*longtitle:notempty=`<div class="some wrapper">[[*longtitle]]</div>`]]

Well, this is okay, but there's another way that keeps the logic in a Snippet, and the output template-able via a Chunk. (Very MODX-y way of doing it ;) Furthermore, it's only one line of PHP!

Just tell me how to do it...

Make yourself a custom Snippet in MODX by right-clicking the "Snippets" item in the Element Tree and selecting "New Snippet". Call it whatever you want – mine is "wrapifnotempty". Then in the code field, paste in this one line:

if (!empty($input)) return $modx->getChunk($options, array('output' => $input));

Break It Down:

  1. This Snippet is meant to be used as an output modifier, so the $input variable is populated with the value of whatever MODX tag you call with the output modifier, like this: [[*introtext:wrapifnotempty]].
  2. The $options variable holds the value from within the backticks, which in output modifier syntax is used like this: [[*introtext:wrapifnotempty=`myChunkName`]]. That value is the first argument passed to the $modx->getChunk method, which references the Chunk by name.
  3. The second argument to $modx->getChunk is an array with a placeholder key, in this case 'output', and the value to render in that placeholder, which is $input, the value of the input field.

In other words, take the value of this field and wrap it with this Chunk, rendering the field value in the placeholder called 'output'. Your Chunk may contain something like:

<div class="some wrapper">[[+output]]</div>

Now, if the field is empty, nothing will render, including the wrapper. Otherwise your field value is formatted exactly the way you want. Just another handy-dandy way to use your favorite CMS :)

UPDATED 2018-01-27: PHP's empty() may not actually be the right function for what you're trying to achieve here. If the string "0" is a valid "non-empty" value for your use case, it won't pass this output filter. In that case, use this:

if (strlen($input)) return $modx->getChunk($options, array('output' => $input));