content_admin.inc 60.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php
// $Id$

/**
 * @file
 * Administrative interface for content type creation.
 */


/**
 * Menu callback; presents a listing of content types.
 */
function _content_admin_type_overview() {
John Hwang's avatar
John Hwang committed
14
  $types = content_types();
15 16 17 18 19

  $header = array(t('Label'), t('Name'), t('Description'), array('data' => t('Operations'), 'colspan' => 3));
  $rows = array();
  foreach ($types as $type) {
    $row = array();
John Hwang's avatar
John Hwang committed
20 21 22
    $row[] = l(t($type['label']), 'admin/node/types/'. $type['type_name'] .'/fields');
    $row[] = $type['type_name'];
    $row[] = $type['description'];
23

John Hwang's avatar
John Hwang committed
24 25 26
    $row[] = l(t('edit'), 'admin/node/types/'. $type['type_name']);
    $row[] = l(t('duplicate'), 'admin/node/types/'. $type['type_name'] .'/duplicate');
    $row[] = l(t('delete'), 'admin/node/types/'. $type['type_name'] .'/delete');
27 28 29 30 31 32 33 34 35 36 37 38 39

    $rows[] = $row;
  }

  $output = theme('table', $header, $rows);

  return $output;
}

/**
 * Menu callback; lists all defined fields for quick reference.
 */
function _content_admin_type_fields() {
John Hwang's avatar
John Hwang committed
40
  $fields = content_fields();
41 42 43 44 45 46 47 48 49

  $header = array(t('Name'), t('Type'), t('Content types'));
  $rows = array();
  foreach ($fields as $field) {
    $row = array();
    $row[] = $field['field_name'];
    $row[] = $field['type'];

    $types = array();
50
    $result = db_query("SELECT nt.label FROM {node_field_instance} nfi LEFT JOIN {node_type_content} nt ON nt.type_name = nfi.type_name WHERE nfi.field_name = '%s' ORDER BY nt.label ASC", $field['field_name']);
John Hwang's avatar
John Hwang committed
51 52
    while ($type = db_fetch_array($result)) {
      $types[] = $type['label'];
53
    }
54
    $row[] = implode(', ', $types);
55 56 57 58 59 60 61 62 63 64 65 66 67

    $rows[] = $row;
  }

  $output = theme('table', $header, $rows);

  return $output;
}

/**
 * Menu callback; handles the editing of a content type.
 */
function _content_admin_type_edit($type_name = '', $original_type_name = '') {
John Hwang's avatar
John Hwang committed
68
  $types = content_types();
69 70 71 72 73 74 75 76
  if (isset($types[$type_name])) {
    $type = $types[$type_name];
  }
  else {
    if (isset($types[$original_type_name])) {
      $type = $types[$original_type_name];
    }
    else {
John Hwang's avatar
John Hwang committed
77 78 79 80 81
      $type = array();
      $type['label'] = '';
      $type['description'] = '';
      $type['help'] = '';
      $type['title_label'] = 'Title';
82 83 84 85 86 87 88
    }
  }

  $form = array();
  $form['label'] = array(
    '#title' => t('Label'),
    '#type' => 'textfield',
John Hwang's avatar
John Hwang committed
89
    '#default_value' => $type['label'],
90 91 92 93 94 95
    '#description' => t('The human-readable name of this content type.'),
    '#required' => TRUE,
  );
  $form['description'] = array(
    '#title' => t('Description'),
    '#type' => 'textarea',
John Hwang's avatar
John Hwang committed
96
    '#default_value' => $type['description'],
97 98 99 100 101 102 103
    '#rows' => 10,
    '#description' => t('A brief description of the content type.'),
    '#required' => FALSE,
  );
  $form['help'] = array(
    '#title' => t('Help text'),
    '#type' => 'textarea',
John Hwang's avatar
John Hwang committed
104
    '#default_value' => $type['help'],
105 106 107 108 109 110 111
    '#rows' => 10,
    '#description' => t('Instructions to present to the user when adding new content of this type.'),
    '#required' => FALSE,
  );
  $form['title_label'] = array(
    '#title' => t('Title field label'),
    '#type' => 'textfield',
John Hwang's avatar
John Hwang committed
112
    '#default_value' => $type['title_label'],
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    '#description' => t('The label for the title field.'),
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save content type'),
  );
  $form['type_name'] = array(
    '#type' => 'value',
    '#value' => $type_name,
  );
  $form['original_type_name'] = array(
    '#type' => 'value',
    '#value' => $original_type_name,
  );
  return drupal_get_form('_content_admin_type_edit', $form);
}

/**
 * Save a content type after editing.
 */
function _content_admin_type_edit_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
135
  $types = content_types();
136 137 138 139 140 141
  if (!isset($types[$form_values['type_name']])) {
    // Find a valid, computer-friendly type name.
    $form_values['type_name'] = trim($form_values['label']);
    $form_values['type_name'] = drupal_strtolower($form_values['type_name']);
    $form_values['type_name'] = str_replace(array(' ', '-'), '_', $form_values['type_name']);
    $form_values['type_name'] = preg_replace('/[^a-z0-9_]/', '', $form_values['type_name']);
142
    $form_values['type_name'] = 'content_'. $form_values['type_name'];
143 144 145 146 147 148 149 150 151
    $form_values['type_name'] = substr($form_values['type_name'], 0, 32);
    if (isset($types[$form_values['type_name']])) {
      $counter = 0;
      do {
        $new_name = substr($form_values['type_name'], 0, 30) .'_'. $counter++;
      } while (isset($types[$new_name]));
      $form_values['type_name'] = $new_name;
    }

152
    db_query("INSERT INTO {node_type_content} (type_name, label, description, help, title_label) VALUES ('%s', '%s', '%s', '%s', '%s')", $form_values['type_name'], $form_values['label'], $form_values['description'], $form_values['help'], $form_values['title_label']);
JonBob's avatar
JonBob committed
153 154 155 156

    switch ($GLOBALS['db_type']) {
      case 'mysql':
      case 'mysqli':
157
        db_query("CREATE TABLE {node_". $form_values['type_name'] ."} (
JonBob's avatar
JonBob committed
158 159 160
            vid int unsigned NOT NULL default '0',
            nid int unsigned NOT NULL default '0',
            PRIMARY KEY (vid)
yched's avatar
yched committed
161
          ) /*!40100 DEFAULT CHARACTER SET utf8 */");
JonBob's avatar
JonBob committed
162 163 164
        break;

      case 'pgsql':
165
        db_query("CREATE TABLE {node_". $form_values['type_name'] ."} (
166 167
            vid integer NOT NULL default '0' CHECK (vid >= 0),
            nid integer NOT NULL default '0' CHECK (nid >= 0),
JonBob's avatar
JonBob committed
168 169 170
            PRIMARY KEY (vid)
          )");
        break;
171
    }
172 173
  }
  else {
174
    db_query("UPDATE {node_type_content} SET label = '%s', description = '%s', help = '%s', title_label = '%s' WHERE type_name = '%s'", $form_values['label'], $form_values['description'], $form_values['help'], $form_values['title_label'], $form_values['type_name']);
175 176
  }

