Using getValue() to get Object Content

In previous articles, we looked at a very fast and efficient xPDO method for getting the value of a single field from a MODX object using the getValue method of the xPDO object. For example, this code will get the introtext field from a resource with the pagetitle “Products”:

In this article, we’ll look at using it to get the content of objects like resources, chunks, templates, snippets, and plugins.

The main code of our method is similar, but as we learned in an earlier article, you need to know the “name” of the content field. If you have the object, you can get its content with $object->getContent(), but with our method, we’re not actually getting the object, just the value of a single field. If you’re getting the object by name, as you often are, you also have to know the name of the “name” field.

It’s handy, sometimes, to get content of a particular object. You might want the main content of a resource, the PHP code of a snippet or plugin, the raw contents of a chunk, or the HTML code of a template.

Here is our method, modified to get the content field of the various objects. Remember that this will get the raw content and any tags it contains will not be processed in any way.

Chunks

With Chunks, you can also get the content with $modx->getChunk('MyChunk'), but our method will be a little faster because it eliminates an unnecessary function call.

One good use of this method is to store data in chunks. Since that data will usually not contain placeholders or other tags, it won’t need processing. For example, you could put the options for a drop-down list in a chunk as a comma-separated list and create the HTML for the drop-down list on the fly after retrieving the chunk’s content. This will be very fast and it will allow users to change the options just by editing the chunk. Using this method will be *much* faster than using a TV to store the options.

I’ll have some more examples of how to use getValue() to get multiple fields (optionally from multiple objects) in future articles, but if you’ve been following along, you’re probably a little tired of this topic, so I’ll take a break from it for a while.