Commit 218a48cd authored by George's avatar George
Browse files

Issue #2979037 - Exclude user loaded on user form from duplicate lookup.

parent 34dae3f5
Loading
Loading
Loading
Loading
+9 −5
Changes for fbl.module: 9 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -5,7 +5,6 @@
 * Module file for the field based login module.
 */

use Drupal\user\Entity\User;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
@@ -74,18 +73,23 @@ function fbl_user_register_validate($form, FormStateInterface &$form_state) {
      // Run query to check and make sure value is unique.
      $query = \Drupal::entityQuery('user');
      $query->condition($field_name . '.value', $user_input[0]['value']);
      // If on user form, let's load this user and exclude from lookup.
      if ($form_state->getValue('form_id') && $form_state->getValue('form_id') == 'user_form') {
        /** @var \Drupal\user\Entity\User $user */
        if ($user = user_load_by_name($form_state->getValue('name'))) {
          // Exclude current user.
          $query->condition('uid', $user->id(), '!=');
        }
      }
      // Get results.
      $results = $query->execute();
      // If any results, let's throw error.
      if (count($results)) {
        // Get current user.
        $current_user = User::load(\Drupal::currentUser()->id());
        if ((!isset($results[$current_user->id()]) || $current_user->id() === 0) && !$current_user->hasPermission('administer users')) {
        $form_state->setErrorByName($field_name, t('The entered value already exists. Please enter a different value.'));
      }
    }
  }
}
}

/**
 * Custom validate function to check custom user field records.