Modx Plugin: Set createdby of Resource to Match TV Value

362 Views Asked by At

I am trying to create a plugin that will take the value of a listbox TV and set the document's createdby field to match that TV's setting onDocFormSave. The TV populates itself automatically with all active users and output's their ID.

I have the following code for the plugin, but when I try to save any resource it simply hangs and never saves. setCreatedBy is the name of the listbox TV:

switch ($modx->event->name) {
    case 'onDocFormSave':

        $created_by = $resource->getTVValue('setCreatedBy')

        if ($resource->get('createdby') != $created_by) {  
            $modx->resource->set('createdby', $created_by));
        }
    break;
}
3

There are 3 best solutions below

0
On

If you omit the $resource->set... and run the plugin, will it pass? I'm wondering if you might be causing a loop, i.e $resource->set triggers another onDocFormSave. Do you have access to the server error.log? It probably contains whatever is crashing.

3
On

Untested.

It looks like setting also has to be done on the resource, not via the Modx-class.

$resource->set('createdby', $created_by); // You also have a ) too much in your code.

Inspected the docs.

0
On

Those on the Modx forums were able to give me a leg up.

switch ($modx->event->name) {
case 'OnDocFormSave':

    $created_by = $resource->getTVValue('setCreatedBy');

    if (!empty($created_by) && $resource->get('createdby') != $created_by) {
        $resource->set('createdby', $created_by);
        $resource->save();
    }
break;}

For reference, the way I handled gathering the names and user id's of Modx users and placing them in a selectbox TV was to use the Peoples snippet in an @EVAL binding:

@EVAL return $modx->runSnippet('Peoples',array('tpl'=>'peoplesTpl','outputSeparator'=>'||','active'=>'1'));

This is a petty dirty and slow way of doing things, but a request to have this be a standard field on Modx resources has been submitted to GitHub