177
  if ($form_values['original_type_name'] > '') {
178

179
    // Duplicate the field structure from the old content type.
180 181 182 183
    $info   = _content_type_info();
    $fields = array_keys($info['content types'][$form_values['original_type_name']]['fields']);
    foreach ($fields as $field) {
      $field_values = array('field_name' => $field, 'type_name' => $form_values['type_name']);
184
      // using this function will both create new field instances
185 186 187
      // and move existing fields to separate shared table, if not already shared
      _content_admin_field_add_existing_submit('_content_admin_field_add_existing', $field_values);
    }
188 189 190
    if (module_exist('fieldgroup')) {
      fieldgroup_duplicate($form_values['original_type_name'], $form_values['type_name']);
    }
191 192 193 194 195 196 197
  }

  drupal_set_message(t('Saved content type %type.', array('%type' => theme('placeholder', $form_values['label']))));

  content_clear_type_cache();
  menu_rebuild();

198
  return 'admin/node/types/'. $form_values['type_name'];
199 200 201 202 203 204
}

/**
 * Menu callback; delete a content type.
 */
function _content_admin_type_delete($type_name = '') {
John Hwang's avatar
John Hwang committed
205
  $type = content_types($type_name);
206 207 208

  $form = array();
  $form['type_name'] = array('#type' => 'value', '#value' => $type_name);
John Hwang's avatar
John Hwang committed
209
  return confirm_form('_content_admin_type_delete', $form, t('Are you sure you want to delete the content type %type?', array('%type' => theme('placeholder', $type['label']))), 'admin/node/types', t('If you have any content left in this content type, it will be permanently deleted. This action cannot be undone.'), t('Delete'), t('Cancel'));
210 211 212 213 214 215
}

/**
 * Delete a content type.
 */
function _content_admin_type_delete_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
216
  $type = content_types($form_values['type_name']);
217 218

  if ($type && $form_values['confirm']) {
219
    include_once('./'. drupal_get_path('module', 'content') .'/content_crud.inc');
220
    content_type_delete($form_values);
John Hwang's avatar
John Hwang committed
221
    drupal_set_message(t('Deleted content type %type.', array('%type' => theme('placeholder', $type['label']))));
222
    return 'admin/node/types';
223 224 225 226 227
  }
}

/**
 * Menu callback; presents a listing of fields for a content type.
228
 *
229 230 231
 * Form includes form widgets to set weight and group for each item
 * and displays other form elements and their weights to make it
 * easier to place CCK fields in the form and see where they will appear.
232 233
 */
function _content_admin_field_overview($type_name) {
234 235 236 237 238 239
  return drupal_get_form('content_admin_field_overview_form', content_admin_field_overview_form($type_name));
}

