Logic Hook Field-Change Detection, $bean->$field vs $bean->fetched_row[$field]

sugarcrmdevelopers —  March 30, 2012

SugarCRM Logic Hooks are a powerful way of interacting with data or other systems on specific system actions, usually retrieving or saving a record. A common customization challenge we face is saving a record and performing an action if a particular field has changed. For example, if a phone number field changes for a contact, we want to merge the updated contact record with another system via an API. Let’s look at how to detect changes.

Logic hooks are well enough explained in the Developer Guide and other sites like Angel Magaña’s Simple SugarCRM Logic Hook Example. I won’t explain them in-depth here. What I want to get into is detecting changes on key fields. That said, here’s an example of a logic hook that does just that:

<?php
class DataSync{
	/*
	 * The method that does the checking for the specific fields. This is
	 * the method that we'll want to call in the logic_hooks.php file.
	 */
	function CheckUpdatedFields($bean, $event, $arguments){
		// if there are more than one field you're interested in, use an array
		$key_fields = array('phone_home','phone_other','phone_work');
		// and cycle through them
		foreach($key_fields as $key_field){
			// do a change detection leveraging the fetched_row value
			if($bean->$key_field != $bean->fetched_row[$key_field]{
				// and if a change is detected, queue up the Sync method
				$this->SyncToSystem($bean,$key_field);
			}
		}
	}

	/*
	 * A Generic Placeholder function, to be called when a change is detected
	 */
	function SyncToSystem($bean,$field){
		// placeholder
		return true;
	}
}

This hook is doing the change-detection by leveraging the $bean->fetched_row value. fetched_row holds the information from the database that was originally retrieved. This works in a before_save logic hook, because the database value hasn’t yet been updated, but the $bean->$field itself has been changed. Comparing the live value ($bean->$field) and the stored database value (in $bean->fetched_row[$field]) will show whether or not that field has been modified.