mirror of
https://gitlab.unicamp.br/infimecc_drupal11_modules/site_tools.git
synced 2026-05-08 12:43:50 -03:00
Adiciona sub-módulo site_tools_group_helpers
Fornece um plugin EntityReferenceSelection que restringe campos de referência a grupos aos grupos dos quais o usuário atual é membro. Inclui troca automática para o widget options_select ao configurar o handler, e remoção do #required em target_bundles para campos que referenciam group, permitindo deixar o tipo de grupo em branco. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\site_tools_group_helpers\Plugin\EntityReferenceSelection;
|
||||
|
||||
use Drupal\Core\Entity\Attribute\EntityReferenceSelection;
|
||||
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\StringTranslation\TranslatableMarkup;
|
||||
use Drupal\group\Entity\GroupMembership;
|
||||
|
||||
/**
|
||||
* Restricts group selection to groups where the current user is a member.
|
||||
*
|
||||
* Use this handler on any entity_reference field that targets the 'group'
|
||||
* entity type when only the groups the current user belongs to should appear
|
||||
* as options. Users with no memberships will see an empty list.
|
||||
*/
|
||||
#[EntityReferenceSelection(
|
||||
id: 'site_tools_group_helpers',
|
||||
label: new TranslatableMarkup('Member groups (current user)'),
|
||||
entity_types: ['group'],
|
||||
group: 'site_tools_group_helpers',
|
||||
weight: 0,
|
||||
)]
|
||||
class MemberGroupSelection extends DefaultSelection {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
|
||||
$form = parent::buildConfigurationForm($form, $form_state);
|
||||
|
||||
// Allow leaving group types empty (= any type), matching the behaviour
|
||||
// of the default selection handler.
|
||||
if (isset($form['target_bundles'])) {
|
||||
$form['target_bundles']['#required'] = FALSE;
|
||||
}
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
|
||||
$query = parent::buildEntityQuery($match, $match_operator);
|
||||
|
||||
$memberships = GroupMembership::loadByUser($this->currentUser);
|
||||
|
||||
if (empty($memberships)) {
|
||||
// User has no memberships — return an empty result set.
|
||||
$query->condition('id', 0, '=');
|
||||
return $query;
|
||||
}
|
||||
|
||||
$gids = array_map(fn($m) => $m->getGroupId(), $memberships);
|
||||
$query->condition('id', $gids, 'IN');
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user