NameItem.php 8.77 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\name\Plugin\Field\FieldType;

5
use Drupal\Core\Cache\Cache;
6 7
use Drupal\Core\Link;
use Drupal\Core\Url;
8
use Drupal\Core\Field\FieldDefinitionInterface;
webflo's avatar
webflo committed
9
use Drupal\Core\Field\FieldItemBase;
webflo's avatar
webflo committed
10
use Drupal\Core\Field\FieldStorageDefinitionInterface;
webflo's avatar
webflo committed
11
use Drupal\Core\Form\FormStateInterface;
12
use Drupal\Core\Security\TrustedCallbackInterface;
13
use Drupal\Core\TypedData\DataDefinition;
14 15 16
use Drupal\name\Traits\NameFieldSettingsTrait;
use Drupal\name\Traits\NameFormDisplaySettingsTrait;
use Drupal\name\Traits\NameFormSettingsHelperTrait;
17
use Drupal\name\Traits\NameAdditionalPreferredTrait;
18 19 20 21

/**
 * Plugin implementation of the 'name' field type.
 *
22 23
 * Majority of the settings handling is delegated to the traits so that these
 * can be reused.
24
 *
25 26 27 28 29 30 31 32
 * @FieldType(
 *   id = "name",
 *   label = @Translation("Name"),
 *   description = @Translation("Stores real name."),
 *   default_widget = "name_default",
 *   default_formatter = "name_default"
 * )
 */
33
class NameItem extends FieldItemBase implements TrustedCallbackInterface {
34

35 36 37
  use NameFieldSettingsTrait;
  use NameFormDisplaySettingsTrait;
  use NameFormSettingsHelperTrait;
38
  use NameAdditionalPreferredTrait;
39

40
  /**
41
   * Definition of name field components.
42 43 44
   *
   * @var array
   */
45
  protected static $components = [
46 47 48 49 50
    'title',
    'given',
    'middle',
    'family',
    'generational',
51 52
    'credentials',
  ];
53

54 55 56 57 58 59 60
  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return ['fieldSettingsFormPreRender'];
  }

webflo's avatar
webflo committed
61
  /**
62
   * {@inheritdoc}
webflo's avatar
webflo committed
63
   */
64 65 66 67 68 69 70 71 72 73 74 75 76 77
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $columns = [];
    foreach (static::$components as $key) {
      $columns[$key] = [
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
      ];
    }
    return [
      'columns' => $columns,
      'indexes' => [
        'given' => ['given'],
        'family' => ['family'],
78 79
      ],
    ];
webflo's avatar
webflo committed
80 81 82 83 84
  }

  /**
   * {@inheritdoc}
   */
webflo's avatar
webflo committed
85
  public static function defaultFieldSettings() {
86 87
    $settings = self::getDefaultNameFieldSettings();
    $settings += self::getDefaultNameFormDisplaySettings();
88
    $settings += self::getDefaultAdditionalPreferredSettings();
89
    $settings['override_format'] = 'default';
webflo's avatar
webflo committed
90
    return $settings + parent::defaultFieldSettings();
webflo's avatar
webflo committed
91 92
  }

93
  /**
94
   * {@inheritdoc}
95
   */
webflo's avatar
webflo committed
96
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
97
    $properties = [];
webflo's avatar
webflo committed
98 99
    $properties['title'] = DataDefinition::create('string')
      ->setLabel(t('Title'));
100

webflo's avatar
webflo committed
101 102
    $properties['given'] = DataDefinition::create('string')
      ->setLabel(t('Given'));
103

webflo's avatar
webflo committed
104 105
    $properties['middle'] = DataDefinition::create('string')
      ->setLabel(t('Middle name(s)'));
106

webflo's avatar
webflo committed
107 108
    $properties['family'] = DataDefinition::create('string')
      ->setLabel(t('Family'));
109

webflo's avatar
webflo committed
110 111
    $properties['generational'] = DataDefinition::create('string')
      ->setLabel(t('Generational'));
112

webflo's avatar
webflo committed
113 114
    $properties['credentials'] = DataDefinition::create('string')
      ->setLabel(t('Credentials'));
webflo's avatar
webflo committed
115

webflo's avatar
webflo committed
116
    return $properties;
117 118
  }

119
  /**
120
   * {@inheritdoc}
121 122 123 124 125 126
   */
  public static function mainPropertyName() {
    // There is no main property for this field item.
    return NULL;
  }

127
  /**
128
   * {@inheritdoc}
129 130 131
   */
  public function isEmpty() {
    foreach ($this->properties as $property) {
webflo's avatar
webflo committed
132 133
      $definition = $property->getDataDefinition();
      if (!$definition->isComputed() && $property->getValue() !== NULL) {
134 135 136 137 138 139 140 141 142
        return FALSE;
      }
    }
    if (isset($this->values)) {
      foreach ($this->values as $name => $value) {
        // Title & generational have no meaning by themselves.
        if ($name == 'title' || $name == 'generational') {
          continue;
        }
143
        if (isset($value) && strlen($value) && !isset($this->properties[$name])) {
144 145 146 147 148 149 150
          return FALSE;
        }
      }
    }
    return TRUE;
  }