function content_admin_field_overview_form($type_name) {
  $form = array();

John Hwang's avatar
John Hwang committed
240
  $type = content_types($type_name);
241
  $field_types = _content_field_types();
242

243 244
  // Create a dummy node and form and call hook_form_alter()
  // to produce an array of fields and weights added to the node by all modules.
245
  $dummy_node = new stdClass();
246
  $dummy_node->type = $type['type_name'];
247 248 249 250 251
  
  // Some modules (userreview...) "hide" their node forms, resulting in no field 
  // being listed. We set a special flag to inform them this form is special.
  $dummy_node->cck_dummy_node_form = TRUE;
  
252 253 254 255 256 257
  $dummy_form_id = $type['type_name'] .'_node_form';
  $dummy_form = node_form_array($dummy_node);
  foreach (module_implements('form_alter') as $module) {
    $function = $module .'_form_alter';
    $function($dummy_form_id, $dummy_form);
  }
258

259 260 261 262 263 264 265 266 267 268 269 270 271 272
  // Move group fields into a 'fields' subgroup to make them easier to identify.
  // Remove fields that are used in groups from the form, the group will handle them.
  if (module_exist('fieldgroup')) {
    $form['#groups']       = fieldgroup_groups($type['type_name']);
    $form['#group_labels'] = _fieldgroup_groups_label($type['type_name']);
    if (!$form['#groups']) {
      drupal_set_message(t('There are no groups configured for this content type.'));
    }
    foreach ($form['#groups'] as $group) {
      foreach ($group['fields'] as $field_name => $field) {
        unset($dummy_form[$field_name]);
      }
    }
  }
273

274 275 276
  if (!$type['fields']) {
    drupal_set_message(t('There are no fields configured for this content type.'));
  }
277

278 279 280
  if (!$type['fields'] && !$form['#groups']) {
    return $form;
  }
281

282
  $form['disabled']['#value'] = array();
283

284 285 286
  // Iterate through the dummy form and add top-level fields and weights to a table.
  // Construct the table values in an array '#table' that FAPI will ignore, keyed on the item's weight.
  // Create separate form elements for each weight and group value and put a placeholder for each in #table.
287

288
  foreach ($dummy_form as $key => $value) {
289

290 291 292 293
    // Limiting weight to < 10 will keep workflow and submit elements from being added to the overview table.
    // They're outside the weight range allowed for CCK fields, so won't interfere with field placement.

    if (is_array($value) && (isset($value['#weight']) || $key == 'body_filter') && $value['#weight'] <= 10) {
294

295
      // if this item is a group, insert group info into table, then add all the group fields below it
296
      if (substr($key, 0, 6) == 'group_' && isset($form['#groups'])) {
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
        $row = $group_form = array();
        $row['label']     = $form['#group_labels'][$form['#groups'][$key]['group_name']];
        $row['name']      = $form['#groups'][$key]['group_name'];
        $row['type']      = t('group');
        $row['weights']   = 'form-group-weights';
        $row['groups']    = '';
        $row['configure'] = l(t('configure'), 'admin/node/types/'. $type['type_name'] .'/groups/'. $form['#groups'][$key]['group_name'] .'/edit');
        $row['remove']    = l(t('remove'), 'admin/node/types/'. $type['type_name'] .'/groups/'. $form['#groups'][$key]['group_name'] .'/remove');
        $data = $row;

        $form['group-weights'][$key] = array('#type' => 'weight', '#default_value' => $value['#weight']);
        foreach ($form['#groups'][$key]['fields'] as $field_name => $field) {
          $row = array();
          $field = $type['fields'][$field_name];
          $row['label']     = $field['widget']['label'];
          $row['name']      = $field['field_name'];
          $row['type']      = $field_types[$field['type']]['label'];
          $row['weights']   = 'form-field-weights';
          $row['groups']    = 'form-field-groups';
          $row['configure'] = l(t('configure'), 'admin/node/types/'. $type['type_name'] .'/fields/'. $field_name);
          $row['remove']    = l(t('remove'), 'admin/node/types/'. $type['type_name'] .'/fields/'. $field_name .'/remove');
          $group_form[$field['widget']['weight']][] = array($field_name => $row);

          $form['field-weights'][$field_name] = array('#type' => 'weight', '#default_value' => $field['widget']['weight']);
          $form['field-groups'][$field_name]  = array('#type' => 'select', '#options' => $form['#group_labels'], '#default_value' => fieldgroup_get_group($type['type_name'], $field_name));
          $form['field-groups-defaults'][$field_name]  = array('#type' => 'hidden', '#value' => fieldgroup_get_group($type['type_name'], $field_name));
        }
        // sort the group fields by weight
        ksort($group_form);
        $group = (array) $data + array('fields' => $group_form);
        $form['#table'][$value['#weight']][] = array($key => $group);
      }
329

330 331 332 333 334 335 336 337 338 339 340 341 342 343
      // else if this item is a top-level field, insert field row into the table
      elseif (substr($key, 0, 6) == 'field_') {
        $row = array();
        $field = $type['fields'][$key];
        $row['label']     = $field['widget']['label'];
        $row['name']      = $field['field_name'];
        $row['type']      = $field_types[$field['type']]['label'];
        $row['weights']   = 'form-field-weights';
        if (isset($form['#groups'])) {
          $row['groups']  = 'form-field-groups';
        }
        $row['configure'] = l(t('configure'), 'admin/node/types/'. $type['type_name'] .'/fields/'. $key);
        $row['remove']    = l(t('remove'), 'admin/node/types/'. $type['type_name'] .'/fields/'. $key .'/remove');
        $form['#table'][$field['widget']['weight']][] = array($key => $row);
344

345 346 347 348 349
        $form['field-weights'][$key] = array('#type' => 'weight', '#default_value' => $field['widget']['weight']);
        if (isset($form['#groups'])) {
          $form['field-groups'][$key]  = array('#type' => 'select', '#options' => $form['#group_labels'], '#default_value' => fieldgroup_get_group($type['type_name'], $key));
        }
      }
350

351 352 353 354 355 356 357 358 359 360 361 362 363
      // otherwise this is some other form field or fieldset
      // if it has a weight display it as a disabled item
      else {
        $row = array();
        $row['label']     = $key == 'body_filter' ? t('body') : $key;
        $row['name']      = $key;
        $row['type']      = $key;
        $row['weights']   = 'form-field-weights';
        if (isset($form['#groups'])) {
          $row['groups']  = '';
        }
        $row['configure'] = '';
        $row['remove']    = '';
364
        $form['#table'][$value['#weight']][] = array($key => $row);
365
        $form['disabled']['#value'][] = $key;
366

367 368 369
        $form['field-weights'][$key] = array('#type' => 'weight', '#default_value' => $value['#weight'], '#attributes' => array('disabled' => 'disabled'));
      }
    }
370
  }
371

372 373
  // sort the table by weight
  ksort($form['#table']);
374

375 376 377 378 379 380 381 382 383 384
  // add submit buttons and hidden fields
  $form['submit']                         = array('#type' => 'submit', '#value' => t('Update'));
  $form['field-weights']['#tree']         = TRUE;
  $form['group-weights']['#tree']         = TRUE;
  $form['field-groups']['#tree']          = TRUE;
  $form['field-groups-defaults']['#tree'] = TRUE;
  $form['disabled']['#type']              = 'hidden';
  $form['disabled']['#value']             = serialize($form['disabled']['#value']);
  $form['type_name']['#type']             = 'hidden';
  $form['type_name']['#value']            = $type['type_name'];
385

386
  return $form;
387

388
}
389

390 391 392 393
/**
 *  Theme the field overview table by iterating through the form and rendering form elements in table cells
 */
function theme_content_admin_field_overview_form($form) {
394

395 396
  if (!$form['#table']) {
    return;
397 398
  }

399
  $disabled = unserialize($form['disabled']['#value']);
400

401 402 403 404 405 406 407 408
  if (module_exist('fieldgroup')) {
    $header = array(t('Label'), t('Name'), t('Type'), t('Weight'), t('Group'), array('data' => t('Operations'), 'colspan' => 2));
    $colspan = 7;
  }
  else {
    $header = array(t('Label'), t('Name'), t('Type'), t('Weight'), array('data' => t('Operations'), 'colspan' => 2));
    $colspan = 6;
  }
409

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  $rows = array();
  $i = 0;

  // The table was created in the form
  // iterate through it and render form elements when placeholders are encountered
  // then run the rows array through theme_table().
  foreach ($form['#table'] as $weight => $frow) {
    foreach ($frow as $delta => $item) {
      foreach ($item as $fname => $field) {
        $row = array();
        $class = 'content-field-overview-enabled';
        if (in_array($fname, $disabled)) {
          $class = 'content-field-overview-disabled';
        }
        foreach ($field as $col => $cell) {
          // display cols other than the group 'fields' col
          if ($col != 'fields') {
            switch ($cell) {
            case 'form-field-weights':
              $row[] = form_render($form['field-weights'][$fname]);
              break;
            case 'form-group-weights':
              $row[] = form_render($form['group-weights'][$fname]);
              break;
            case 'form-field-groups':
              $row[] = form_render($form['field-groups'][$fname]);
              break;
            default:
              $row[] = array('data' => $cell, 'class' => $class);
            }
          }
441

442 443 444 445
          elseif (isset($form['#groups'])) {
            // if this form contains groups info and this is a group 'fields' col, finish the previous row
            // then theme the 'fields' col with a fieldset containing a table and the group fields
            $grows = array();
446

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
            if (!empty($cell)) {
              foreach ($cell as $gweight => $grow) {
                foreach ($grow as $gdelta => $gitem) {
                  foreach ($gitem as $gname => $gfield) {
                    $grow = array();
                    foreach ($gfield as $gcol => $gcell) {
                      switch ($gcell) {
                        case 'form-field-weights':
                          $grow[] = form_render($form['field-weights'][$gname]);
                          break;
                        case 'form-field-groups':
                          $grow[] = form_render($form['field-groups'][$gname]);
                          break;
                        default:
                          $grow[] = $gcell;
                      }
                    }
                    $grows[] = array('data' => $grow, 'class' => 'content-field-overview-enabled');
                  }
                }
              }
            }
            else {
              $grows[] = array(array('data' => t('No fields have been added to this group.'), 'colspan' => $colspan, 'class' => 'content-field-overview-empty'));
            }
472

473 474 475 476 477 478 479 480 481
            // add the group row in its own table above the group fields table, then reset $row().
            $fieldset = array(
              '#title' => t('!label (!name)', array('!label' => $form['#group_labels'][$fname], '!name' => $fname)),
              '#collapsible' => TRUE,
              '#collapsed' => FALSE,
              '#value' => theme('table', array(), array(array('data' => $row, 'class' => 'content-field-overview-group'))) . theme('table', $header, $grows),
              );
            $row = array();
            $row[] = array(
482 483
              'data' => theme('fieldset', $fieldset),
              'colspan' => $colspan,
484 485 486 487 488 489 490 491 492 493 494
              'class' => 'active',
              );
            $grows = array();
          }
        }
        $rows[] = $row;
      }
    }
  }
  $output  = theme('table', $header, $rows, array('class' => 'content-field-overview'));
  $output .= form_render($form);
495
  return $output;
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516

}

