You are here

private static function Tablefield::importCsv in TableField 8.2

Helper function to import data from a CSV file.

Parameters

string $form_field_name: Field name.

Return value

mixed Table array or FALSE.

1 call to Tablefield::importCsv()
Tablefield::submitCallbackRebuild in src/Element/Tablefield.php
Submit handler.

File

src/Element/Tablefield.php, line 314

Class

Tablefield
Provides a form element for tabular data.

Namespace

Drupal\tablefield\Element

Code

private static function importCsv($form_field_name) {
  $files = \Drupal::request()->files
    ->get('files');
  $file_upload = $files[$form_field_name];
  if (empty($file_upload)) {
    \Drupal::messenger()
      ->addError(t('Select a CSV file to upload.'));
    return FALSE;
  }
  if ($file_upload
    ->getClientOriginalExtension() != 'csv') {
    \Drupal::messenger()
      ->addError(t('Only files with the following extensions are allowed: %files-allowed.', [
      '%files-allowed' => 'csv',
    ]));
    return FALSE;
  }
  if (!empty($file_upload) && ($handle = fopen($file_upload
    ->getPathname(), 'r'))) {

    // Checking the encoding of the CSV file to be UTF-8.
    $encoding = 'UTF-8';
    if (function_exists('mb_detect_encoding')) {
      $file_contents = file_get_contents($file_upload
        ->getPathname());
      $encodings = [
        'UTF-8',
        'ISO-8859-1',
        'WINDOWS-1251',
      ];
      \Drupal::moduleHandler()
        ->alter('tablefield_encodings', $encodings);
      $encodings_list = implode(',', $encodings);
      $encoding = mb_detect_encoding($file_contents, $encodings_list);
    }

    // Populate CSV values.
    $tablefield = [];
    $max_cols = 0;
    $rows = 0;
    $separator = \Drupal::config('tablefield.settings')
      ->get('csv_separator');
    while (($csv = fgetcsv($handle, 0, $separator)) != FALSE) {
      foreach ($csv as $value) {
        $tablefield['table'][$rows][] = self::convertEncoding($value, $encoding);
      }
      $cols = count($csv);
      if ($cols > $max_cols) {
        $max_cols = $cols;
      }
      $rows++;
    }
    fclose($handle);
    $tablefield['rebuild']['cols'] = $max_cols;
    $tablefield['rebuild']['rows'] = $rows;
    \Drupal::messenger()
      ->addMessage(t('Successfully imported @file', [
      '@file' => $file_upload
        ->getClientOriginalName(),
    ]));
    return $tablefield;
  }
  \Drupal::messenger()
    ->addError(t('There was a problem importing @file.', [
    '@file' => $file_upload
      ->getClientOriginalName(),
  ]));
  return FALSE;
}