MODX Quick Tip: Easily Filter Strings to Valid URLs

Jan 23, 2017

The Thirst

You have a field—any field—in which a CMS content editor will enter arbitrary text, and you want to turn it into a valid URL segment. You might want to use this inside an HTML attribute like id or class.

The Drink

MODX had to solve this problem early on, because the Resource "Alias" field (aka "permalink") is exposed to content editors to customize, but it has to be validated before saving it. Thus, there's a built-in method to handle this functionality.

You can create a custom Output Modifier that exposes the MODX core method. It could be something like this:

Things to note

  • The $options property accepts a regex pattern, and defaults to the System Setting used for filtering Resource aliases.
  • In output modifier Snippets, the $options variable is always set, but can be empty. The 4th argument to getOption shown above, means the default System Setting value will be used in this case.
  • In order to create valid id or class attribute values, you may want to customize the regex pattern, like so:
/[\0\x0B\t\n\r\f\a&=+%#<>"~:`@\.\?\[\]\{\}\|\^'\\]/

(This removes periods and colons in addition to the default characters.)

You would use this output modifier like any other:

[[+myPlaceholder:filterpathsegment]]

(Assuming you named the Snippet "filterpathsegment".) That's it. Happy MODX-ing!

*UPDATE: in Jan 2018 this was merged into Revo 2.x