function content_admin_field_overview_form_submit($form_id, $form_values) {
  $msg = FALSE;
  foreach ((array) $form_values['field-groups'] as $key => $value) {
    if ($key && !in_array($key, unserialize($form_values['disabled']))) {
      $values  = array('field_name' => $key, 'group' => $value, 'type_name' => $form_values['type_name']);
      $default = $form_values['field-groups-defaults'][$key];
      fieldgroup_content_admin_form_submit('_content_admin_field', $values, $default);
      $msg = TRUE;
    }
  }
  if ($msg) {
    drupal_set_message(t('Updated field groups.'));
  }
  $msg = FALSE;
  foreach ((array) $form_values['group-weights'] as $key => $value) {
    if ($key && !in_array($key, unserialize($form_values['disabled']))) {
      db_query("UPDATE {node_group} SET weight = %d WHERE type_name = '%s' AND group_name = '%s'",
        $value, $form_values['type_name'], $key);
517
      $msg = TRUE;
518 519 520 521 522 523 524 525
    }
  }
  if ($msg) {
    drupal_set_message(t('Updated group weights.'));
  }
  $msg = FALSE;
  foreach ((array) $form_values['field-weights'] as $key => $value) {
    if ($key && !in_array($key, unserialize($form_values['disabled']))) {
526
      db_query("UPDATE {node_field_instance} SET weight = %d WHERE type_name = '%s' AND field_name = '%s'",
527 528 529 530 531 532 533 534 535 536
        $value, $form_values['type_name'], $key);
      $msg = TRUE;
    }
  }
  if ($msg) {
    drupal_set_message(t('Updated field weights.'));
  }
  content_clear_type_cache();
  cache_clear_all('fieldgroup_data');

537 538
}

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
/**
 * Menu callback; presents a listing of fields display settings for a content type.
 *
 * Form includes form widgets to select which fields appear for teaser, full node...
 * and how the field labels should be rendered
 */
function content_admin_display_overview_form($type_name) {
  $type = content_types($type_name);
  $field_types = _content_field_types();

  $form = array();
  if (empty($type['fields'])) {
    drupal_set_message(t('There are no fields configured for this content type.'));
    return $form;
  }

  $form['#tree'] = TRUE;
  foreach ($type['fields'] as $field) {
    $form['fields'][$field['field_name']] = _content_admin_display_overview_row($field, $field_types[$field['type']]);
  }

  $form['type_name'] = array('#type' => 'hidden', '#value' => $type['type_name']);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));

  return drupal_get_form('content_admin_display_overview_form', $form);
}

function theme_content_admin_display_overview_form($form) {
  $header = array(t('Field'), t('Type'), t('Label'));
  foreach (_content_admin_display_contexts() as $key => $title) {
    $header[] = $title;
  }
  $rows = array();

  foreach (element_children($form['fields']) as $field) {
    $row = array();
    foreach (element_children($form['fields'][$field]) as $key) {
      $row[] = form_render($form['fields'][$field][$key]);
    }
    $rows[] = $row;
  }

  $output  = theme('table', $header, $rows, array('class' => 'content-field-display-overview'));
  $output .= form_render($form);
  return $output;
}

function content_admin_display_overview_form_submit($form_id, $form_values) {
  $type = $form_values['type_name'];
  foreach ($form_values['fields'] as $fieldname => $fieldvalues) {
    $display_settings = array();
    foreach ($fieldvalues as $key => $value) {
      $display_settings[$key] = $value;
    }

    db_query("UPDATE {node_field_instance} SET display_settings = '%s' WHERE type_name = '%s' AND field_name = '%s'",
      serialize($display_settings), $form_values['type_name'], $fieldname);
  }
597
  drupal_set_message(t('Your settings have been saved.'));
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
  content_clear_type_cache();
}

function _content_admin_display_overview_row($field, $field_type) {
  $defaults = $field['display_settings'];

  $options = array();
  foreach ($field_type['formatters'] as $name => $formatter_info) {
    $options[$name] = $formatter_info['label'];
  }
  $options['hidden'] = t('<Hidden>');

  $label_options = array(
    'above' => t('Above'),
    'inline' => t('Inline'),
    'hidden' => t('<Hidden>'),
  );

  $row = array();
  $row['type_label']  = array('#value' => $field['widget']['label']);
  $row['type']        = array('#value' => $field_type['label']);

  $row['label']['format'] = array(
    '#type' => 'select',
    '#options' => $label_options,
    '#default_value' => isset($defaults['label']['format']) ? $defaults['label']['format'] : 'above',
  );

  foreach (_content_admin_display_contexts() as $key => $title) {
    $row[$key]['format'] = array(
      '#type' => 'select',
      '#options' => $options,
      '#default_value' => isset($defaults[$key]['format']) ? $defaults[$key]['format'] : 'default',
    );
  }
  return $row;
}

function _content_admin_display_contexts() {
  return array(
    'teaser' => t('Teaser'),
    'full' => t('Full'),
  );
}

643 644 645 646
/**
 * Menu callback; presents the form for adding a new field.
 */
