pepebe
2/23/2016 - 9:16 AM

A Snippet to clone a Resource into multiple, user-defined parent containers in arbitrary contexts

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