You are here

public static function NameItem::validateUserPreferred in Name Field 8

Manage whether the name field should override a user's login name.

File

src/Plugin/Field/FieldType/NameItem.php, line 254

Class

NameItem
Plugin implementation of the 'name' field type.

Namespace

Drupal\name\Plugin\Field\FieldType

Code

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.
      Cache::invalidateTags([
        'user:' . $uid,
      ]);
    }
    \Drupal::logger('name')
      ->notice('Cache cleared for data tagged as %tag.', [
      '%tag' => 'user:{$uid}',
    ]);
  }
}