MODX User-related Resource Fields III

In the last article, we saw how to get the full name (or username) of the usMODX logoer for any of the user-related fields, but to change the field, we had to rewrite the code of the snippet. In this article we’ll see a snippet that will handle the current user plus any other user-related field for the current resource.


The Wrong Way

Using the snippet from the previous article, we could display user full names for multiple fields like this:

[code language=”html”]
<p>Created By: [[!GetFullname? &type=`createdby`]]</p>
<p>Published By: [[!GetFullname? &type=`publishedby`]]</p>
<p>Edited By: [[!GetFullname? &type=`editedby`]]</p>

This will definitely work, but we’re calling the snippet three times for no good reason. That’s ridiculously inefficient since the snippet could easily get all three names for us if we rewrote it.


Another Way

This isn’t the best way, but it’s definitely a step forward. We’ll use placeholders for the names and set them in the snippet. Here’s the HTML code:

[code language=”html”]

<p>Created By: [[+createdby]]</p>
<p>Published By: [[+publishedby]]</p>
<p>Edited By: [[+editedby]]</p>

And here’s the snippet code:

[code language=”php”]

/* GetFullnames snippet */

$fields = array(

/* Perform the query to get the full name for each field */
foreach ($fields as $field) {
$userId = $modx->resource->get($field);
$query = $modx->newQuery(‘modUserProfile’, array(‘internalKey’ => $userId));
$name = $modx->getValue($query->prepare());

/* Use username as a backup if the fullname is empty */

if (empty($name)) {
$query = $modx->newQuery(‘modUser’, $userId);
$name = $modx->getValue($query->prepare());

$modx->setPlaceholder($field, $name);

The code simply loops through the fields, getting the fullname or username for each one and setting the placeholder for each one. Because we used the field names for the placeholder names, we can use the $field variable to get the user ID and to set the placeholders. We could have used different placeholder names (e.g., createdby.user, but it would make the code more lengthy and less efficient.


Coming Up

It has probably occurred to you that the use case above is crying out for a Tpl chunk. In the next article, we’ll use a Tpl chunk to make things a little more efficient and to demonstrate how to use Tpl chunks in MODX 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!

Tags: , , | Posted under MODX, MODX | RSS 2.0

Author Spotlight

Bob Ray

Bob Ray is the author of MODX: The Official Guide and over 30 MODX add-on components. He hosts Bob's Guides, a source of valuable information for MODX users, and has been very active in the MODX Forums with over 19,000 posts.

Leave a Reply

Your email address will not be published. Required fields are marked *