function _content_admin_field_add($type_name) {
647 648 649 650 651
  // make sure the old field list gets cleared before creating the new one
  if (!isset($_POST['edit'])) {
    content_clear_type_cache();
  }

John Hwang's avatar
John Hwang committed
652
  $type = content_types($type_name);
653
  $field_types = _content_field_types();
John Hwang's avatar
John Hwang committed
654
  $fields = content_fields();
655 656 657 658 659
  $widget_types = _content_widget_types();
  $output = '';

  $options = array();
  foreach ($fields as $field) {
John Hwang's avatar
John Hwang committed
660
    if (!isset($type['fields'][$field['field_name']]))
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    $options[$field['field_name']] = t($field['widget']['label']) .' ('. $field['field_name'] .')';
  }
  if ($options) {
    $form = array();
    $form['existing'] = array(
      '#type' => 'fieldset',
      '#title' => t('Add existing field'),
    );
    $form['existing']['field_name'] = array(
      '#type' => 'select',
      '#required' => TRUE,
      '#options' => $options,
    );
    $form['existing']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Add field'),
    );
    $form['existing']['type_name'] = array(
      '#type' => 'value',
      '#value' => $type_name,
    );
    $output .= drupal_get_form('_content_admin_field_add_existing', $form);
  }

  $field_type_options = array();
  foreach ($field_types as $field_name => $field_type) {
    foreach ($widget_types as $widget_name => $widget_type) {
      if (in_array($field_name, $widget_type['field types'])) {
        $field_type_options[$field_name .'-'. $widget_name] = $widget_type['label'];
      }
    }
  }
  if (count($field_type_options) > 0) {
    $form = array();
    $form['new'] = array(
      '#type' => 'fieldset',
      '#title' => t('Create new field'),
    );
    $form['new']['widget']['label'] = array(
700
      '#title' => t('Name'),
701 702
      '#type' => 'textfield',
      '#default_value' => '',
703
      '#description' => t('The machine-readable name of the field.<br/>Allowed characters : unaccentuated a-z, numbers and _. All other characters will be discarded.<br/>You\'ll be able to choose a human-readable label for the field on next page'),
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
      '#required' => TRUE,
    );
    $form['new']['field_widget_type'] = array(
      '#type' => 'radios',
      '#title' => t('Field type'),
      '#required' => TRUE,
      '#options' => $field_type_options,
      '#theme' => 'content_admin_field_add_new_field_widget_type',
    );

    $form['new']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Create field'),
    );
    $form['new']['type_name'] = array(
      '#type' => 'value',
      '#value' => $type_name,
    );
    $output .= drupal_get_form('_content_admin_field_add_new', $form);
  }
  else {
    drupal_set_message(t('No field modules are enabled. You need to <a href="%modules_url">enable one</a>, such as text.module, before you can add new fields.', array('%modules_url' => url('admin/modules'))), 'error');
  }

  return $output;
}

function theme_content_admin_field_add_new_field_widget_type($form) {
  $field_types = _content_field_types();
  $widget_types = _content_widget_types();
  $output = '';

  $output .= '<dl>';
  foreach ($field_types as $field_name => $field_type) {
    $output .= '<dt>'. $field_type['label'] .'</dt>';
    foreach ($widget_types as $widget_name => $widget_type) {
      if (in_array($field_name, $widget_type['field types'])) {
        $output .= '<dd>'. form_render($form[$field_name .'-'. $widget_name]) .'</dd>';
      }
    }
  }
  $output .= '</dl>';

  return $output;
}

/**
 * Add an existing field to a content type.
 */
function _content_admin_field_add_existing_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
754
  $field = content_fields($form_values['field_name']);
JonBob's avatar
JonBob committed
755 756 757 758 759 760 761 762 763 764 765 766 767
  $field_types = _content_field_types();
  $field_type = $field_types[$field['type']];
  $columns = module_invoke($field_type['module'], 'field_settings', 'database columns', $field);

  if (is_array($columns) && count($columns)) {
    if ($field['db_storage'] == CONTENT_DB_STORAGE_PER_CONTENT_TYPE) {
      $new_field = $field;
      $new_field['db_storage'] = CONTENT_DB_STORAGE_PER_FIELD;
      db_query("UPDATE {node_field} SET db_storage = %d WHERE field_name = '%s'", CONTENT_DB_STORAGE_PER_FIELD, $form_values['field_name']);
      content_alter_db_field($field, $columns, $new_field, $columns);
    }
  }

768
  $prior_instance = db_fetch_array(db_query("SELECT * FROM {node_field_instance} WHERE field_name = '%s'", $form_values['field_name']));
769
  if (!$prior_instance) {
John Hwang's avatar
John Hwang committed
770 771 772 773 774
    $prior_instance = array();
    $prior_instance['weight'] = 0;
    $prior_instance['label'] = $form_values['field_name'];
    $prior_instance['widget_type'] = '';
    $prior_instance['widget_settings'] = '';
775
    $prior_instance['display_settings'] = '';
John Hwang's avatar
John Hwang committed
776
    $prior_instance['description'] = '';
777
  }
778
  db_query("INSERT INTO {node_field_instance} (field_name, type_name, weight, label, widget_type, widget_settings, display_settings, description) VALUES ('%s', '%s', %d, '%s', '%s', '%s', '%s', '%s')", $form_values['field_name'], $form_values['type_name'], $prior_instance['weight'], $prior_instance['label'], $prior_instance['widget_type'], $prior_instance['widget_settings'], $prior_instance['display_settings'], $prior_instance['description']);
779

John Hwang's avatar
John Hwang committed
780
  drupal_set_message(t('Added field %label.', array('%label' => theme('placeholder', $prior_instance['label']))));
781
  content_clear_type_cache();
782
  return 'admin/node/types/'. $form_values['type_name'] .'/fields';
783 784 785 786 787 788 789 790
}

/**
 * Create a new field for a content type.
 */
function _content_admin_field_add_new_submit($form_id, $form_values) {
  // Find a valid, computer-friendly field name.

John Hwang's avatar
John Hwang committed
791
  $fields = content_fields();
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807

  $field_name = trim($form_values['label']);
  $field_name = drupal_strtolower($field_name);
  $field_name = str_replace(array(' ', '-'), '_', $field_name);
  $field_name = preg_replace('/[^a-z0-9_]/', '', $field_name);
  $field_name = 'field_'. $field_name;
  $field_name = substr($field_name, 0, 31);
  if (isset($fields[$field_name])) {
    $counter = 0;
    do {
      $new_name = substr($field_name, 0, 29) .'_'. $counter++;
    } while (isset($fields[$new_name]));
    $field_name = $new_name;
  }

  $field_widget_type = explode('-', $form_values['field_widget_type']);
JonBob's avatar
JonBob committed
808
  db_query("INSERT INTO {node_field} (field_name, type, global_settings, required, multiple, db_storage) VALUES ('%s', '%s', '%s', %d, %d, %d)", $field_name, $field_widget_type[0], serialize(array()), 0, 0, CONTENT_DB_STORAGE_PER_CONTENT_TYPE);
809
  db_query("INSERT INTO {node_field_instance} (field_name, type_name, weight, label, widget_type, widget_settings, display_settings, description) VALUES ('%s', '%s', %d, '%s', '%s', '%s', '%s', '%s')", $field_name, $form_values['type_name'], 0, $form_values['label'], $field_widget_type[1], serialize(array()), serialize(array()), '');
810 811

  content_clear_type_cache();
812 813 814 815

  // Create new database columns as necessary.
  $field_types = _content_field_types();
  $field_type = $field_types[$field_widget_type[0]];
John Hwang's avatar
John Hwang committed
816
  $field = content_fields($field_name);
JonBob's avatar
JonBob committed
817

818
  $columns = module_invoke($field_type['module'], 'field_settings', 'database columns', $field);
819 820 821
  if (is_array($columns) && count($columns)) {
    content_alter_db_field(array(), array(), $field, $columns);
  }
822 823

  drupal_set_message(t('Created field %label.', array('%label' => theme('placeholder', $form_values['label']))));
824
  return 'admin/node/types/'. $form_values['type_name'] .'/fields/'. $field_name;
825 826 827 828 829 830
}

