yj-t
4/6/2016 - 5:51 PM

Useful in conjunction with ContentBlocks for example to get nested field content (from a repeater)

Useful in conjunction with ContentBlocks for example to get nested field content (from a repeater)

<?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);