151 152 153 154 155 156 157 158 159 160 161 162
  /**
   * Returns active components only.
   *
   * @return array
   *   Array of filtered name component values.
   */
  public function filteredArray() {
    $values = [];
    $field = $this->getFieldDefinition();
    $settings = $field->getSettings();
    $active_components = array_filter($settings['components']);
    foreach ($this->getProperties() as $name => $property) {
163
      if (isset($active_components[$name]) && $active_components[$name]) {
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
        $values[$name] = $property->getValue();
      }
    }
    return $values;
  }

  /**
   * Get a list of active components.
   *
   * @return array
   *   Keyed array of active component labels.
   */
  public function activeComponents() {
    $settings = $this->getFieldDefinition()->getSettings();
    $components = [];
    foreach (_name_translations() as $key => $label) {
      if (!empty($settings['components'][$key])) {
        $components[$key] = empty($settings['labels'][$key]) ? $label : $settings['labels'][$key];
      }
    }

    return $components;
  }

188
  /**
189
   * {@inheritdoc}
190
   */
webflo's avatar
webflo committed
191
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
webflo's avatar
webflo committed
192
    $settings = $this->getSettings();
193 194
    $element = $this->getDefaultNameFieldSettingsForm($settings, $form, $form_state);
    $element += $this->getDefaultNameFormDisplaySettingsForm($settings, $form, $form_state);
195 196 197 198 199 200
    foreach ($this->getNameAdditionalPreferredSettingsForm($form, $form_state) as $key => $value) {
      $element[$key] = $value;
      $element[$key]['#table_group'] = 'none';
      $element[$key]['#weight'] = 50;
    }

201
    $element['#pre_render'][] = [$this, 'fieldSettingsFormPreRender'];
202

203
    // Add the overwrite user name option.
webflo's avatar
webflo committed
204
    if ($this->getFieldDefinition()->getTargetEntityTypeId() == 'user') {
205

webflo's avatar
webflo committed
206 207
      $preferred_field = \Drupal::config('name.settings')
        ->get('user_preferred');
208

209
      $element['name_user_preferred'] = [
210
        '#type' => 'checkbox',
211
        '#title' => $this->t("Use this field to override the user's login name?"),
212 213 214
        '#description' => $this->t('You may need to clear the @cache_link before this change is seen everywhere.', [
          '@cache_link' => Link::fromTextAndUrl('Performance cache', Url::fromRoute('system.performance_settings'))->toString(),
        ]),
215
        '#default_value' => (($preferred_field == $this->getFieldDefinition()->getName()) ? 1 : 0),
216 217
        '#table_group' => 'above',
        '#weight' => -100,
218
      ];
219 220

      // Store the machine name of the Name field.
221
      $element['name_user_preferred_fieldname'] = [
222 223
        '#type' => 'hidden',
        '#default_value' => $this->getFieldDefinition()->getName(),
224 225
        '#table_group' => 'above',
        '#weight' => -99,
226
      ];
227

228
      $element['override_format'] = [
229
        '#type' => 'select',
230
        '#title' => $this->t('User name override format to use'),
webflo's avatar
webflo committed
231
        '#default_value' => $this->getSetting('override_format'),
232
        '#options' => name_get_custom_format_options(),
233 234
        '#table_group' => 'above',
        '#weight' => -98,
235
      ];
236 237

      $element['#element_validate'] = [[get_class($this), 'validateUserPreferred']];
238 239 240
    }
    else {
      // We may extend this feature to Profile2 latter.
241
      $element['override_format'] = [
242
        '#type' => 'value',
webflo's avatar
webflo committed
243
        '#value' => $this->getSetting('override_format'),
244
        '#table_group' => 'none',
245
      ];
246 247
    }

webflo's avatar
webflo committed
248
    return $element;
249
  }
250

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  /**
   * Manage whether the name field should override a user's login name.
   */
  public static function validateUserPreferred(&$element, FormStateInterface $form_state, &$complete_form) {

    $value = NULL;
    $config = \Drupal::configFactory()->getEditable('name.settings');

    // Ensure the name field value should override a user's login name.
    if ((!empty($element['name_user_preferred'])) && ($element['name_user_preferred']['#value'] == 1)) {
      // Retrieve the name field's machine name.
      $value = $element['name_user_preferred_fieldname']['#default_value'];
    }

    // Ensure that the login-name-override configuration has changed.
    if ($config->get('user_preferred') != $value) {

      // Update the configuration with the new value.
      $config->set('user_preferred', $value)->save();

      // Retrieve the ID of all existing users.
      $query = \Drupal::entityQuery('user');
      $uids = $query->execute();

      foreach ($uids as $uid) {
        // Invalidate the cache for each user so that
        // the appropriate login name will be displayed.
278
        Cache::invalidateTags(['user:' . $uid]);
279 280 281 282
      }

      \Drupal::logger('name')->notice('Cache cleared for data tagged as %tag.', ['%tag' => 'user:{$uid}']);
    }
283
  }
284

285 286 287 288
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
289
    // Single reused generation of 100 random names.
290
    $names = &drupal_static(__FUNCTION__, []);
291
    if (empty($names)) {
292
      $names = \Drupal::service('name.generator')->generateSampleNames(100, $field_definition);
293 294
    }
    return $names[array_rand($names)];
295 296
  }

297
}