You are here

class OgComplex in Organic groups 8

Plugin implementation of the 'entity_reference autocomplete' widget.

Plugin annotation


@FieldWidget(
  id = "og_complex",
  label = @Translation("OG reference"),
  description = @Translation("An autocompletewidget for OG"),
  field_types = {
    "og_standard_reference",
    "og_membership_reference"
  }
)

Hierarchy

Expanded class hierarchy of OgComplex

File

src/Plugin/Field/FieldWidget/OgComplex.php, line 28

Namespace

Drupal\og\Plugin\Field\FieldWidget
View source
class OgComplex extends EntityReferenceAutocompleteWidget {

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

    // @todo Fix the definition in the UI level.
    $parent['target_id']['#selection_handler'] = 'og:default';
    $parent['target_id']['#selection_settings']['field_mode'] = 'default';
    return $parent;
  }

  /**
   * {@inheritdoc}
   */
  public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
    $parent_form = parent::form($items, $form, $form_state, $get_delta);
    $parent_form['other_groups'] = [];

    // Adding the other groups widget.
    if ($this
      ->isGroupAdmin()) {
      $parent_form['other_groups'] = $this
        ->otherGroupsWidget($items, $form_state);
    }
    return $parent_form;
  }

  /**
   * Special handling to create form elements for multiple values.
   *
   * Handles generic features for multiple fields:
   * - number of widgets
   * - AHAH-'add more' button
   * - table display and drag-n-drop value reordering.
   */
  protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
    $field_name = $this->fieldDefinition
      ->getName();
    $cardinality = $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getCardinality();
    $parents = $form['#parents'];
    $target_type = $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getSetting('target_type');

    /** @var \Drupal\og\MembershipManagerInterface $membership_manager */
    $membership_manager = \Drupal::service('og.membership_manager');
    $user_groups = $membership_manager
      ->getUserGroups(\Drupal::currentUser()
      ->id());
    $user_groups_target_type = isset($user_groups[$target_type]) ? $user_groups[$target_type] : [];
    $user_group_ids = array_map(function ($group) {
      return $group
        ->id();
    }, $user_groups_target_type);

    // Determine the number of widgets to display.
    switch ($cardinality) {
      case FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED:
        $field_state = static::getWidgetState($parents, $field_name, $form_state);
        $max = $field_state['items_count'];
        $is_multiple = TRUE;
        break;
      default:
        $max = $cardinality - 1;
        $is_multiple = $cardinality > 1;
        break;
    }
    $title = $this->fieldDefinition
      ->getLabel();
    $description = FieldFilteredMarkup::create(\Drupal::token()
      ->replace($this->fieldDefinition
      ->getDescription()));
    $elements = [];
    for ($delta = 0; $delta <= $max; $delta++) {

      // Add a new empty item if it doesn't exist yet at this delta.
      if (!isset($items[$delta])) {
        $items
          ->appendItem();
      }
      elseif (!in_array($items[$delta]
        ->get('target_id')
        ->getValue(), $user_group_ids)) {
        continue;
      }

      // For multiple fields, title and description are handled by the wrapping
      // table.
      if ($is_multiple) {
        $element = [
          '#title' => $this
            ->t('@title (value @number)', [
            '@title' => $title,
            '@number' => $delta + 1,
          ]),
          '#title_display' => 'invisible',
          '#description' => '',
        ];
      }
      else {
        $element = [
          '#title' => $title,
          '#title_display' => 'before',
          '#description' => $description,
        ];
      }
      $element = $this
        ->formSingleElement($items, $delta, $element, $form, $form_state);
      if ($element) {

        // Input field for the delta (drag-n-drop reordering).
        if ($is_multiple) {

          // We name the element '_weight' to avoid clashing with elements
          // defined by widget.
          $element['_weight'] = [
            '#type' => 'weight',
            '#title' => $this
              ->t('Weight for row @number', [
              '@number' => $delta + 1,
            ]),
            '#title_display' => 'invisible',
            // Note: this 'delta' is the FAPI #type 'weight' element's property.
            '#delta' => $max,
            '#default_value' => $items[$delta]->_weight ?: $delta,
            '#weight' => 100,
          ];
        }
        $elements[$delta] = $element;
      }
    }
    if ($elements) {
      $elements += [
        '#theme' => 'field_multiple_value_form',
        '#field_name' => $field_name,
        '#cardinality' => $cardinality,
        '#cardinality_multiple' => $this->fieldDefinition
          ->getFieldStorageDefinition()
          ->isMultiple(),
        '#required' => $this->fieldDefinition
          ->isRequired(),
        '#title' => $title,
        '#description' => $description,
        '#max_delta' => $max,
      ];

      // Add 'add more' button, if not working with a programmed form.
      if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && !$form_state
        ->isProgrammed()) {
        $id_prefix = implode('-', array_merge($parents, [
          $field_name,
        ]));
        $wrapper_id = Html::getUniqueId($id_prefix . '-add-more-wrapper');
        $elements['#prefix'] = '<div id="' . $wrapper_id . '">';
        $elements['#suffix'] = '</div>';
        $elements['add_more'] = [
          '#type' => 'submit',
          '#name' => strtr($id_prefix, '-', '_') . '_add_more',
          '#value' => $this
            ->t('Add another item'),
          '#attributes' => [
            'class' => [
              'field-add-more-submit',
            ],
          ],
          '#limit_validation_errors' => [
            array_merge($parents, [
              $field_name,
            ]),
          ],
          '#submit' => [
            [
              get_class($this),
              'addMoreSubmit',
            ],
          ],
          '#ajax' => [
            'callback' => [
              get_class($this),
              'addMoreAjax',
            ],
            'wrapper' => $wrapper_id,
            'effect' => 'fade',
          ],
        ];
      }
    }
    return $elements;
  }

  /**
   * Adding the other groups widget to the form.
   *
   * @param \Drupal\Core\Field\FieldItemListInterface $items
   *   The existing items to add to the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   A renderable element with the "other groups".
   */
  protected function otherGroupsWidget(FieldItemListInterface $items, FormStateInterface $form_state) {
    if ($this->fieldDefinition
      ->getTargetEntityTypeId() === 'user') {
      $description = $this
        ->t('As groups administrator, associate this user with groups you do <em>not</em> belong to.');
    }
    else {
      $description = $this
        ->t('As groups administrator, associate this content with groups you do <em>not</em> belong to.');
    }
    $field_wrapper = Html::getClass($this->fieldDefinition
      ->getName()) . '-add-another-group';
    $elements = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#title' => $this
        ->t('Other groups'),
      '#description' => $description,
      '#prefix' => '<div id="' . $field_wrapper . '">',
      '#suffix' => '</div>',
      '#cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
      '#cardinality_multiple' => TRUE,
      '#theme' => 'field_multiple_value_form',
      '#field_name' => $this->fieldDefinition
        ->getName(),
      '#max_delta' => 1,
    ];
    $elements['add_more'] = [
      '#type' => 'button',
      '#value' => $this
        ->t('Add another item'),
      '#name' => 'add_another_group',
      '#ajax' => [
        'callback' => [
          $this,
          'addMoreAjax',
        ],
        'wrapper' => $field_wrapper,
        'effect' => 'fade',
      ],
    ];
    $delta = 0;
    $target_type = $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getSetting('target_type');

    /** @var \Drupal\og\MembershipManagerInterface $membership_manager */
    $membership_manager = \Drupal::service('og.membership_manager');
    $user_groups = $membership_manager
      ->getUserGroups(\Drupal::currentUser()
      ->id());
    $user_groups_target_type = isset($user_groups[$target_type]) ? $user_groups[$target_type] : [];
    $user_group_ids = array_map(function ($group) {
      return $group
        ->id();
    }, $user_groups_target_type);
    $other_groups_weight_delta = round(count($user_groups) / 2);
    foreach ($items
      ->referencedEntities() as $group) {
      if (in_array($group
        ->id(), $user_group_ids)) {
        continue;
      }
      $elements[$delta] = $this
        ->otherGroupsSingle($delta, $group, $other_groups_weight_delta);
      $delta++;
    }
    if (!$form_state
      ->get('other_group_delta')) {
      $form_state
        ->set('other_group_delta', $delta);
    }

    // Get the trigger element and check if this the add another item button.
    $trigger_element = $form_state
      ->getTriggeringElement();
    if (!empty($trigger_element) && $trigger_element['#name'] == 'add_another_group') {

      // Increase the number of other groups.
      $delta = $form_state
        ->get('other_group_delta') + 1;
      $form_state
        ->set('other_group_delta', $delta);
    }

    // Add another auto complete field.
    for ($i = $delta; $i <= $form_state
      ->get('other_group_delta'); $i++) {

      // Also add one to the weight delta, just to make sure.
      $elements[$i] = $this
        ->otherGroupsSingle($i, NULL, $other_groups_weight_delta + 1);
    }
    return $elements;
  }

  /**
   * Generating other groups auto complete element.
   *
   * @param int $delta
   *   The delta of the new element. Need to be the last delta in order to be
   *   added in the end of the list.
   * @param \Drupal\Core\Entity\EntityInterface|null $entity
   *   The entity object.
   * @param int $weight_delta
   *   The delta of the item.
   *
   * @return array
   *   A single entity reference input.
   */
  public function otherGroupsSingle(int $delta, ?EntityInterface $entity = NULL, $weight_delta = 10) {
    $selection_settings = [
      'other_groups' => TRUE,
      'field_mode' => 'admin',
    ];
    if ($this
      ->getFieldSetting('handler_settings')) {
      $selection_settings += $this
        ->getFieldSetting('handler_settings');
    }
    return [
      'target_id' => [
        // @todo Allow this to be configurable with a widget setting.
        '#type' => 'entity_autocomplete',
        '#target_type' => $this->fieldDefinition
          ->getFieldStorageDefinition()
          ->getSetting('target_type'),
        '#selection_handler' => 'og:default',
        '#selection_settings' => $selection_settings,
        '#default_value' => $entity,
      ],
      '_weight' => [
        '#type' => 'weight',
        '#title_display' => 'invisible',
        '#delta' => $weight_delta,
        '#default_value' => $delta,
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {

    // Remove empty values. The form fields may be empty.
    $values = array_filter($values, function ($item) {
      return !empty($item['target_id']);
    });

    // Get the groups from the other groups widget.
    foreach ($form[$this->fieldDefinition
      ->getName()]['other_groups'] as $key => $value) {
      if (!is_int($key)) {
        continue;
      }

      // Matches the entity label and ID. E.g. 'Label (123)'. The entity ID will
      // be captured in it's own group, with the key 'id'.
      preg_match("|.+\\((?<id>[\\w.]+)\\)|", $value['target_id']['#value'], $matches);
      if (!empty($matches['id'])) {
        $values[] = [
          'target_id' => $matches['id'],
          '_weight' => $value['_weight']['#value'],
          '_original_delta' => $value['_weight']['#delta'],
        ];
      }
    }
    return $values;
  }

  /**
   * Determines if the current user has group admin permission.
   *
   * @return bool
   *   TRUE if the user is a group admin.
   */
  protected function isGroupAdmin() {

    // @todo Inject current user service as a dependency.
    return \Drupal::currentUser()
      ->hasPermission('administer organic groups');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AllowedTagsXssTrait::allowedTags public function Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss().
AllowedTagsXssTrait::displayAllowedTags public function Returns a human-readable list of allowed tags for display in help texts.
AllowedTagsXssTrait::fieldFilterXss public function Filters an HTML string to prevent XSS vulnerabilities.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityReferenceAutocompleteWidget::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsBase::defaultSettings
EntityReferenceAutocompleteWidget::errorElement public function Assigns a field-level validation error to the right widget sub-element. Overrides WidgetBase::errorElement
EntityReferenceAutocompleteWidget::getAutocreateBundle protected function Returns the name of the bundle which will be used for autocreated entities.
EntityReferenceAutocompleteWidget::getMatchOperatorOptions protected function Returns the options for the match operator.
EntityReferenceAutocompleteWidget::getSelectionHandlerSetting protected function Returns the value of a setting for the entity reference selection handler.
EntityReferenceAutocompleteWidget::settingsForm public function Returns a form to configure settings for the widget. Overrides WidgetBase::settingsForm
EntityReferenceAutocompleteWidget::settingsSummary public function Returns a short summary for the current widget settings. Overrides WidgetBase::settingsSummary
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
OgComplex::form public function Creates a form element for a field. Overrides WidgetBase::form
OgComplex::formElement public function Returns the form for a single field widget. Overrides EntityReferenceAutocompleteWidget::formElement
OgComplex::formMultipleElements protected function Special handling to create form elements for multiple values. Overrides WidgetBase::formMultipleElements
OgComplex::isGroupAdmin protected function Determines if the current user has group admin permission.
OgComplex::massageFormValues public function Massages the form values into the format expected for field values. Overrides EntityReferenceAutocompleteWidget::massageFormValues
OgComplex::otherGroupsSingle public function Generating other groups auto complete element.
OgComplex::otherGroupsWidget protected function Adding the other groups widget to the form.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
WidgetBase::$fieldDefinition protected property The field definition.
WidgetBase::$settings protected property The widget settings. Overrides PluginSettingsBase::$settings
WidgetBase::addMoreAjax public static function Ajax callback for the "Add another item" button.
WidgetBase::addMoreSubmit public static function Submission handler for the "Add another item" button.
WidgetBase::afterBuild public static function After-build handler for field elements in a form.
WidgetBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 5
WidgetBase::extractFormValues public function Extracts field values from submitted form values. Overrides WidgetBaseInterface::extractFormValues 2
WidgetBase::flagErrors public function Reports field-level validation errors against actual form elements. Overrides WidgetBaseInterface::flagErrors 2
WidgetBase::formSingleElement protected function Generates the form element for a single copy of the widget.
WidgetBase::getFieldSetting protected function Returns the value of a field setting.
WidgetBase::getFieldSettings protected function Returns the array of field settings.
WidgetBase::getFilteredDescription protected function Returns the filtered field description.
WidgetBase::getWidgetState public static function Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface::getWidgetState
WidgetBase::getWidgetStateParents protected static function Returns the location of processing information within $form_state.
WidgetBase::handlesMultipleValues protected function Returns whether the widget handles multiple values.
WidgetBase::isApplicable public static function Returns if the widget can be used for the provided field. Overrides WidgetInterface::isApplicable 4
WidgetBase::isDefaultValueWidget protected function Returns whether the widget used for default value form.
WidgetBase::setWidgetState public static function Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface::setWidgetState
WidgetBase::__construct public function Constructs a WidgetBase object. Overrides PluginBase::__construct 5