Wrap (notempty) MODX Fields

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=`
[[*longtitle]]
`]]

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:

      
[[+output]]

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 :)