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
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
- class \Drupal\Core\Field\PluginSettingsBase implements DependentPluginInterface, PluginSettingsInterface
- class \Drupal\Core\Field\WidgetBase implements WidgetInterface, ContainerFactoryPluginInterface uses AllowedTagsXssTrait
- class \Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
- class \Drupal\og\Plugin\Field\FieldWidget\OgComplex
- class \Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
- class \Drupal\Core\Field\WidgetBase implements WidgetInterface, ContainerFactoryPluginInterface uses AllowedTagsXssTrait
- class \Drupal\Core\Field\PluginSettingsBase implements DependentPluginInterface, PluginSettingsInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
Expanded class hierarchy of OgComplex
File
- src/
Plugin/ Field/ FieldWidget/ OgComplex.php, line 28
Namespace
Drupal\og\Plugin\Field\FieldWidgetView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
AllowedTagsXssTrait:: |
public | function | Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss(). | |
AllowedTagsXssTrait:: |
public | function | Returns a human-readable list of allowed tags for display in help texts. | |
AllowedTagsXssTrait:: |
public | function | Filters an HTML string to prevent XSS vulnerabilities. | |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntityReferenceAutocompleteWidget:: |
public static | function |
Defines the default settings for this plugin. Overrides PluginSettingsBase:: |
|
EntityReferenceAutocompleteWidget:: |
public | function |
Assigns a field-level validation error to the right widget sub-element. Overrides WidgetBase:: |
|
EntityReferenceAutocompleteWidget:: |
protected | function | Returns the name of the bundle which will be used for autocreated entities. | |
EntityReferenceAutocompleteWidget:: |
protected | function | Returns the options for the match operator. | |
EntityReferenceAutocompleteWidget:: |
protected | function | Returns the value of a setting for the entity reference selection handler. | |
EntityReferenceAutocompleteWidget:: |
public | function |
Returns a form to configure settings for the widget. Overrides WidgetBase:: |
|
EntityReferenceAutocompleteWidget:: |
public | function |
Returns a short summary for the current widget settings. Overrides WidgetBase:: |
|
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
OgComplex:: |
public | function |
Creates a form element for a field. Overrides WidgetBase:: |
|
OgComplex:: |
public | function |
Returns the form for a single field widget. Overrides EntityReferenceAutocompleteWidget:: |
|
OgComplex:: |
protected | function |
Special handling to create form elements for multiple values. Overrides WidgetBase:: |
|
OgComplex:: |
protected | function | Determines if the current user has group admin permission. | |
OgComplex:: |
public | function |
Massages the form values into the format expected for field values. Overrides EntityReferenceAutocompleteWidget:: |
|
OgComplex:: |
public | function | Generating other groups auto complete element. | |
OgComplex:: |
protected | function | Adding the other groups widget to the form. | |
PluginBase:: |
protected | property | Configuration information passed into the plugin. | 1 |
PluginBase:: |
protected | property | The plugin implementation definition. | 1 |
PluginBase:: |
protected | property | The plugin_id. | |
PluginBase:: |
constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
PluginBase:: |
public | function |
Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
3 |
PluginBase:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
PluginBase:: |
public | function | Determines if the plugin is configurable. | |
PluginSettingsBase:: |
protected | property | Whether default settings have been merged into the current $settings. | |
PluginSettingsBase:: |
protected | property | The plugin settings injected by third party modules. | |
PluginSettingsBase:: |
public | function |
Calculates dependencies for the configured plugin. Overrides DependentPluginInterface:: |
6 |
PluginSettingsBase:: |
public | function |
Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
protected | function | Merges default settings values into $settings. | |
PluginSettingsBase:: |
public | function |
Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface:: |
3 |
PluginSettingsBase:: |
public | function |
Sets the value of a setting for the plugin. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Sets the settings for the plugin. Overrides PluginSettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
PluginSettingsBase:: |
public | function |
Unsets a third-party setting. Overrides ThirdPartySettingsInterface:: |
|
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
WidgetBase:: |
protected | property | The field definition. | |
WidgetBase:: |
protected | property |
The widget settings. Overrides PluginSettingsBase:: |
|
WidgetBase:: |
public static | function | Ajax callback for the "Add another item" button. | |
WidgetBase:: |
public static | function | Submission handler for the "Add another item" button. | |
WidgetBase:: |
public static | function | After-build handler for field elements in a form. | |
WidgetBase:: |
public static | function |
Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface:: |
5 |
WidgetBase:: |
public | function |
Extracts field values from submitted form values. Overrides WidgetBaseInterface:: |
2 |
WidgetBase:: |
public | function |
Reports field-level validation errors against actual form elements. Overrides WidgetBaseInterface:: |
2 |
WidgetBase:: |
protected | function | Generates the form element for a single copy of the widget. | |
WidgetBase:: |
protected | function | Returns the value of a field setting. | |
WidgetBase:: |
protected | function | Returns the array of field settings. | |
WidgetBase:: |
protected | function | Returns the filtered field description. | |
WidgetBase:: |
public static | function |
Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface:: |
|
WidgetBase:: |
protected static | function | Returns the location of processing information within $form_state. | |
WidgetBase:: |
protected | function | Returns whether the widget handles multiple values. | |
WidgetBase:: |
public static | function |
Returns if the widget can be used for the provided field. Overrides WidgetInterface:: |
4 |
WidgetBase:: |
protected | function | Returns whether the widget used for default value form. | |
WidgetBase:: |
public static | function |
Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface:: |
|
WidgetBase:: |
public | function |
Constructs a WidgetBase object. Overrides PluginBase:: |
5 |