Recursion problem creating a group relationship.

Created on 10 August 2024, 5 months ago

Creating group content is always a 2 step process but this makes for a confusing UX. I'm trying to do it all in one step, but running into this problem.

function hook_myEntity_insert($myEntity) {// also update
  $group = Group::load(99);
  $props = [
    'type' => $group->getGroupType()->id().'-my_plugin-'.$myEntity->bundle(),
    'gid' => $group->id(),
    'entity_id' => $myEntity->id(),
  ];
  GroupRelationship::create($props)->save();
}

This falls into a recursive loop when GroupRelationship::postsave() calls $this->getEntity()->save().
Furthermore if I user hook_ENTITY_TYPE_update, the $myEntity passed through the loop is the original entity, not the updated one.
The script explains why

      // We want to make sure that the entity we just added to the group behaves
      // as a grouped entity. This means we may need to update access records,
      // flush some caches containing the entity or perform other operations we
      // cannot possibly know about. Lucky for us, all of that behavior usually
      // happens when saving an entity so let's re-save the added entity.

I tried moving that function to drupal_register_shutdown_function(), before realising it just falls into the same loop.
So please, manually do those operations you cannot possibly know about, and don't deny us the possibility of making a good user experience.

📌 Task
Status

Active

Version

3.2

Component

Code

Created by

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @matslats
  • I found a workaround in my hook_ENTITY_TYPE_update() which just stops the recursion

      $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
      array_unshift($backtrace);
      foreach ($backtrace as $trace) {
        if (isset($trace['function']) && $trace['smallads_group_smallad_update'] === $currentFunction) {
          return;
        }
      }
    

    McNasty!

Production build 0.71.5 2024