I'd like a isDirty($bean) function in my code

I find it very useful in my Laravel code and now I kind of need it in my sugar code.  I have many external sources putting data in my system. We have many custom APIs that save data or update data. But sometimes these external systems send Data it is exactly the same as the data that's already in the database, my system does the save anyway which kicks off workflows BPM's logic hooks yada yada yada.  All of this is unnecessary since nothing has really changed. What I'd like to do is before I save anything I'd like to check to see if there are any differences. But there's just no good way to do this, and I'm kind of worried about slowing down the system too much. 

My first attempt is here (I updated it after  answered)

<?php
/**
 * Checks to see if any field in a beam has changed in relation to what's in
 * the database right now
 *
 * It does not check many to many relationships
 *
 * @param SugarBean $bean
 * @return bool
 */
function isDirty(SugarBean $bean): bool
{
	$tableName = $bean->table_name;
	$beanID = $bean->id;
	if (empty($beanID) || empty($tableName)) return false;
	$persistedState = is_array($bean->fetched_row)
		? array_merge($bean->fetched_row, $bean->fetched_rel_row)
		: [];
	foreach ($persistedState as $fieldName => $fieldValue) {
		if ($fieldName !== 'id_c' && $bean->$fieldName != $fieldValue) {
			return true;
		}
	}
	return false;
}
?>

This works well enough for what I need, I'm not sending saves from the UI through it, just calls to my custom APIs so it doesnt affect users at all but still, its not terribly elegant.

Anyone got a better way to do this?

Parents Reply
  • I can't believe I forgot about this, this is the code that feeds the array to an after save logic hook.  It's good to know, but that code is far more complex than I need it to be. It has to do a lot of translations that I don't really care about. I just need to know if the value changed.

    Although it does show me that I could use the fetched_row of the bean instead of making another SQL call so that would make my code smaller and faster.  No need for that function the checks for a custom table anymore. So that's a lot better actually.

Children
No Data