/**
 * Menu callback; present a form for removing a field from a content type.
 */
function _content_admin_field_remove($type_name, $field_name) {
John Hwang's avatar
John Hwang committed
831 832
  $type = content_types($type_name);
  $field = $type['fields'][$field_name];
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849

  $form = array();
  $form['type_name'] = array(
    '#type' => 'value',
    '#value' => $type_name,
  );
  $form['field_name'] = array(
    '#type' => 'value',
    '#value' => $field_name,
  );
  return confirm_form('_content_admin_field_remove', $form, t('Are you sure you want to remove the field %field?', array('%field' => theme('placeholder', $field['widget']['label']))), 'admin/node/types/'. $type_name .'/fields', t('If you have any content left in this field, it will be lost. This action cannot be undone.'), t('Remove'), t('Cancel'));
}

/**
 * Remove a field from a content type.
 */
function _content_admin_field_remove_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
850 851
  $type = content_types($form_values['type_name']);
  $field = $type['fields'][$form_values['field_name']];
852 853

  if ($type && $field && $form_values['confirm']) {
854
    include_once('./'. drupal_get_path('module', 'content') .'/content_crud.inc');
855
    content_field_instance_delete($form_values);
856

John Hwang's avatar
John Hwang committed
857
    drupal_set_message(t('Removed field %field from %type.', array('%field' => theme('placeholder', $field['widget']['label']), '%type' => theme('placeholder', $type['label']))));
858

859
    return 'admin/node/types/'. $form_values['type_name'] .'/fields';
860 861 862 863 864 865 866 867 868
  }
}


/**
 * Menu callback; presents the field editing page.
 */
function _content_admin_field($type_name, $field_name) {
  $output = '';
John Hwang's avatar
John Hwang committed
869 870 871

  $type = content_types($type_name);
  $field = $type['fields'][$field_name];
872 873 874 875 876 877 878 879 880
  $field_types = _content_field_types();
  $field_type = $field_types[$field['type']];
  $widget_types = _content_widget_types();
  $widget_type = $widget_types[$field['widget']['type']];

  $form = array();
  $form['widget'] = array(
    '#type' => 'fieldset',
    '#title' => t('Widget settings'),
John Hwang's avatar
John Hwang committed
881
    '#description' => t('These settings apply only to the %field field as it appears in the %type content type.', array('%field' => theme('placeholder', $field['widget']['label']), '%type' => theme('placeholder', $type['label']))),
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
  );
  $options = array();
  foreach ($widget_types as $possible_widget_name => $possible_widget_type) {
    if (in_array($field['type'], $possible_widget_type['field types'])) {
      $options[$possible_widget_name] = $possible_widget_type['label'];
    }
  }
  if (count($options) == 1) {
    $key = array_keys($options);
    $default_widget = array_pop($key);
  }
  $form['widget']['widget_type'] = array(
    '#type' => 'radios',
    '#title' => t('Widget'),
    '#options' => $options,
    '#default_value' => $field['widget']['type'] ? $field['widget']['type'] : $default_widget,
    '#required' => TRUE,
  );
  $form['widget']['label'] = array(
    '#type' => 'textfield',
    '#title' => t('Label'),
    '#default_value' => $field['widget']['label'],
    '#required' => TRUE,
  );
  $form['widget']['weight'] = array(
907 908
    '#type' => 'hidden',
    '#value' => $field['widget']['weight'],
909
  );
910 911
  $additions = module_invoke($widget_type['module'], 'widget_settings', 'form', $field['widget']);
  if (is_array($additions)) {
912 913
    $form['widget'] = array_merge($form['widget'], $additions);
  }
914

JonBob's avatar
JonBob committed
915 916 917 918 919 920 921 922
  $form['widget']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Help text'),
    '#default_value' => $field['widget']['description'],
    '#rows' => 5,
    '#description' => t('Instructions to present to the user below this field on the editing form.'),
    '#required' => FALSE,
  );
923

924
  // Add handling for default value if not provided by field.
925
  if (content_handle('widget', 'default value', $field) == CONTENT_CALLBACK_DEFAULT) {
926
    $form['#attributes'] = array("enctype" => "multipart/form-data");
927 928 929 930 931 932 933 934 935 936 937
    $form['widget']['default_value_fieldset'] = array(
      '#type' => 'fieldset',
      '#title' => t('Default value'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    $default_value = is_array($field['widget']['default_value']) ? $field['widget']['default_value'] : array();
    $module = $widget_types[$field['widget']['type']]['module'];
    $function = $module .'_widget';
    if (function_exists($function)) {
      $node = array(); // TODO are there things we need to add in here ?
938 939 940 941 942
      // Make sure the default value is not a required field.
      $widget_field = $field;
      $widget_field['required'] = FALSE;
      $function('prepare form values', $node, $widget_field, $default_value);
      $form_element = $function('form', $node, $widget_field, $default_value);
943 944 945 946 947
    }
    else {
      // TODO : generate a series of textfields ?
      // why would a widget not have a hook_widget implementation ?
    }
948 949
    $form['widget']['default_value_fieldset']['default_value_widget'] = $form_element;
    $form['widget']['default_value_fieldset']['default_value_widget']['#tree'] = TRUE;
950 951 952 953
    $form['widget']['default_value_fieldset']['advanced_options'] = array(
      '#type' => 'fieldset',
      '#title' => t('Php code'),
      '#collapsible' => TRUE,
954
      '#collapsed' => empty($field['widget']['default_value_php']),
955
    );
956 957 958
    $db_info = content_database_info($field);
    $columns = array_keys($db_info['columns']);
    foreach ($columns as $key => $column) {
959
      $columns[$key] = "'$column' => value for $column";
960
    }
961 962 963 964 965 966 967
    $sample = 'array(
  0 => array('. implode(', ', $columns) .'),
  // You\'ll usually want to stop here. Provide more values
  // if you want your \'default value\' to be multi-valued :
  1 => array('. implode(', ', $columns) .'),
  2 => ...
);';
968 969 970 971 972 973
    $form['widget']['default_value_fieldset']['advanced_options']['default_value_php'] = array(
      '#type' => 'textarea',
      '#title' => t('Code'),
      '#default_value' => $field['widget']['default_value_php'],
      '#rows' => 6,
      '#tree' => TRUE,
974
      '#description' => t('Advanced Usage Only: PHP code that returns a default value. Should not include &lt;?php ?&gt; delimiters. If this field is filled out, the value returned by this code will override any value specified above. Expected format :<pre>%sample</pre>Using %link_devel\'s \'devel load\' tab on a %type content page might help you figure out the expected format.', array('%sample' => $sample, '%link_devel' => l('devel.module', 'http://www.drupal.org/project/devel'), '%type' => theme('placeholder', check_plain($type_name)))),
975 976 977
    );
  }

978 979
  $form['field'] = array(
    '#type' => 'fieldset',
980
    '#title' => t('Data settings'),
981 982 983 984 985 986 987 988 989 990 991 992 993
    '#description' => t('These settings apply to the %field field in every content type in which it appears.', array('%field' => theme('placeholder', $field['widget']['label']))),
  );
  $form['field']['required'] = array(
    '#type' => 'checkbox',
    '#title' => t('Required'),
    '#default_value' => $field['required'],
  );
  $form['field']['multiple'] = array(
    '#type' => 'checkbox',
    '#title' => t('Multiple values'),
    '#default_value' => $field['multiple'],
  );

994
  $additions = module_invoke($field_type['module'], 'field_settings', 'form', $field);
995 996 997
  if (is_array($additions)) {
    $form['field'] = array_merge($form['field'], $additions);
  }
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save field settings'),
  );
  $form['type_name'] = array(
    '#type' => 'value',
    '#value' => $type_name,
  );
  $form['field_name'] = array(
    '#type' => 'value',
    '#value' => $field_name,
  );
