Why call bean->save() in before_save logic hook?

The documentation on before_save logic hooks states that "calling save on the bean in this hook will cause an infinite loop if not handled correctly". I'm curious, what are the circumstances when you would need to call save on a bean in a before_save logic hook? Since the bean is saved automatically after the before_save hook runs, I can't think of a reason to call save inside the hook.

If there is a good reason to call save in a before_save hook, how can one do it to prevent an infinite loop?

Parents
  • Hi Yury Voloshin,

    There are multiple scenarios where we can call save function in the before_save logic hook. Following are some examples:

    1) When we need to create another record during the creation of the existing record of the "same module". For the more detailed explanation you can have a look here: Creating Record Inside Logic Hook 

    2) When we need to create another record during the creation of the existing record of the "different module". For example in the before_save logic hook of Account's module we are creating a Contact's record and then calls $contact_bean->save for the Contacts record. On the other side in the before_save logic hook of Contact's module we are creating a record of Accounts and then call $account_bean->save for Account's bean. In this case, both logic hooks will call each other again and again and then the infinite loop will trigger.

    There are multiple customizations by which we can avoid the infinite loop. For example:

    1) We can use static variables: Prevent a Logic Hook From Running Multiple Times 

    2) We can use $bean->processed = true; property. It makes sure during the save procedure of bean it tells the SugarBean class to avoid the execution for the next iteration during the current save process

    3) You can create and use your own custom properties to figure out this situation.

    4) We can handle the other record's creation in the "after_save Logic" hook.

Reply Children
No Data