You are here

function tablefield_import_csv in TableField 7

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

Helper function to import data from a CSV file

_state

Parameters

array $form:

1 call to tablefield_import_csv()
tablefield_field_widget_form in ./tablefield.module
Implements hook_widget_form().

File

./tablefield.module, line 461
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('/tablefield-import-button-(.*)$/', $form_state['clicked_button']['#name'], $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('/' . $field_delta[0] . '/', '', $file_name);
    $language = isset($form['language']['#value']) ? $form['language']['#value'] : 'und';
    $file = file_save_upload($field_name, array(
      'file_validate_extensions' => array(
        'csv',
      ),
    ));
    if (is_object($file)) {
      if (($handle = fopen($file->uri, "r")) !== FALSE) {
        tablefield_delete_table_values($form_state['values'][$field_name][$language][$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['input'][$field_name][$language][$delta]['tablefield']['cell_' . $row_count . '_' . $col_id] = $form_state['values'][$field_name][$language][$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['input'][$field_name][$language][$delta]['tablefield']['rebuild']['count_cols'] = $form_state['values'][$field_name][$language][$delta]['tablefield']['rebuild']['count_cols'] = $max_col_count;
        $form_state['input'][$field_name][$language][$delta]['tablefield']['rebuild']['count_rows'] = $form_state['values'][$field_name][$language][$delta]['tablefield']['rebuild']['count_rows'] = $row_count;
        drupal_set_message(t('Successfully imported @file', array(
          '@file' => $file->filename,
        )));
      }
      else {
        drupal_set_message(t('There was a problem importing @file.', array(
          '@file' => $file->filename,
        )));
      }
    }
  }
}