New Logic Hooks after_relationship_add and after_relationship_delete

sugarcrmdevelopers —  July 12, 2012

SugarCRM Developer Blog is, as far as I can tell, the only existing documentation for the new(ish) logic hooks after_relationship_add and after_relationship_delete.

For after relationship add, the logic hook is set up like a standard logic hook. In the hook array in custom/moduleName/logic_hooks.php file you add a new entry like the one below…

Both beans aren’t necessarily loaded, but the id’s and bean names can be accessed via $arguments[‘module’], $arguments[‘related_module’], $arguments[‘id’] and $arguments[‘related_id’] so they can be $bean->retrieve()’ed.

An important thing to remember is that the main module’s custom after_relationship_add logic is called first and then the related module’s custom after_relationship_add logic is called.

HOWTO: After Relationship Add Logic hooks.

That last bit is a pretty important “gotcha,” as my recent experiences confirm that the beans really aren’t fully loaded. For some reason, I was unable to load all of the relationships I needed in my logic hook using the $bean value that I was given. To remedy, I simply reloaded the $bean value if I detect that I’m within this type of hook (the hook actually fires both on before_save and in after_relationship_add):

<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class Duplicator{
    function duplicate($bean,$event,$args){
        $dump_args = print_r($args,true);
        $GLOBALS['log']->fatal("[PSI] Order Duplicator Script invoked with ({$event} {$dump_args}).");

        /*
         * Beans are not fully loaded and/or not correctly loaded in the
         * after_relationship_add logic hooks. Whatever the issue,
         * they aren't ready to retrieve all of the relationships and
         * this seems to fix it.
         */
        if($event == 'after_relationship_add'){
            unset($bean);
            $bean = new kiss1_Orders();
            $bean->retrieve($args['id']);
        }

        $bean->load_relationships('opportunities');
        ...