Last active
December 21, 2017 12:32
-
-
Save sepiariver/3e638b5a9b7eb3f6af381bb973174c50 to your computer and use it in GitHub Desktop.
Useful in conjunction with ContentBlocks for example to get nested field content (from a repeater)
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 | |
/** | |
* getJsonProperty | |
* | |
* Example usage: | |
* [[getJsonProperty? | |
* &tpl=`myChunkTpl` | |
* &key=`0.rows.0.repeater.rows` | |
* &json=`[[cbGetFieldContent? &field=`28` &returnAsJSON=`1`]]` | |
* ]] | |
* */ | |
// Required | |
$json = $modx->getOption('json', $scriptProperties, ''); | |
$workingArray = $modx->fromJSON($json); | |
$key = $modx->getOption('key', $scriptProperties, ''); | |
if (empty($key) || empty($workingArray) || !is_array($workingArray)) { | |
$modx->log(modX::LOG_LEVEL_ERROR, 'getJsonProperty snippet requires json and key parameters'); | |
return; | |
} | |
// Options | |
$tpl = $modx->getOption('tpl', $scriptProperties, ''); | |
$iterateOnChildProperties = $modx->getOption('iterateOnChildProperties', $scriptProperties, true); | |
$iteratedOutputSeparator = $modx->getOption('iteratedOutputSeparator', $scriptProperties, PHP_EOL); | |
$toPlaceholder = $modx->getOption('toPlaceholder', $scriptProperties, ''); | |
$debug = $modx->getOption('debug', $scriptProperties, false); | |
// Access child properties | |
$key = array_filter(array_map('trim', explode('.', $key)), 'strlen'); | |
foreach ($key as $segment) { | |
if (!isset($workingArray[$segment])) break; | |
$workingArray = $workingArray[$segment]; | |
} | |
// Only attempt iteration on arrays | |
if (!is_array($workingArray)) $iterateOnChildProperties = false; | |
// Output | |
if (!empty($tpl)) { | |
if ($iterateOnChildProperties) { | |
$output = array(); | |
$idx = 0; | |
foreach ($workingArray as $item) { | |
$item['idx'] = $idx; | |
$output[] = $modx->getChunk($tpl, $item); | |
$idx++; | |
} | |
$output = implode($iteratedOutputSeparator, $output); | |
} elseif (is_array($workingArray)) { | |
$output = $modx->getChunk($tpl, $workingArray); | |
} else { | |
$output = $modx->getChunk($tpl, array('value' => $workingArray)); | |
} | |
} elseif ($debug) { | |
$output = '<pre>' . print_r($workingArray, true) . '</pre>'; | |
} else { | |
$output = ''; | |
} | |
if (empty($toPlaceholder)) return $output; | |
$modx->setPlaceholder($toPlaceholder, $output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment