You are here

function tablefield_import_csv in TableField 6

Same name and namespace in other branches
  1. 7.3 tablefield.module \tablefield_import_csv()
  2. 7 tablefield.module \tablefield_import_csv()
  3. 7.2 tablefield.module \tablefield_import_csv()

Validation function to help import data from a CSV file

_state

Parameters

array $form:

1 string reference to 'tablefield_import_csv'
tablefield_process in ./tablefield.module
Process the tablefield

File

./tablefield.module, line 464
This module provides a set of fields that can be used to store tabular data with a node. The implementation uses a custom CCK widget.

Code

function tablefield_import_csv($form, &$form_state) {

  // Look for the field name by checking on the clicked button
  if (preg_match('/edit-rebuild-(.*)/', $form_state['clicked_button']['#id'], $id)) {

    // Extract the field and file name from the id of the clicked button
    $file_name = preg_replace('/\\-/', '_', $id[1]);
    preg_match('/_([0-9]+)$/', $file_name, $field_delta);

    // Extract the field delta from the field name
    $delta = $field_delta[1];
    $field_name = preg_replace('/_([0-9]+)$/', '', $file_name);

    // @todo fail out if no file
    // @todo validate file type
    $file = file_save_upload('tablefield_csv_' . $file_name);
    if (is_object($file)) {
      if (($handle = fopen($file->filepath, "r")) !== FALSE) {
        tablefield_delete_table_values($form_state['values'][$field_name][$delta]['tablefield']);

        // Populate CSV values
        $max_col_count = 0;
        $row_count = 0;
        while (($csv = fgetcsv($handle, 0, ",")) !== FALSE) {
          $col_count = count($csv);
          foreach ($csv as $col_id => $col) {
            $form_state['values'][$field_name][$delta]['tablefield']['cell_' . $row_count . '_' . $col_id] = $col;
          }
          $max_col_count = $col_count > $max_col_count ? $col_count : $max_col_count;
          $row_count++;
        }
        fclose($handle);
        $form_state['values'][$field_name][$delta]['tablefield']['count_cols'] = $max_col_count;
        $form_state['values'][$field_name][$delta]['tablefield']['count_rows'] = $row_count;
        $form_state['values']['tablefield_import'] = TRUE;
        drupal_set_message(t('Successfully imported @file. Please preview the result before saving.', array(
          '@file' => $file->filename,
        )));
      }
      else {
        drupal_set_message(t('There was a problem importing @file.', array(
          '@file' => $file->filename,
        )));
      }
    }

    // Remove the temporary file
    db_query("DELETE FROM {files} WHERE fid = %d", $file->fid);
    file_delete($file->filepath);
  }
}