Skip to content

Instantly share code, notes, and snippets.

@andronex
Forked from sepiariver/cloneResource.php
Created January 8, 2019 20:58
Show Gist options
  • Save andronex/735bf8e91f0659622550ad09d2e9f56d to your computer and use it in GitHub Desktop.
Save andronex/735bf8e91f0659622550ad09d2e9f56d to your computer and use it in GitHub Desktop.
A Snippet to clone a Resource into multiple, user-defined parent containers in arbitrary contexts
<?php
// get user-defined source document and target parents
$source = intval($modx->getOption('sourceId', $scriptProperties, ''));
$targets = array_map('trim', explode(',', $modx->getOption('targetIds', $scriptProperties, '')));
// to prevent accidents...
$_allowedUsers = explode(',', 'username1,username2');
// check stuff, and if passed then get the source document object
if ( !in_array($modx->user->get('username'), $_allowedUsers) || empty($source) || $source == 0 || !is_array($targets) || empty($targets) ) return;
$sourceDoc = $modx->getObject('modResource', $source);
// loop through the defined target parents, create new child objects with overrides
foreach ($targets as $target) {
$parent = intval($target);
$parentDoc = $modx->getObject('modResource', $parent);
if ( !is_object($parentDoc) ) continue;
// the duplicate() method is pretty rad, Jason!
$newDoc = $sourceDoc->duplicate(array(
'newName' => $modx->getOption('name', $scriptProperties, ''),
'parent' => $parent,
'duplicateChildren' => $modx->getOption('duplicate_children', $scriptProperties, true),
'prefixDuplicate' => $modx->getOption('prefixDuplicate', $scriptProperties, false),
'publishedMode' => $modx->getOption('published_mode', $scriptProperties, 'unpublish'),
'overrides' => array('context_key' => $parentDoc->get('context_key')),
));
$output[] = $newDoc->get('id');
}
// what happened? this is very basic reporting. Could do with some calls to MODX log
return implode(', ', $output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment