group_member_mgmt-8.x-1.0-beta7/src/Plugin/Field/FieldWidget/GroupRolesWidget.php

src/Plugin/Field/FieldWidget/GroupRolesWidget.php
<?php

namespace Drupal\group_member_mgmt\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsButtonsWidget;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Checkboxes for selecting group roles.
 *
 * @FieldWidget(
 *   id = "group_member_mgmt_group_roles",
 *   label = @Translation("Group roles, restricted by group management"),
 *   field_types = {
 *     "entity_reference",
 *   },
 *   multiple_values = TRUE
 * )
 */
class GroupRolesWidget extends OptionsButtonsWidget {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Group storage service.
   *
   * @var \Drupal\Core\Entity\ContentEntityStorageInterface
   */
  protected $groupStorage;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    /** @var static $plugin */
    $plugin = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $plugin->currentUser = $container->get('current_user');
    $plugin->groupStorage = $container->get('entity_type.manager')
      ->getStorage('group');
    return $plugin;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    /** @var \Drupal\group\Entity\GroupContentInterface $entity */
    $entity = $items->getEntity();
    if ($entity->getEntityTypeId() != 'group_content') {
      return $element;
    }

    // Group administrator is not restricted.
    $group = $entity->getGroup();
    if ($group->hasPermission('administer members', $this->currentUser)) {
      return $element;
    }

    // Disable options to which the user does not have access.
    foreach ($element['#options'] as $roleId => $label) {
      $perm = "update group-role:$roleId group_membership content";
      if (!$group->hasPermission($perm, $this->currentUser)) {
        $element[$roleId]['#disabled'] = TRUE;
      }
    }

    return $element;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc