Using Group Media with Media Entity Browser

Last updated on
8 February 2023

When using media inside the group it would be also nice to have the view provided by the Media Entity Browser contrib module (not to be confused with the core Media Library module) filtered by the media that is allowed for current user - the media that is a part of the current user's groups. To achieve this result you need to modify the entity browser view.
First you need to add 2 relations to the view:

  1. Media group content, make it as required.

    Views configuration

  2. ... and Group that depends on Media group content.

    Default argument

Then simply add contextual filter Group ID that uses the relation Group. As a default argument set the "Group Ids from current user" (available only with patch from https://www.drupal.org/project/group/issues/2999661) and save. From now on, users will see in the browser only the media they are supposed to see (the ones from the groups they've joined).
There is only one more tip needed, for the users that are allowed to view any media from any groups one needs to make a small tweak in a custom module, like this (for example):

/**
 * Implements hook_views_pre_build().
 *
 * @param \Drupal\views\ViewExecutable $view
 */
function YOUR_CUSTOM_MODULE_NAME_views_pre_build(ViewExecutable $view) {
  if ($view->storage->id() == 'media' && strpos($view->current_display, 'entity_browser_') !== FALSE) {
      // Check if the current user role has the right permission.
    if (\Drupal::currentUser()->hasPermission('bypass group access')) {
      // Make the relationship to group content not required, so the user can get access
      // to any media.
      if (!empty($view->relationship['group_content'])) {
        $view->relationship['group_content']->options['required'] = FALSE;
      }
    }
  }
}

The code above is assuming that the view name is "media" and the display starts with "entity_browser_".

Tags

Help improve this page

Page status: No known problems

You can: