pepebe
5/22/2012 - 10:51 AM

Update resource fields on save (MODX Revo 2.2)

Update resource fields on save (MODX Revo 2.2)

<?php

/* 
Update resource fields when they are saved

trigger on the following system events:
	OnBeforeDocFormSave
	OnDocFormSave 

note: changing / inserting tv values is better done onDocFormSave as the process for saving tvs onBeforeDocFormSave is much more complicated (apparently)

*/


switch ($modx->event->name) {

	case 'OnBeforeDocFormSave':
		if ( $mode == modSystemEvent::MODE_NEW ) {

			// stuff to do before saving a new resource
			// this example checks the parent document, and updates various resource fields
			if ( $resource->get('parent') == 32 ) {
				$resource->set('template','4');
			 	$resource->set('contentType','application/pdf');
			 	$resource->set('content_type',7);
			 	$resource->set('class_key','modStaticResource');
			}

		} else if ( $mode == modSystemEvent::MODE_UPD ) {

			// stuff to do before updating a resource

		}
	break;

	case 'OnDocFormSave':
		if ( $mode == modSystemEvent::MODE_UPD ) {

			// stuff to do after updating a resource

			if ( $resource->get('template') == '4' ) {
				/* checking a custom date, and updating if necessary */
				// first, compare the old existing tv value with the new submitted tv value	
				$new_tv_val = $_REQUEST['tv1']; // the submitted value
				$old_tv_val = $resource->getTVValue(1); // the old value (using id of tv)
				// do some comparison if necessary then save...

				if (!$resource->setTVValue(1, $new_tv_val)) {
				    $modx->log(modX::LOG_LEVEL_ERROR, 'There was a problem saving your TV...');
				} 
			}
		}	
    	break;

	default:			
	break;
}


return;