1011 1012 1013 1014 1015 1016 1017 1018
  $form['field_type'] = array(
    '#type' => 'value',
    '#value' => $field['type'],
    );
  $form['module'] = array(
    '#type' => 'value',
    '#value' => $field_type['module'],
    );
1019

1020
  $output .= drupal_get_form('_content_admin_field', $form);
1021

1022 1023 1024 1025 1026 1027 1028
  return $output;
}

/**
 * Validate a field's settings.
 */
function _content_admin_field_validate($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
1029 1030
  $type = content_types($form_values['type_name']);
  $field = $type['fields'][$form_values['field_name']];
1031 1032 1033 1034
  $field_types = _content_field_types();
  $field_type = $field_types[$field['type']];
  $widget_types = _content_widget_types();
  $widget_type = $widget_types[$field['widget']['type']];
1035

1036 1037
  module_invoke($widget_type['module'], 'widget_settings', 'validate', array_merge($field, $form_values));
  module_invoke($field_type['module'], 'field_settings', 'validate', array_merge($field, $form_values));
1038

1039
  // If content.module is handling the default value,
1040
  // validate the result using the field validation.
1041
  if (content_handle('widget', 'default value', $field) == CONTENT_CALLBACK_DEFAULT) {
1042 1043 1044
    if (isset($form_values['default_value_php']) && ($php = trim($form_values['default_value_php']))) {
      ob_start();
      $return = eval($php);
1045
      ob_end_clean();
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
      if (!is_array($return)) {
        $error = TRUE;
      }
      else {
        foreach ($return as $item) {
          if (!is_array($item)) {
            $error = TRUE;
            break;
          }
        }
      }
      if ($error) {
1058 1059 1060
        $db_info = content_database_info($field);
        $columns = array_keys($db_info['columns']);
        foreach ($columns as $key => $column) {
1061
          $columns[$key] = "'$column' => value for $column";
1062
        }
1063 1064 1065 1066 1067 1068 1069 1070
        $sample = 'array(
  0 => array('. implode(', ', $columns) .'),
  // You\'ll usually want to stop here. Provide more values
  // if you want your \'default value\' to be multi-valued :
  1 => array('. implode(', ', $columns) .'),
  2 => ...
);';
        form_set_error('default_value_php', t('The default value php code returned an incorrect value<br/>Expected format : <pre>%sample</pre>Returned value : %value', array('%sample' => $sample, '%value' => print_r($return, true))));
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
        return;
      }
      else {
        $default_value = $return;
        $is_code = TRUE;
        form_set_value(array('#parents' => array('default_value_php')), $php);
        form_set_value(array('#parents' => array('default_value')), array());
      }
    }
    else {
1081
      $default_value = $form_values['default_value_widget'][$field['field_name']];
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
      $is_code = FALSE;
      form_set_value(array('#parents' => array('default_value_php')), '');
      form_set_value(array('#parents' => array('default_value')), $default_value);
    }
    if (isset($default_value)) {
      $node = array();
      $node[$form_values['field_name']] = $default_value;
      $field['required'] = FALSE;
      $field_function = $field_type['module'] .'_field';
      $widget_function = $widget_type['module'] .'_widget';

      // If default_value is created from php code, don't run it through widget processing.
      // This way the default value code can directly create the correct array without being
      // mangled by widget processing which sometimes requires an input array in a completely different format.
      if (function_exists($widget_function) && !$is_code) {
        $widget_function('validate', $node, $field, $default_value);
        $widget_function('process form values', $node, $field, $default_value);
        // The widget processing may have altered the value, save it to be sure.
        form_set_value(array('#parents' => array('default_value')), $default_value);
      }
      if (function_exists($field_function)) {
        $field_function('validate', $node, $field, $default_value, NULL, NULL);
      }
      // The field validation routine won't set an error on the right field, so set it here.
      if (form_get_errors()) {
        if (trim($form_values['default_value_php'])) {
          form_set_error('default_value_php', t('The default value php code created @value which is invalid.', array('@value' => print_r($default_value, true))));
        }
        else {
          form_set_error('default_value', t('The default value is invalid.'));
        }
      }
    }
  }
1116 1117 1118 1119 1120 1121
}

/**
 * Save a field's settings after editing.
 */
