Using the API

Using getObject() To Fetch a Resource

gourmet fare

Get a Single Resource by Pagetitle

You want to fetch a single resource, using the pagetitle to determine which one.

jentree asked...

I am making an ajax call to a script using runSnippet and getResources. All I know is the parent id. I will not know the id of the actual resource so I am trying to get a resource by pagetitle.

The Solution

BobRay says...

If you just want a single resource, using getResources is serious overkill. You might try something like this:

$resource = $modx->getObject('modResource', array('pagetitle' => $location));
if ($resource) {
   $fields = $resource->toArray();
   $output = $modx->getChunk('locationTpl', $fields);
} else {
   $output = '<p>No results found</p>';

If you need to restrict it to resources directly under resource 1, it would be:

$resource = $modx->getObject('modResource', array('pagetitle' => $location, 'parent' => '1'));

What's the Story?

While getResources could be used to return a single resource, as BobRay said it's serious overkill. This is where the MODX API shines. You can fetch any object, including custom objects, by specifying the object type (in this case a modResource object) and an array of properties.

getObject() will return an object (of course...) with all of the object's fields from the database, so the easiest way to output what you want is to convert them to an array and use a chunk tpl to format your output. All of the object's fields will be available to the chunk as placeholders, for example [[+content]] to get the resource's content.