Search code examples
sugarcrmsuitecrm

assigned_user_id doesn't change


Gotta be something simple I'm sure, but I'm just not seeing it.

I have a before and after save hooks which simply check if the assigned user ID has changed. But I'm getting the same user_ID in the before AND the after save hooks.

Logic Hook registry

$hook_array['before_save'] = Array();
$hook_array['before_save'][] = Array(
 77,
 'If a new user is assigned to the unit of inventory it changes inventory status to OFFER',
 'custom/modules/un_inventory/user_assigned_c.php',
 'user_assigned_c',
 'user_assigned_before_save');

$hook_array['after_save'] = Array();
$hook_array['after_save'][] = Array(
 78,
 'If a new user is assigned to the unit of inventory it changes inventory status to OFFER',
 'custom/modules/un_inventory/user_assigned_c.php',
 'user_assigned_c',
 'user_assigned_after_save');

And the logic hook

class user_assigned_c {

    function user_assigned_before_save($bean, $event, $arguments) {

        $GLOBALS['log']->info('User ID before save: '.$bean->assigned_user_id);

    }

    function user_assigned_after_save($bean, $event, $arguments) {
        // $bean->assigned_user_id stays the same as in the method above...
        $GLOBALS['log']->info('User ID after save: '.$bean->assigned_user_id);
    }

}

Solution

  • This is expected. A usual flow might be the following:

    $bean = getBeanFromSomewhere();
    $bean->assigned_user_is = "12345ABC";
    $bean->save();
    

    Note that, in the save the assigned user id is already set.

    If you want to check what the previous value of something is in a hook you can use the fetched_row attribute - this stores a list of the fields as they were when the bean was loaded.

    I.e.

    $newId = $bean->assigned_user_id;
    $oldId = $bean->fetched_row['assigned_user_id'];
    if($newId !== $oldId){
        //Assigned user changed!
    }
    

    I believe there was issues in the past with fetched_row in an after save hook but hopefully the above helps.