A MODX user asked for a snippet to create a link to the first child of the current resource, using the child’s pagetitle as the link text. This snippet will do that. It assumes that the first child is defined as the one with the lowest menuindex
. If your Resource tree is sorted by menuindex
(the default sorting method), the link will be to the resource just below the current resource in the tree.
You can send a &docId
property to get a link to the first child of another resource. If you leave that property out, the current resource is assumed. You can also set a &noResult
property to specify what will be returned if the resource has no children (defaults to an empty string).
Snippet Tag Examples
[code language=”html”]
[[!FirstChildLink]]
[[!FirstChildLink? &noResult=`No Children`]]
[[!FirstChildLink? &docId=12]]
[[!FirstChildLink? &docId=12 &noResult=`No Children`]]
[/code]
The Code
[code language=”php”]
<?php
/* FirstChildLink Snippet */
/* Use current resource if no docId sent */
$docId = $modx->getOption(‘docId’, $scriptProperties, $modx->resource->get(‘id’));
/* Set default noResult return */
$link = $modx->getOption(‘noResult’, $scriptProperties, ”);
/* Set up the query parameters */
$c = $modx->newQuery(‘modResource’);
$c->sortby(‘menuindex’, ‘ASC’);
$c->select(array(‘id’,’parent’, ‘menuindex’, ‘pagetitle’));
/* Limit search to children of the docId resource */
$c->where(array(
‘parent’ => $docId,
));
/* Get the first child (if there is one) */
$childObj = $modx->getObject(‘modResource’, $c);
if ($childObj) { /* Make sure we got one */
$childId = $childObj->get(‘id’);
$url = $modx->makeUrl($childId, "", "", "full");
$pagetitle = $childObj->get(‘pagetitle’);
$link = ‘<a href="’ . $url . ‘">’ . $pagetitle . ‘</a>’;
}
return $link;
[/code]
Summing Up
One interesting feature of this code is that it demonstrates an unusual use of the getObject()
method. Notice that we’ve set up the query parameters as if we were looking for an array of resources. In other words, the parameters are exactly as they would look for a call to getCollection()
.
It’s rare to use a full set of query criteria in a call to getObject()
, but obviously, it works fine. We could have called getCollection()
and then selected the first (and only) object in the array with the code below, but since we only want one object, using getObject()
will be slightly faster.
[code language=”php”]
$c->limit(1);
$children = $modx->getCollection(‘modResource’, $c);
$childObj = current($children);
[/code]
For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or better yet, buy my book: MODX: The Official Guide.
Looking for quality MODX Web Hosting? Look no further than Arvixe Web Hosting!