I'm using the Drupal Group module and I've added content to a Drupal group I've created. I've also added users to this Group.
Works well: Drupal users have to login to see this content in that group.
Now I'm looking at User Experience (UX) improvements: If a non-logged in user visits a URL for a node that belongs to a group, then I'd like to redirect them to the login page and then redirect them back to that page.
I know how to do the 2 redirects ( How to redirect a user after login in Drupal the proper way - I got this working for something else ). But I don't know how to get the group(s) that a node belongs to. Is there a standard call? on the Node object or via another object I can get hold of?
So far I found this: Find out to which group the entity belongs to by route. It's a code fragment for a class. I added in the constructor with params that correspond to the said services and member variables.
It runs, but doesn't work: calling $group = \Drupal::service('mysite_custom_module.current_group')->getGroupFromRoute(); returns $group as null
My code I've written based on: Find out to which group the entity belongs to by route
(Note - by me posting this code example here below doesn't mean I'm fixated on getting this particular approach to work. I would surely be very happy with any solution that answers my main question: "How to get the Drupal Group that the node belongs to / redirect anonymous to login page if they land on node belonging to group" )
web/modules/custom/mysite_custom_module/mysite_custom_module.services.yml
services: mysite_custom_module.current_group: class: Drupal\mysite_custom_module\CurrentGroup arguments: ['@current_route_match', '@entity_type.manager'] web/modules/custom/mysite_custom_module/mysite_custom_module.module
/** * https://www.thesavvyfew.com/insights/how-redirect-user-after-login-drupal-proper-way * * Implements hook_form_FORM_ID_alter(). */ function mysite_custom_module_module_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) { $form['#submit'][] = 'mysite_custom_module_module_user_login_form_submit'; } /** * Custom submit handler for the login form. */ function mysite_custom_module_module_user_login_form_submit($form, FormStateInterface $form_state) { $originalUrlAsString = \Drupal::request()->get('return'); $urlAsObject = Url::fromUserInput($originalUrlAsString); $form_state->setRedirectUrl($urlAsObject); } function mysite_custom_module_module_preprocess_page(&$variables) { $group = \Drupal::service('mysite_custom_module_module.current_group')->getGroupFromRoute(); if ( $group ) { if (!( \Drupal::currentUser()->isAuthenticated() ) ) { $originalUrl = \Drupal::service('path.current')->getPath(); $loginWithOriginalUrl = "/user/login?return=".$originalUrl; //$response = new RedirectResponse(Url::fromUserInput($loginWithOriginalUrl)->toString()); $response = new RedirectResponse($loginWithOriginalUrl); $response->send(); } } } web/modules/custom/mysite_custom_modue/src/CurrentGroup.php:
<?php namespace Drupal\mysite_module; // https://www.drupal.org/docs/8/modules/group-media/find-out-to-which-group-the-entity-belongs-to-by-route class CurrentGroup { private $routeMatch; private $entityTypeManager; // see mysite_module/mysite_module.services.yml public function __construct( $current_route_match, $entity_type_manager ) { $this->routeMatch = $current_route_match; $this->entityTypeManager = $entity_type_manager; } /** * @param \Drupal\Core\Entity\EntityInterface $entity * * @return bool|\Drupal\group\Entity\GroupInterface * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException */ public function getGroupByEntity(EntityInterface $entity) { $group = FALSE; if ($entity instanceof GroupInterface) { return $entity; } $entity_type = $entity->getEntityTypeId(); $group_content_type = 'membership_group_type-group_' . $entity_type . '-' . $entity->bundle(); // Load all the group content for this entity. /** @var \Drupal\group\Entity\GroupContent $group_content */ $group_content = $this->entityTypeManager->getStorage('group_content') ->loadByProperties([ 'type' => $group_content_type, 'entity_id' => $entity->id(), ]); // Assuming that the content can be related only to 1 group. $group_content = reset($group_content); if (!empty($group_content)) { $group = $group_content->getGroup(); } return $group; } /** * Get the group from the current route match. * * @return bool|\Drupal\group\Entity\GroupInterface * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException */ public function getGroupFromRoute() { $entity = FALSE; $parameters = $this->routeMatch->getParameters()->all(); if (!empty($parameters['group']) && is_numeric($parameters['group'])) { $group = Group::load($parameters['group']); return $group; } if (!empty($parameters)) { foreach ($parameters as $parameter) { if ($parameter instanceof EntityInterface) { $entity = $parameter; break; } } } if ($entity) { return $this->getGroupByEntity($entity); } return FALSE; } }