function _content_admin_field_submit($form_id, $form_values) {
John Hwang's avatar
John Hwang committed
1122 1123
  $type = content_types($form_values['type_name']);
  $field = $type['fields'][$form_values['field_name']];
1124 1125 1126 1127 1128
  $field_types = _content_field_types();
  $field_type = $field_types[$field['type']];
  $widget_types = _content_widget_types();
  $widget_type = $widget_types[$form_values['widget_type']];

1129 1130
  // If content.module is handling the default value,
  // initialize $widget_settings with default values,
1131
  if (content_handle('widget', 'default value', $field) == CONTENT_CALLBACK_DEFAULT) {
1132 1133 1134 1135 1136 1137
    $widget_settings = array(
      'default_value' => $form_values['default_value'],
      'default_value_php' => $form_values['default_value_php'],
      );
  }

1138 1139
  $setting_names = module_invoke($widget_type['module'], 'widget_settings', 'save', $field);
  if (is_array($setting_names)) {
1140 1141 1142 1143 1144
    foreach ($setting_names as $setting) {
      $widget_settings[$setting] = $form_values[$setting];
    }
  }
  $field_settings = array();
1145 1146
  $setting_names = module_invoke($field_type['module'], 'field_settings', 'save', $field);
  if (is_array($setting_names)) {
1147 1148 1149 1150
    foreach ($setting_names as $setting) {
      $field_settings[$setting] = $form_values[$setting];
    }
  }
1151

1152 1153
  $prev_field = $field;
  $prev_columns = module_invoke($field_type['module'], 'field_settings', 'database columns', $field);
1154

JonBob's avatar
JonBob committed
1155
  db_query("UPDATE {node_field_instance} SET weight = %d, label = '%s', widget_type = '%s', widget_settings = '%s', description = '%s' WHERE type_name = '%s' AND field_name = '%s'", $form_values['weight'], $form_values['label'], $form_values['widget_type'], serialize($widget_settings), $form_values['description'], $form_values['type_name'], $form_values['field_name']);
1156

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  if ($form_values['multiple']) {
    $field['db_storage'] = CONTENT_DB_STORAGE_PER_FIELD;
  }
  else {
    $instances = db_result(db_query("SELECT COUNT(*) FROM {node_field_instance} WHERE field_name = '%s'", $form_values['field_name']));
    if ($instances == 1) {
      $field['db_storage'] = CONTENT_DB_STORAGE_PER_CONTENT_TYPE;
    }
  }
  db_query("UPDATE {node_field} SET required = %d, multiple = %d, global_settings = '%s', db_storage = %d WHERE field_name = '%s'", $form_values['required'], $form_values['multiple'], serialize($field_settings), $field['db_storage'], $form_values['field_name']);
1167 1168 1169

  drupal_set_message(t('Saved field %field.', array('%field' => theme('placeholder', $form_values['label']))));
  content_clear_type_cache();
1170

John Hwang's avatar
John Hwang committed
1171
  $new_field = content_fields($form_values['field_name']);
JonBob's avatar
JonBob committed
1172
  $new_columns = module_invoke($field_type['module'], 'field_settings', 'database columns', $new_field);
1173

1174 1175 1176 1177 1178 1179
  if (!isset($prev_columns)) {
    $prev_columns = array();
  }
  if (!isset($new_columns)) {
    $new_columns = array();
  }
1180 1181
  content_alter_db_field($prev_field, $prev_columns, $new_field, $new_columns);

1182
  return 'admin/node/types/'. $form_values['type_name'] .'/fields';
1183
}
1184 1185 1186 1187 1188 1189


/**
 * Perform adds, alters, and drops as needed to synchronize the database with
 * new field definitions.
 */
JonBob's avatar
JonBob committed
1190 1191 1192
function content_alter_db_field($previous_field, $previous_columns, $new_field, $new_columns) {
  // When adding and removing columns, we need to know what content type has an instance of the field.
  if (count($previous_columns)) {
1193 1194 1195
    if (!isset($previous_field['type_name'])) {
      $previous_field['type_name'] = db_result(db_query("SELECT type_name FROM {node_field_instance} WHERE field_name = '%s'", $previous_field['field_name']));
    }
JonBob's avatar
JonBob committed
1196 1197 1198 1199 1200
    $previous_db_info = content_database_info($previous_field);
  }
  if (count($new_columns)) {
    $new_field['type_name'] = db_result(db_query("SELECT type_name FROM {node_field_instance} WHERE field_name = '%s'", $new_field['field_name']));
    $new_db_info = content_database_info($new_field);
1201 1202
  }

JonBob's avatar
JonBob committed
1203 1204 1205 1206
  if (!count($new_columns)) {
    if (count($previous_columns)) {
      if ($previous_field['db_storage'] == CONTENT_DB_STORAGE_PER_FIELD) {
        db_query('DROP TABLE {'. $previous_db_info['table'] .'}');
1207
      }
JonBob's avatar
JonBob committed
1208 1209 1210 1211
      else {
        foreach ($previous_db_info['columns'] as $column => $attributes) {
          db_query('ALTER TABLE {'. $previous_db_info['table'] .'} DROP '. $attributes['column']);
        }
1212 1213
      }
    }
JonBob's avatar
JonBob committed
1214
    return;
1215
  }
JonBob's avatar
JonBob committed
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228

  if ($new_field['db_storage'] == CONTENT_DB_STORAGE_PER_FIELD) {
    if (!count($previous_columns) || $previous_field['db_storage'] == CONTENT_DB_STORAGE_PER_CONTENT_TYPE) {
      // New columns with per-field storage; need to add a table.
      if ($new_field['multiple']) {
        switch ($GLOBALS['db_type']) {
          case 'mysql':
          case 'mysqli':
            db_query("CREATE TABLE {". $new_db_info['table'] ."} (
                vid int unsigned NOT NULL default '0',
                delta int unsigned NOT NULL default '0',
                nid int unsigned NOT NULL default '0',
                PRIMARY KEY (vid,delta)
yched's avatar
yched committed
1229
              ) /*!40100 DEFAULT CHARACTER SET utf8 */");
JonBob's avatar
JonBob committed
1230 1231 1232 1233
            break;

          case 'pgsql':
            db_query("CREATE TABLE {". $new_db_info['table'] ."} (
1234 1235 1236
                vid integer NOT NULL default '0' CHECK(vid >= 0),
                delta integer NOT NULL default '0' CHECK(delta >= 0),
                nid integer NOT NULL default '0' CHECK(nid >= 0),
JonBob's avatar
JonBob committed
1237 1238 1239 1240
                PRIMARY KEY (vid,delta)
              )");
            break;
        }
1241
      }
JonBob's avatar
JonBob committed
1242 1243 1244 1245 1246 1247 1248 1249
      else {
        switch ($GLOBALS['db_type']) {
          case 'mysql':
          case 'mysqli':
            db_query("CREATE TABLE {". $new_db_info['table'] ."} (
                vid int unsigned NOT NULL default '0',
                nid int unsigned NOT NULL default '0',
                PRIMARY KEY (vid)
yched's avatar
yched committed
1250
              ) /*!40100 DEFAULT CHARACTER SET utf8 */");
JonBob's avatar
JonBob committed
1251 1252 1253 1254
            break;

          case 'pgsql':
            db_query("CREATE TABLE {". $new_db_info['table'] ."} (
1255 1256
                vid integer NOT NULL default '0' CHECK(vid >= 0),
                nid integer NOT NULL default '0' CHECK(nid >= 0),
JonBob's avatar
JonBob committed
1257 1258 1259 1260
                PRIMARY KEY (vid)
              )");
            break;
        }