You are here

function social_profile_fields_user_format_name_alter in Open Social 8.3

Same name and namespace in other branches
  1. 8.2 modules/social_features/social_profile/modules/social_profile_fields/social_profile_fields.module \social_profile_fields_user_format_name_alter()
  2. 8.4 modules/social_features/social_profile/modules/social_profile_fields/social_profile_fields.module \social_profile_fields_user_format_name_alter()

Implements hook_user_format_name_alter().

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

File

modules/social_features/social_profile/modules/social_profile_fields/social_profile_fields.module, line 49
The social profile fields module file.

Code

function social_profile_fields_user_format_name_alter(&$name, $account) {

  // Can we use the fields?
  $use_first_name = _social_profile_fields_get_setting('profile_profile_field_profile_first_name');
  $use_last_name = _social_profile_fields_get_setting('profile_profile_field_profile_last_name');
  $use_nick_name = _social_profile_fields_get_setting('profile_profile_field_profile_nick_name');
  $accountname = '';

  // Let's get the Nickname, First name Last name.

  /** @var \Drupal\profile\ProfileStorageInterface $storage */
  $storage = \Drupal::entityTypeManager()
    ->getStorage('profile');
  if (!empty($storage)) {

    // Returns false.
    if ($user_profile = $storage
      ->loadByUser($account, 'profile', TRUE)) {

      // First try to set it from the nick_name.
      $accountname = $use_nick_name ? $user_profile
        ->get('field_profile_nick_name')->value : '';

      // If that fails, fallback to old behaviour with first/last name.
      if ($accountname == '') {
        $first_name = $use_first_name ? $user_profile
          ->get('field_profile_first_name')->value : '';
        $last_name = $use_last_name ? $user_profile
          ->get('field_profile_last_name')->value : '';
        $accountname = $first_name . ' ' . $last_name;
        $accountname = trim($accountname);
      }
    }
  }

  // If all fails, we now fall back to the drupal username.
  $name = $accountname !== '' ? $accountname : $account
    ->getUsername();
}