Skip to content

Instantly share code, notes, and snippets.

@goldsky
Last active November 27, 2016 12:09
Show Gist options
  • Save goldsky/a99f6ec75dcbde30b1cd to your computer and use it in GitHub Desktop.
Save goldsky/a99f6ec75dcbde30b1cd to your computer and use it in GitHub Desktop.
Snippet to parse dynamic field and hold its values if the form submission returns back to the same page
<?php
/**
* fiDynamicFields snippet
*
* the snippet to manipulate this dynamic form, to parse the HTML code and
* to hold the submitted values if the page goes back to the same page.
*
* @link http://www.virtudraft.com/blog/dynamic-fields-in-multiple-pages-for-formit.html
* @author goldsky <[email protected]>
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3
*/
/**
* &itemTpl=`a chunk name`
* Chunk name as template to render each row
*/
$itemTpl = $modx->getOption('itemTpl', $scriptProperties);
/**
* &wrapperTpl=`a chunk name`
* (optional)
* Chunk name to wrap rendered items and place the javascript code.
* Leave this empty/unused if the javascript code is added directly in the template.
*/
$wrapperTpl = $modx->getOption('wrapperTpl', $scriptProperties);
if (empty($itemTpl)) {
$modx->log(modX::LOG_LEVEL_ERROR, '[fiDynamicFields] is missing &itemTpl');
return;
}
$phsPrefix = $modx->getOption('phsPrefix', $scriptProperties, 'dynfield.');
if (!isset($_POST)) {
return;
}
$reverting = array();
foreach ($_POST as $k => $v) {
if (!is_array($v)) {
continue;
}
$i = 0;
foreach ($v as $key => $val) {
$reverting[$key][$phsPrefix.'idx'] = $i;
$reverting[$key][$phsPrefix.$k] = $val;
$i++;
}
}
$items = array();
foreach ($reverting as $phs) {
$items[] = $modx->getChunk($itemTpl, $phs);
}
if (empty($wrapperTpl)) {
return @implode("\n", $items);
} else {
$wrapper = array(
$phsPrefix.'items' => @implode("\n", $items),
);
$output = $modx->getChunk($wrapperTpl, $wrapper);
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment