I've been doing too many long blog articles lately, so here's a short one.
A MODX Forum user asked how to get the pagetitle of the current resource's parent in Revolution. I thought I'd put my answer up here to make it easier to find.
It can be done with a very simple snippet that gets the parent field of the current resource, retrieves its parent object from the database, and gets the content of the parent's pagetitle field.
This tag goes where you want the parent's pagetitle to appear:
[[!GetParentPagetitle]]
Here's the code of the GetParentPagetitle snippet. It's a somewhat verbose version to make it easier to understand:
$output = '';
/* Get the current resource's 'parent' field */
$parentId = $modx->resource->get('parent');
/* Get the parent object */
$parentObj = $modx->getObject('modResource', $parentId);
/* If we have the parent,
get and return the pagetitle */
if ($parentObj) {
$output = $parentObj->get('pagetitle');
}
return $output;
The if ($parentObj) sanity test is important. Resources at the root of the tree have no parent, so if this snippet executes in one of them you'll get a PHP error when $parentObj->get() is called because the $parentObj will be null. Because we set $output to an empty string at the top of the snippet, that's what will be returned if there's no parent.
Here's a much more compact version of the same snippet:
$parentObj = $modx->getObject('modResource', $modx->resource->get('parent'));
return $parentObj? $parentObj->get('pagetitle') : '';

Comments (1)
Susan Ottwell — Jan 17, 2014 at 08:07 PM
The fastField extra makes this easy: [ [#[ [*parent] ].pagetitle] ]
pdoTools comes with a snippet pdoField that combines UltimateParent with getResourceField, allowing you to get any field from any parent, grandparent, etc up the tree at a given level. It can be used as an output modifier or as a snippet.
If when installing pdoTools you also install its optional parser extension you can use its implementation of fastField.
Please login to comment.