Skip to content
This repository has been archived by the owner on Aug 18, 2024. It is now read-only.

Pass membership data in form_state for roles add/remove form. #750

Closed
39 changes: 39 additions & 0 deletions og.api.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\og\OgAccess;

/**
Expand Down Expand Up @@ -54,6 +55,44 @@ function hook_og_user_access_alter(array &$permissions, CacheableMetadata $cache
$cacheable_metadata->addCacheableDependency($config);
}

/**
* Implements hook_form_FORM_ID_alter().
*/
function hook_form_og_membership_remove_multiple_roles_action_form_alter(array &$form, FormStateInterface $form_state, string $form_id) {
// Get access to current group and selected memberships when we're on the role
// remove form.
/** @var \Drupal\og\OgMembershipInterface[] $memberships */
$memberships = $form_state->getTemporaryValue('selected_memberships');

$form['roles']['#options'] = array_filter($form['roles']['#options'], function ($key) use (&$form, $memberships) {
// Code to filter out options based on data from memberships and group.
$membership = reset($memberships);
$group = $membership->getGroup();
if ($group->id() != 9999) {
unset($form['roles']['#options'][$key]);
}
}, ARRAY_FILTER_USE_KEY);
}

/**
* Implements hook_form_FORM_ID_alter().
*/
function hook_form_og_membership_add_multiple_roles_action_form_alter(array &$form, FormStateInterface $form_state, string $form_id) {
// Get access to current group and selected memberships when we're on the role
// add form.
/** @var \Drupal\og\OgMembershipInterface[] $memberships */
$memberships = $form_state->getTemporaryValue('selected_memberships');

$form['roles']['#options'] = array_filter($form['roles']['#options'], function ($key) use (&$form, $memberships) {
// Code to filter out options based on data from memberships and group.
$membership = reset($memberships);
$group = $membership->getGroup();
if ($group->id() != 9999) {
unset($form['roles']['#options'][$key]);
}
}, ARRAY_FILTER_USE_KEY);
}

/**
* @} End of "addtogroup hooks".
*/
9 changes: 9 additions & 0 deletions src/Form/OgChangeMultipleRolesFormBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,15 @@ public function buildForm(array $form, FormStateInterface $form_state) {
'#value' => $this->t('Submit'),
];

// Set selected memberships in the form state. This can be used to alter
// the roles add/remove form.
$memberships = $this->getMemberships();
if (empty($memberships)) {
return $form;
}

$form_state->setTemporaryValue('selected_memberships', $memberships);

return $form;
}

Expand Down