It looks pretty good. Thanks for posting it.
I hope you don’t mind a few minor suggestions.
Although it’s often used, you don’t need the test at the top (don’t forget to remove the closing }
):
if ($modx->event->name == 'OnDocFormSave') {
as long at that’s the only event the plugin is connected to the test will always pass.
This code:
if ($mode == 'new' || empty($tvv)) {
Should be:
if ($mode === modSystemEvent::MODE_NEW || empty($tvv)) {
In all cases, modDocument
should probably be modResource
. It’s recommended to work with the parent class. If you need to skip weblinks or symlinks, you can test the class_key
of the resource at the top.
You might want to make sure the save()
works before executing the last three lines:
if ($doc->save()) {
/* Your last three lines */
} else {
$modx->log(modX::LOG_LEVEL_ERROR, ' [YourPluginName] failed to save child resource';
}
This last one is optional, it will save a little memory and make your code shorter:
// first, define what we want to create:
$fields = array(
'parent' = 415, // simply the folder for the children
'pagetitle' = 'Example Page',
'longtitle' = 'Example - A New Document Created Through The Modx API',
'alias' = 'example-page',
'description' = 'Example description...',
'template' = 36, // template id that the child should use
'published' = 1,
'content' = '<p>This is some sample content.</p>',
);
$doc = $modx->newObject('modResource');
$doc->fromArray($fields, "", false, true);
if ($doc->save()) {
/* Your last three lines */
}