Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
2
Indexable
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Drupal\Core\Database\Database;

class CustomCsvUserCheckerForm extends FormBase {

  // ...

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $csv_file_fid = $form_state->getValue('csv_upload');
    if (!empty($csv_file_fid)) {
      $file = File::load($csv_file_fid[0]);
      if ($file instanceof FileInterface) {
        $file_path = $file->getFileUri();

        $csv_data = array_map('str_getcsv', file($file_path));

        // Initialize an empty array to store results
        $results = [];

        // Loop through CSV data and process user accounts
        foreach ($csv_data as $csv_row) {
          $email = $csv_row[0];
          
          // Load user by email using a database query
          $query = Database::getConnection()->select('users_field_data', 'u');
          $query->fields('u', ['uid', 'name']);
          $query->condition('u.mail', $email);
          $user = $query->execute()->fetchAssoc();

          if (!empty($user)) {
            // User found
            $username = $user['name'];
            $status = $this->t('Account Present');
          } else {
            // User not found
            $username = '';
            $status = $this->t('Account Not Present');
          }

          $results[] = [
            'email' => $email,
            'username' => $username,
            'status' => $status,
          ];
        }

        // Now you can use the $results array to display or process the data
      }
    }
  }

  // ...
}