diff --git a/src/Plugin/Field/FieldWidget/DynamicEntityReferenceOptionsTrait.php b/src/Plugin/Field/FieldWidget/DynamicEntityReferenceOptionsTrait.php index 1bf3c54..7c366f2 100644 --- a/src/Plugin/Field/FieldWidget/DynamicEntityReferenceOptionsTrait.php +++ b/src/Plugin/Field/FieldWidget/DynamicEntityReferenceOptionsTrait.php @@ -64,23 +64,69 @@ trait DynamicEntityReferenceOptionsTrait { /** * {@inheritdoc} + * + * @todo Remove this when https://www.drupal.org/node/2426781 is fixed. */ protected function getOptions(FieldableEntityInterface $entity) { - $options = parent::getOptions($entity); + if (!isset($this->options)) { + // Limit the settable options for the current user account. + $options = $this->fieldDefinition + ->getFieldStorageDefinition() + ->getOptionsProvider($this->column, $entity) + ->getSettableOptions(\Drupal::currentUser()); + + // Add an empty option if the widget needs one. + if ($empty_option = $this->getEmptyOption()) { + switch ($this->getPluginId()) { + case 'options_buttons': + $label = t('N/A'); + break; + + case 'options_select': + $label = ($empty_option == static::OPTIONS_EMPTY_NONE ? t('- None -') : t('- Select a value -')); + break; + + default: + $label = $this->getEmptyLabel(); + } - // Add an empty option if the widget needs one. - if ($empty_option = $this->getEmptyOption()) { - $plugin_id = $this->getPluginId(); - if (strpos($plugin_id, 'buttons') !== FALSE) { - $label = t('N/A'); + $options = array('_none' => $label) + $options; } - else { - $label = ($empty_option == static::OPTIONS_EMPTY_NONE ? t('- None -') : t('- Select a value -')); + + $module_handler = \Drupal::moduleHandler(); + $context = array( + 'fieldDefinition' => $this->fieldDefinition, + 'entity' => $entity, + ); + $module_handler->alter('options_list', $options, $context); + + array_walk_recursive($options, array($this, 'sanitizeLabel')); + + // Options might be nested ("optgroups"). If the widget does not support + // nested options, flatten the list. + if (!$this->supportsGroups()) { + $options = OptGroup::flattenOptions($options); } - $options = array('_none' => $label) + $options; + $this->options = $options; } - return $options; + return $this->options; } + /** + * Returns the empty option label . + * + * @return string|null + * Either string, or NULL. + */ + protected function getEmptyLabel() { + $plugin_id = $this->getPluginId(); + if (strpos($plugin_id, 'buttons') !== FALSE) { + $label = t('N/A'); + } + else { + $label = ($this->getEmptyOption() == static::OPTIONS_EMPTY_NONE ? t('- None -') : t('- Select a value -')); + } + return $label; + } }