Untitled
unknown
plain_text
2 years ago
2.2 kB
11
Indexable
<?php
namespace Drupal\custom_csv_user_checker\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;
use Drupal\file\Entity\File;
use Drupal\Core\File\FileSystemInterface;
class CustomCsvUserCheckerForm extends FormBase {
public function getFormId() {
return 'custom_csv_user_checker_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['csv_upload'] = [
'#type' => 'file',
'#title' => $this->t('Upload CSV File'),
'#description' => $this->t('Upload a CSV file containing email addresses.'),
'#upload_validators' => [
'file_validate_extensions' => ['csv'],
],
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Process CSV'),
];
return $form;
}
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 File) {
$file_path = $file->getFileUri();
$csv_data = array_map('str_getcsv', file($file_path));
$header = [$this->t('Email'), $this->t('Username'), $this->t('Account Status')];
$rows = [];
foreach ($csv_data as $csv_row) {
$email = $csv_row[0];
$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');
}
$rows[] = [$email, $username, $status];
}
$form_state->set('results', [
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
]);
}
}
}
}
Editor is loading...