yj-t
10/12/2015 - 2:23 AM

Accessor snippet for MODX Resource properties field.

Accessor snippet for MODX Resource properties field.

<?php
/**
 * getProps
 * Snippet to access MODX Resource properties.
 * @author @sepiariver
 * 
 * @package ResourceProperties
 * GPL+, no warranties express nor implied.
 * 
 **/

// Options
// Resource ID (optional)
$id = (int) $modx->getOption('id', $scriptProperties, 0);
// Optionally get a standard Resource field
$field = $modx->getOption('field', $scriptProperties, '');
// Top-level namespace in array $properties
$namespace = (string) $modx->getOption('namespace', $scriptProperties, 'core');
// 2nd-level key at $properties[$namespace][$key]
$key = (string) $modx->getOption('key', $scriptProperties, '');
// TPL Chunk
$tpl = (string) $modx->getOption('tpl', $scriptProperties, '');
// Dump array values if no TPL?
$dump = $modx->getOption('dump', $scriptProperties, false);
// toPlaceholder
$toPlaceholder = $modx->getOption('toPlaceholder', $scriptProperties, '');

// Get $resource object
$resource = ($id) ? $modx->getObject('modResource', abs($id)) : $modx->resource;
if (!($resource instanceof modResource)) {
    $modx->log(modX::LOG_LEVEL_ERROR, 'getResourceProps snippet could not load resource object.');
    return;
}
$fields = $resource->toArray();

// If $field property is set, just return it and nothing else is done
if (!empty($field) && isset($fields[$field])) {
    
    $return = (empty($tpl)) ? $fields[$field] : $modx->getChunk($tpl, array('output' => $fields[$field]));
    if (empty($toPlaceholder)) return $return;
    $modx->setPlaceholder($toPlaceholder, $return);
    return;

}

// Get properties
$properties = (empty($key)) ? $resource->getProperties($namespace) : $resource->getProperty($key, $namespace);
if (empty($properties)) return;

// Output
// Initialize
$output = '';
// If no TPL, return empty string or dump the array
if (empty($tpl)) {
    if ($dump) $output = '<pre>' . print_r($properties, true) . '</pre>';
    return $output;
}
// Template the data
$output = $modx->getChunk($tpl, $properties);
// Return if no placeholder specified
if (empty($toPlaceholder)) return $output;
// Otherwise set the placeholder and return nothing
$modx->setPlaceholder($toPlaceholder, $output);
return;