Find My Symlinks I

Finding symlinks to a given resource

In the last article, we looked at how to remove bad URLs from a browser's MRU list. In this one, we'll take a look at code to find symlinks on a MODX site.

MODX logo

A MODX Forums user (jacielluve) wanted a way to find all the symlinks related to a particular resource. It's an interesting problem, since there's no way to look at a resource and guess which Symlinks point to it.

Symlink Review

In case you've forgotten, a symlink is a resource that points to another resource. In the database, the content field of a symlink contains the ID of another resource. When a user clicks on a link to a symlink, they stay on the same page with the same URL, but the content of symlink's target (the ID in the content field of the symlink), is "pulled into" the current resource and displayed.

In this series of articles, as in the modx documentation, we'll refer to symlinks as "symlinks". Remember, though, that the MODX object referred to is a modSymLink (capital "L"), so we'll use modSymLink when referring to the objects in code.

The Code

So, how do we find symlinks for a particular resource? We look for resources that have the target's ID in their content field. Here's the code to do that:

/* ID of original resource */
$originalId = 38;
$output = '';

/* Search criteria for getCollection */
$fields = array(
   'class_key' => 'modSymLink',
   'content' => $originalId,

/* Get all symlinks of resource 38 */
$symlinks = $modx->getCollection('modResource', $fields);

/* Display them */
foreach ($symlinks as $symlink) {
    $output .= "\n<br>" . $symlink->get('pagetitle') . ' (' . $symlink->get('id') . ')';

return $output;

Simple enough. We just get all the appropriate symlinks and display them.

You might wonder why we don't do this: $modx->getCollection('modSymLink'). It almost always works in the Manager, but I run a lot of code in my editor. There, using modSymLink sometimes results in a very ugly error complaining about not being able to find the modSymLink class code. This is because modSymLink extends modResource. In the editor, the modResource object may not exist and the modSymLink object won't work without it, so it's more reliable to always ask for modResource and specify the class_key.

Coming Up

This was fast and simple, but it's a pain to have to edit the snippet code every time we want to find a symlink. In the next article, we'll look at code to find *all* Symlinks in a MODX site.

Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)

Comments (0)

Please login to comment.