User-related Resource Fields III

Get user info for any user-related resource field

In the last article, we saw how to get the full name (or username) of the user 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:

<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:


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

And here's the snippet code:

/* 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.

Comments (0)

Please login to comment.