Skip to main content
2 of 3
deleted 36 characters in body
user avatar
user avatar

With the help from @Clive I found a solution:

/**
 * Implements hook_node_update().
 */
function MY_MODULE_node_update(\Drupal\node\NodeInterface $node) {
  $node = $form_state->getFormObject()->getEntity();

  foreach ($node->getFieldDefinitions() as $definition) {
    if ($definition instanceof \Drupal\field\Entity\FieldConfig) {
      if ($definition->getSettings()['target_type'] == 'media') {
        $media = $node->{$definition->getName()}->entity;
        if ($media) {
          $media->groups = $node->groups;
          $media->save();
        }
      }
      if ($definition->getSettings()['target_type'] == 'paragraph') {
        $paragraph = $node->{$definition->getName()}->entity;
        if ($paragraph) {
          ph_content_update_media_items($paragraph, $node->groups);
        }
      }
    }
  }
}

/**
 * Set groups on all media items referenced in a paragraph.
 *
 * @param $paragraph
 *   The paragraph.
 * @param $groups
 *   The groups to set.
 */
function MY_MODULE_update_media_items($paragraph, $groups) {
  foreach ($paragraph->getFieldDefinitions() as $definition) {
    if ($definition instanceof \Drupal\field\Entity\FieldConfig) {
      if ($definition->getSettings()['target_type'] == 'media') {
        $media = $paragraph->{$definition->getName()}->entity;
        if ($media) {
          $media->groups = $groups;
          $media->save();
        }
      }
      if ($definition->getSettings()['target_type'] == 'paragraph') {
        $paragraph = $paragraph->{$definition->getName()}->entity;
        if ($paragraph) {
          ph_content_update_media_items($paragraph, $groups);
        }
      }
    }
  }
}
user72672