Check relationships in after_save hooks

Hello

I have one custom module “CM” that is related in a 1:1 with Contacts module.

In this custom module, I have added two fields “CM->field1” and “CM-field2” that should be populated when the CM record is related with a contact record. I have tried to do this by using logic hooks “after_save” and “after_relationship_add”. My understanding is that “after_save” hook should be the proper one, but what I get is that first time the record is saved, fields are not populated, but if I edit the record back again, (with the relationship already present) and then save the record, it is when the fields are populated.

What it seems is that relationships are not saved at db level at the time the “after_save” is run ( I have checked also in the documentation that this could be the case in some modules).

Do you know any workaround or way to get the fields to be populated with the values of the related record by the time the relationship is saved in the first “after_save” execution?

Thanks a lot!

Hello

I have been reading a little bit more about the logic hooks, and I have changed my “after_save” hook by a “after_relationship_add” so my understanding is that the code will get fired once a new relationship is loaded with the record (exactly what I need).

However what I see is the same behaviour, I mean, even the new relationship is added (Record_Module A gest related (added) to record_module B), I still can not fill fields in record_module_b with values from record_module_A

Is this the right way of achieving this?

Regards!

It should be possible. I think the after_relationship_add triggers twice, once for each direction in the relationship (a–>b) and (b–>a).

By using a debugger you can check if the beans are there for you to change. But you need to get the order of things right. If the beans are already saved (before the relationships getting saved), then you might be changing beans, but they won’t get saved afterwards.

If you save them explicitly in your hook, you risk generating an infinite loop of hooks. but there are ways to avoid this, search for articles explaining how to check a hook only runs once.

Thanks, for the help. I think I have found the solution. Instead of obtaining the relalted record by attacking the DB directly I have introduced this code in the hook function

$contact = BeanFactory::getBean(‘Contacts’,$arguments[‘related_id’]);

With this I can get the values of the related record I need and assign them to the fields of the master record.

Hope it helps to someone else :slight_smile:

1 Like