Last active
December 21, 2017 12:18
-
-
Save sepiariver/c88dce525d3954637c75 to your computer and use it in GitHub Desktop.
Accessor snippet for MODX Resource properties field.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment