[MODX] Get a Field Value – Fast!

MODX logoSuppose you want the value of a single field from some MODX object (most often, a resource, user, or user profile). Let’s use the example of a resource. You know something about the resource (e.g., its pagetitle, alias, or id). The usual way of getting a field value in code is to get the resource object with $doc = $modx->getObject() and then get the field with $doc->get('fieldName');. You also have to test the return value of getObject() because if it fails, the call to get() will throw a PHP error.

This method is somewhat slow and *very* wasteful of memory. You only want the value of that one field, but you’re pulling an entire resource object into memory. If you want to see just how wasteful that is, put a tag for this snippet on a page:

[code language=”php”]
return print_r($modx->resource, true);
[/code]

The resource object is monstrous compared to the size of the field you want. What if there were an easy way to get just the field? With a little xPDO magic, there is.

 

 

 

Credit for the method used in this article goes entirely to Jason Coward (OpenGeek). I would never have come up with it on my own.

A Concrete Example

Say you want the introtext (summary) field of a resource with this pagetitle: Products. This is all you need:

[code language=”php”]
$query = $modx->newQuery(‘modResource’, array(
‘pagetitle’ => ‘Products’,
));
$query->select(‘introtext’);
$intro = $modx->getValue($query->prepare());
[/code]

 

Breaking It Down

The method above will work for any MODX object with very little modification. The first argument to $modx->newQuery() is the class of the object you are looking to get a value from (modUser, modResource, modUserProfile, etc.).

The array member will always contain what you already know about the object, with the name of the field you know on the left, and its value on the right. In this case, it’s 'pagetitle' => 'Products'. It could just a well be 'id' => '23' if you knew the ID of the resource.

Finally, the value in the $query->select() line is the name of the field you want the value of, in this case, introtext.

If anything goes wrong (the object isn’t found or the field isn’t set), $modx->getValue() will return false.

It’s fast, it’s efficient, and it doesn’t care what the class_key of the object is, or what permissions the current user has.

Let’s look at a couple examples of using this method to get user information. We’ll assume that you want the email address of the user. The email address is in the user profile, not the modUser object. In each modUserProfile object, the user’s ID is in the internalKey field, so we need to use that field in the array argument to $modx->newQuery().

Case 1 — You Know the User’s ID

If you know the user’s ID, you can query the modUserProfile object directly:

 

[code language=”php”]
$userId = 12;
$query = $modx->newQuery(‘modUserProfile’, array(
‘internalKey’ => $userId,
));
$query->select(’email’);
$email = $modx->getValue($query->prepare());
[/code]

 

This was really easy because we knew the user’s ID, but what if we only had the username?

Case 2 — You Know the User’s username

The username is not stored in the user profile, so we need an extra step here. Luckily, we can use our method for both steps. Neither the user object, nor the user profile object need to be retrieved, just the two fields we want:

 

[code language=”php”]
/* Get the user ID */
$userName = ‘BobRay’;
$query1 = $modx->newQuery(‘modUser’, array(
‘username’ => $userName,
));
$query1->select(‘id’);
$userId = $modx->getValue($query1->prepare());

/* Make sure we got it */
if ($userId === false) {
/* Error! */
} else {
/* Get the email */
$query2 = $modx->newQuery(‘modUserProfile’, array(
‘internalKey’ => $userId,
));
$query2->select(’email’);

$email = $modx->getValue($query2->prepare());
}
[/code]

 

The test of the $userId variable is important. If no user is found with that username, the $userId will be false. Using that value in the second query may actually return a user, but not the one you want — definitely not what you want to happen.

More Fun With Users

The user-related fields in the resource object (createdby, editedby, publishedby, and deletedby) are stored as IDs. Let’s use our method to get the username of the user who created the current resource:

 

[code language=”php”]
$userId = $modx->resource->get(‘createdby’);
$query = $modx->newQuery(‘modUser’, array(
‘id’ => $userId,
));

$query->select(‘username’);
$userName = $modx->getValue($query->prepare());

[/code]

 

What if we want the full name? It’s in the user profile, so we’d do this:

 

[code language=”php”]
$userId = $modx->resource->get(‘createby’);

$query = $modx->newQuery(‘modUserProfile’, array(
‘internalKey’ => $userId,
));

$query->select(‘fullname’);
$fullName = $modx->getValue($query->prepare());
[/code]

 

Some Caveats

This method is fast and efficient, but there are a few catches you need to be aware of.

First, getValue() will always return a string containing the raw value of the field. With date fields, for example, it will return the raw timestamp (as opposed to get(), which will return a formatted time string). For boolean (true/false) fields like published and isfolder it will return '0' or '1'.

If a date field is empty (say, pub_date when there isn’t one set), getValue() will return '0'. If you try to display that empty date, you’ll get a result something like this:

[code language=”html”]
Wednesday, December 31 1969
[/code]

For empty text fields like introtext and description, it will return an empty string ('').

If you use it to get the content of an object such as a resource, chunk, template, snippet, or plugin, it will not process any of the tags in that field, though if you return the value in a snippet, MODX will process the tags before the page is displayed. You also have to know the actual field name of the content field. It’s content for resources, but not for the other objects.

As written above, the method won’t get a TV value for a resource, or even the default value of the TV.

In the next few articles, we’ll look at some trickier uses for this method and see how to use it with boolean fields, date fields, TVs, and some other objects.

 


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 *