How to update a field in an after_save logic hook?

Hello all,

I have created a custom field to hold an autoincrement value for each record in the module. This works ok.

I would like to use this number as a part of the name of the record. So, I have created a logic_hook based on the after_save event.

Unfortunately, it seems that $bean data is not available when after_save-ing.

It I test the logic_hook in before_save event, the code works ok and Name field is properly updated. However I can't use the code in before_save because it only would work when editing records not when creating them, because the logic hook would be fired before setting the autoincrement value.

Any ideas?

Here is my code, so simple. I'm on SugarCRM CE 6.5.11.
class my_class{
  public function my_function(&$bean, $event, $arguments){
    $bean->name = $bean->my_autoincrement_field_c;
  }
}
Parents
  • In a case like this I'd go straight to the database and do an update query. Either that or in your after_save call do a $bean->save(). There is some built-in protection against nested logic hooks, but it would be wise to also set a static var to ensure that your hook only runs once if you call ->save() again.
  • Jaume,

    To add to eggsurplus's notes, in your after_save hook, you just need to :

    $bean->db->query(" UPDATE {$bean->table_name} SET name='{$bean->my_autoincrement_field_c}' WHERE id='{$bean->id}' ");

    This will update the name field in the bean's table with the value from the 'my_autoincrement_field_c'.

    But be careful whether you need the name to be set on EVERY save of the record as doing this without any checks/conditions will overwrite the "name" field if any other logic or users have updated it to something else.

    ie you might want to only update the name once and not everytime and/or based on certain checks/conditions.

    eg set it to the my_autoincrement_field_c value only if the name is empty

    class my_class{
      public function my_function(&$bean, $event, $arguments){        if(empty($bean->name)){
           $bean->db->query(" UPDATE {$bean->table_name} SET name='{$bean->my_autoincrement_field_c}' WHERE id='{$bean->id}' ");      }
      }
    }
    Cheers
    Kedar.
  • Thank you very much for your help, SugarNinja. I'm going to try your code. Thank you for your advices too. Both name and autoinc fields are set to readonly in editview and quickcreateview so it seems there is no risk on updating the name on each save, but it wouldn't be unuseful to take some cautions, as you suggested.
Reply Children
No Data