You are here

function views_calc_fields_form_submit in Views Calc 7

Same name and namespace in other branches
  1. 5 views_calc.module \views_calc_fields_form_submit()
  2. 6.3 views_calc.module \views_calc_fields_form_submit()
  3. 6 views_calc.module \views_calc_fields_form_submit()

FAPI fields_form submit.

Save the views calc field settings

File

./views_calc.module, line 363
This module will allow you to add calculated fields to views tables and compute (SUM, COUNT, AVG, etc) columns of numeric data in a views table.

Code

function views_calc_fields_form_submit($form, &$form_state) {
  $edit = $form_state['values'];
  $form_values = array();
  foreach ($edit as $delta => $value) {

    // If this is some form item we don't care about, skip it.
    if (!is_array($value) || !is_numeric($delta)) {
      continue;
    }
    $value['calc'] = trim($value['calc']);
    if (empty($value['calc'])) {

      // remove blank fields, don't save them
      if (!empty($value['cid'])) {
        db_delete('views_calc_fields')
          ->condition('cid', $value['cid'])
          ->execute();
      }
    }
    else {
      $tables = array();
      $form_values[$delta]['cid'] = $value['cid'];
      $form_values[$delta]['label'] = $value['label'];
      $form_values[$delta]['format'] = $value['format'];
      $form_values[$delta]['custom'] = $value['custom'];
      $form_values[$delta]['calc'] = $value['calc'];
      $form_values[$delta]['base'] = $value['base'];

      // Substitute field names back into the calculation.
      $matches = array();
      $base = $value['base'];
      foreach (_views_calc_substitutions($base) as $key => $value) {
        $label_patterns[] = "`(^|[^\\\\\\\\])" . preg_quote($value) . "`";
        $value_patterns[] = "`(^|[^\\\\\\\\])" . preg_quote($key) . "`";
        $repl[] = '${1}' . $key;
      }
      $form_values[$delta]['calc'] = preg_replace($label_patterns, $repl, $form_values[$delta]['calc']);

      // Extract the fields and table names from the calculation.
      $tables = array();
      $fields = array();
      foreach ($value_patterns as $pattern) {
        if (preg_match($pattern, $form_values[$delta]['calc'], $results)) {
          $fields[trim($results[0])] = trim($results[0]);
          $tmp = explode('.', trim($results[0]));
          if (trim($tmp[0])) {
            $tables[trim($tmp[0])] = trim($tmp[0]);
          }
        }
      }
      $form_values[$delta]['tablelist'] = implode(',', $tables);
      $form_values[$delta]['fieldlist'] = implode(',', $fields);
    }
  }
  foreach ((array) $form_values as $delta => $value) {
    if (empty($value['cid'])) {
      drupal_write_record('views_calc_fields', $value);
    }
    else {
      drupal_write_record('views_calc_fields', $value, array(
        'cid',
      ));
    }
  }
  views_invalidate_cache();
  drupal_set_message(t('Views Calc fields were updated.'));
}