field_ui.admin.inc 76.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<?php

/**
 * @file
 * Administrative interface for custom field type creation.
 */

/**
 * Menu callback; lists all defined fields for quick reference.
 */
function field_ui_fields_list() {
  $instances = field_info_instances();
  $field_types = field_info_field_types();
  $bundles = field_info_bundles();
15 16 17

  $modules = system_rebuild_module_data();

18 19
  $header = array(t('Field name'), t('Field type'), t('Used in'));
  $rows = array();
20
  foreach ($instances as $entity_type => $type_bundles) {
21 22
    foreach ($type_bundles as $bundle => $bundle_instances) {
      foreach ($bundle_instances as $field_name => $instance) {
23
        $field = field_info_field($field_name);
24 25 26 27 28 29 30 31 32 33

        // Initialize the row if we encounter the field for the first time.
        if (!isset($rows[$field_name])) {
          $rows[$field_name]['class'] = $field['locked'] ? array('menu-disabled') : array('');
          $rows[$field_name]['data'][0] = $field['locked'] ? t('@field_name (Locked)', array('@field_name' => $field_name)) : $field_name;
          $module_name = $field_types[$field['type']]['module'];
          $rows[$field_name]['data'][1] = $field_types[$field['type']]['label'] . ' ' . t('(module: !module)', array('!module' => $modules[$module_name]->info['name']));
        }

        // Add the current instance.
34
        $admin_path = _field_ui_bundle_admin_path($entity_type, $bundle);
35
        $rows[$field_name]['data'][2][] = $admin_path ? l($bundles[$entity_type][$bundle]['label'], $admin_path . '/fields') : $bundles[$entity_type][$bundle]['label'];
36
      }
37 38 39 40 41 42
    }
  }
  foreach ($rows as $field_name => $cell) {
    $rows[$field_name]['data'][2] = implode(', ', $cell['data'][2]);
  }
  if (empty($rows)) {
43
    $output = t('No fields have been defined yet.');
44 45 46 47
  }
  else {
    // Sort rows by field name.
    ksort($rows);
48
    $output = theme('table', array('header' => $header, 'rows' => $rows));
49 50 51 52 53 54 55
  }
  return $output;
}

/**
 * Helper function to display a message about inactive fields.
 */
56 57
function field_ui_inactive_message($entity_type, $bundle) {
  $inactive_instances = field_ui_inactive_instances($entity_type, $bundle);
58 59 60 61 62 63 64 65
  if (!empty($inactive_instances)) {
    $field_types = field_info_field_types();
    $widget_types = field_info_widget_types();

    foreach ($inactive_instances as $field_name => $instance) {
      $list[] = t('%field (@field_name) field requires the %widget_type widget provided by %widget_module module', array(
      '%field' => $instance['label'],
      '@field_name' => $instance['field_name'],
66
      '%widget_type' => isset($widget_types[$instance['widget']['type']]) ? $widget_types[$instance['widget']['type']]['label'] : $instance['widget']['type'],
67 68 69
      '%widget_module' => $instance['widget']['module'],
      ));
    }
70
    drupal_set_message(t('Inactive fields are not shown unless their providing modules are enabled. The following fields are not enabled: !list', array('!list' => theme('item_list', array('items' => $list)))), 'error');
71 72 73
  }
}

74 75 76 77 78 79
/**
 * Helper function: determines the rendering order of a tree array.
 *
 * This is intended as a callback for array_reduce().
 */
function _field_ui_reduce_order($array, $a) {
80
  $array = !isset($array) ? array() : $array;
81 82 83 84 85 86 87 88 89 90 91
  if ($a['name']) {
    $array[] = $a['name'];
  }
  if (!empty($a['children'])) {
    uasort($a['children'], 'drupal_sort_weight');
    $array = array_merge($array, array_reduce($a['children'], '_field_ui_reduce_order'));
  }
  return $array;
}

/**
92
 * Returns the region to which a row in the 'Manage fields' screen belongs.
93
 *
94 95
 * This function is used as a #row_callback in field_ui_field_overview_form(),
 * and is called during field_ui_table_pre_render().
96
 */
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
function field_ui_field_overview_row_region($row) {
  switch ($row['#row_type']) {
    case 'field':
    case 'extra_field':
      return 'main';
    case 'add_new_field':
      // If no input in 'label', assume the row has not been dragged out of the
      // 'add new' section.
      return (!empty($row['label']['#value']) ? 'main' : 'add_new');
  }
}

/**
 * Returns the region to which a row in the 'Manage display' screen belongs.
 *
 * This function is used as a #row_callback in field_ui_field_overview_form(),
 * and is called during field_ui_table_pre_render().
 */
function field_ui_display_overview_row_region($row) {
  switch ($row['#row_type']) {
    case 'field':
    case 'extra_field':
      return ($row['format']['type']['#value'] == 'hidden' ? 'hidden' : 'visible');
  }
}

/**
 * Pre-render callback for field_ui_table elements.
 */
function field_ui_table_pre_render($elements) {
  $js_settings = array();
128

129 130 131 132
  // For each region, build the tree structure from the weight and parenting
  // data contained in the flat form structure, to determine row order and
  // indentation.
  $regions = $elements['#regions'];
133
  $tree = array('' => array('name' => '', 'children' => array()));
134 135
  $trees = array_fill_keys(array_keys($regions), $tree);

136 137
  $parents = array();
  $list = drupal_map_assoc(element_children($elements));
138

139 140 141 142 143 144 145
  // Iterate on rows until we can build a known tree path for all of them.
  while ($list) {
    foreach ($list as $name) {
      $row = &$elements[$name];
      $parent = $row['parent_wrapper']['parent']['#value'];
      // Proceed if parent is known.
      if (empty($parent) || isset($parents[$parent])) {
146
        // Grab parent, and remove the row from the next iteration.
147 148 149
        $parents[$name] = $parent ? array_merge($parents[$parent], array($parent)) : array();
        unset($list[$name]);

150 151 152 153
        // Determine the region for the row.
        $function = $row['#region_callback'];
        $region_name = $function($row);

154
        // Add the element in the tree.
155
        $target = &$trees[$region_name][''];
156 157 158 159 160 161 162 163 164 165
        foreach ($parents[$name] as $key) {
          $target = &$target['children'][$key];
        }
        $target['children'][$name] = array('name' => $name, 'weight' => $row['weight']['#value']);

        // Add tabledrag indentation to the first row cell.
        if ($depth = count($parents[$name])) {
          $cell = current(element_children($row));
          $row[$cell]['#prefix'] = theme('indentation', array('size' => $depth)) . (isset($row[$cell]['#prefix']) ? $row[$cell]['#prefix'] : '');
        }
166 167 168 169

        // Add row id and associate JS settings.
        $id = drupal_html_class($name);
        $row['#attributes']['id'] = $id;
170 171 172 173 174 175 176 177
        if (isset($row['#js_settings'])) {
          $row['#js_settings'] += array(
            'rowHandler' => $row['#row_type'],
            'name' => $name,
            'region' => $region_name,
          );
          $js_settings[$id] = $row['#js_settings'];
        }
178 179 180
      }
    }
  }
181 182 183 184
  // Determine rendering order from the tree structure.
  foreach ($regions as $region_name => $region) {
    $elements['#regions'][$region_name]['rows_order'] = array_reduce($trees[$region_name], '_field_ui_reduce_order');
  }
185

186 187 188 189
  $elements['#attached']['js'][] = array(
    'type' => 'setting',
    'data' => array('fieldUIRowsData' => $js_settings),
  );
190 191

  return $elements;
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
}

/**
 * Returns HTML for Field UI overview tables.
 *
 * @param $variables
 *   An associative array containing:
 *   - elements: An associative array containing a Form API structure to be
 *     rendered as a table.
 *
 * @ingroup themeable
 */
function theme_field_ui_table($variables) {
  $elements = $variables['elements'];
  $table = array();
207
  $js_settings = array();
208

209
  // Add table headers and attributes.
210 211 212 213 214 215
  foreach (array('header', 'attributes') as $key) {
    if (isset($elements["#$key"])) {
      $table[$key] = $elements["#$key"];
    }
  }

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  // Determine the colspan to use for region rows, by checking the number of
  // columns in the headers.
  $colums_count = 0;
  foreach ($table['header'] as $header) {
    $colums_count += (is_array($header) && isset($header['colspan']) ? $header['colspan'] : 1);
  }

  // Render rows, region by region.
  foreach ($elements['#regions'] as $region_name => $region) {
    $region_name_class = drupal_html_class($region_name);

    // Add region rows.
    if (isset($region['title'])) {
      $table['rows'][] = array(
        'class' => array('region-title', 'region-' . $region_name_class . '-title'),
        'no_striping' => TRUE,
        'data' => array(
          array('data' => $region['title'], 'colspan' => $colums_count),
        ),
      );
    }
    if (isset($region['message'])) {
      $class = (empty($region['rows_order']) ? 'region-empty' : 'region-populated');
      $table['rows'][] = array(
        'class' => array('region-message', 'region-' . $region_name_class . '-message', $class),
        'no_striping' => TRUE,
        'data' => array(
          array('data' => $region['message'], 'colspan' => $colums_count),
        ),
      );
    }

    // Add form rows, in the order determined at pre-render time.
    foreach ($region['rows_order'] as $name) {
      $element = $elements[$name];

      $row = array('data' => array());
      if (isset($element['#attributes'])) {
        $row += $element['#attributes'];
      }
256

257 258 259 260 261 262
      foreach (element_children($element) as $cell_key) {
        $cell = array('data' => drupal_render($element[$cell_key]));
        if (isset($element[$cell_key]['#cell_attributes'])) {
          $cell += $element[$cell_key]['#cell_attributes'];
        }
        $row['data'][] = $cell;
263
      }
264
      $table['rows'][] = $row;
265 266 267 268 269 270
    }
  }

  return theme('table', $table);
}

271
/**
272
 * Menu callback; listing of fields for a bundle.
273 274 275
 *
 * Allows fields and pseudo-fields to be re-ordered.
 */
276 277
function field_ui_field_overview_form($form, &$form_state, $entity_type, $bundle) {
  $bundle = field_extract_bundle($entity_type, $bundle);
278

279 280
  field_ui_inactive_message($entity_type, $bundle);
  $admin_path = _field_ui_bundle_admin_path($entity_type, $bundle);
281 282 283

  // When displaying the form, make sure the list of fields is up-to-date.
  if (empty($form_state['post'])) {
284
    field_info_cache_clear();
285 286 287
  }

  // Gather bundle information.
288
  $instances = field_info_instances($entity_type, $bundle);
289 290 291
  $field_types = field_info_field_types();
  $widget_types = field_info_widget_types();

292
  $extra_fields = field_info_extra_fields($entity_type, $bundle, 'form');
293

294
  $form += array(
295
    '#entity_type' => $entity_type,
296 297
    '#bundle' => $bundle,
    '#fields' => array_keys($instances),
298
    '#extra' => array_keys($extra_fields),
299 300
  );

301
  $table = array(
302
    '#type' => 'field_ui_table',
303 304 305 306 307 308 309 310 311 312
    '#tree' => TRUE,
    '#header' => array(
      t('Label'),
      t('Weight'),
      t('Parent'),
      t('Name'),
      t('Field'),
      t('Widget'),
      array('data' => t('Operations'), 'colspan' => 2),
    ),
313
    '#parent_options' => array(),
314
    '#regions' => array(
315
      'main' => array('message' => t('No fields are present yet.')),
316 317 318 319 320 321
      'add_new' => array('title' => '&nbsp;'),
    ),
    '#attributes' => array(
      'class' => array('field-ui-overview'),
      'id' => 'field-overview',
    ),
322 323
  );

324 325 326 327
  // Fields.
  foreach ($instances as $name => $instance) {
    $field = field_info_field($instance['field_name']);
    $admin_field_path = $admin_path . '/fields/' . $instance['field_name'];
328
    $table[$name] = array(
329 330 331
      '#attributes' => array('class' => array('draggable', 'tabledrag-leaf')),
      '#row_type' => 'field',
      '#region_callback' => 'field_ui_field_overview_row_region',
332 333 334
      'label' => array(
        '#markup' => check_plain($instance['label']),
      ),
335 336
      'weight' => array(
        '#type' => 'textfield',
337 338
        '#title' => t('Weight for @title', array('@title' => $instance['label'])),
        '#title_display' => 'invisible',
339
        '#default_value' => $instance['widget']['weight'],
340 341 342 343 344 345
        '#size' => 3,
        '#attributes' => array('class' => array('field-weight')),
       ),
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
346 347
          '#title' => t('Parent for @title', array('@title' => $instance['label'])),
          '#title_display' => 'invisible',
348
          '#options' => $table['#parent_options'],
349
          '#empty_value' => '',
350
          '#attributes' => array('class' => array('field-parent')),
351
          '#parents' => array('fields', $name, 'parent'),
352 353 354 355 356 357 358
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
          '#default_value' => $name,
          '#attributes' => array('class' => array('field-name')),
        ),
      ),
359 360 361 362
      'field_name' => array(
        '#markup' => $instance['field_name'],
      ),
      'type' => array(
363 364 365 366
        '#type' => 'link',
        '#title' => t($field_types[$field['type']]['label']),
        '#href' => $admin_field_path . '/field-settings',
        '#options' => array('attributes' => array('title' => t('Edit field settings.'))),
367 368
      ),
      'widget_type' => array(
369 370 371 372
        '#type' => 'link',
        '#title' => t($widget_types[$instance['widget']['type']]['label']),
        '#href' => $admin_field_path . '/widget-type',
        '#options' => array('attributes' => array('title' => t('Change widget type.'))),
373 374
      ),
      'edit' => array(
375 376 377 378
        '#type' => 'link',
        '#title' => t('edit'),
        '#href' => $admin_field_path,
        '#options' => array('attributes' => array('title' => t('Edit instance settings.'))),
379 380
      ),
      'delete' => array(
381 382 383 384 385
        '#type' => 'link',
        '#title' => t('delete'),
        '#href' => $admin_field_path . '/delete',
        '#options' => array('attributes' => array('title' => t('Delete instance.'))),
      ),
386 387 388
    );

    if (!empty($instance['locked'])) {
389 390 391
      $table[$name]['edit'] = array('#value' => t('Locked'));
      $table[$name]['delete'] = array();
      $table[$name]['#attributes']['class'][] = 'menu-disabled';
392 393 394 395
    }
  }

  // Non-field elements.
396
  foreach ($extra_fields as $name => $extra_field) {
397
    $table[$name] = array(
398 399 400
      '#attributes' => array('class' => array('draggable', 'tabledrag-leaf')),
      '#row_type' => 'extra_field',
      '#region_callback' => 'field_ui_field_overview_row_region',
401
      'label' => array(
402
        '#markup' => check_plain($extra_field['label']),
403 404 405
      ),
      'weight' => array(
        '#type' => 'textfield',
406
        '#default_value' => $extra_field['weight'],
407
        '#size' => 3,
408
        '#attributes' => array('class' => array('field-weight')),
409
        '#title_display' => 'invisible',
410
        '#title' => t('Weight for @title', array('@title' => $extra_field['label'])),
411
      ),
412 413 414
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
415 416
          '#title' => t('Parent for @title', array('@title' => $extra_field['label'])),
          '#title_display' => 'invisible',
417
          '#options' => $table['#parent_options'],
418
          '#empty_value' => '',
419
          '#attributes' => array('class' => array('field-parent')),
420
          '#parents' => array('fields', $name, 'parent'),
421 422 423 424 425 426 427 428 429 430 431 432 433 434
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
          '#default_value' => $name,
          '#attributes' => array('class' => array('field-name')),
        ),
      ),
      'field_name' => array(
        '#markup' => $name,
      ),
      'type' => array(
        '#markup' => isset($extra_field['description']) ? $extra_field['description'] : '',
        '#cell_attributes' => array('colspan' => 2),
      ),
435
      'edit' => array(
436
        '#markup' => isset($extra_field['edit']) ? $extra_field['edit'] : '',
437 438
      ),
      'delete' => array(
439
        '#markup' => isset($extra_field['delete']) ? $extra_field['delete'] : '',
440 441 442 443 444
      ),
    );
  }

  // Additional row: add new field.
445
  $max_weight = field_info_max_weight($entity_type, $bundle, 'form');
446 447 448 449
  $field_type_options = field_ui_field_type_options();
  $widget_type_options = field_ui_widget_type_options(NULL, TRUE);
  if ($field_type_options && $widget_type_options) {
    $name = '_add_new_field';
450 451
    $table[$name] = array(
      '#attributes' => array('class' => array('draggable', 'tabledrag-leaf', 'add-new')),
452 453
      '#row_type' => 'add_new_field',
      '#region_callback' => 'field_ui_field_overview_row_region',
454 455
      'label' => array(
        '#type' => 'textfield',
456 457
        '#title' => t('New field label'),
        '#title_display' => 'invisible',
458 459
        '#size' => 15,
        '#description' => t('Label'),
460 461 462 463 464
        '#prefix' => '<div class="label-input"><div class="add-new-placeholder">' . t('Add new field') .'</div>',
        '#suffix' => '</div>',
      ),
      'weight' => array(
        '#type' => 'textfield',
465
        '#default_value' => $max_weight + 1,
466 467 468 469 470 471 472 473 474
        '#size' => 3,
        '#title_display' => 'invisible',
        '#title' => t('Weight for new field'),
        '#attributes' => array('class' => array('field-weight')),
        '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
      ),
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
475 476
          '#title' => t('Parent for new field'),
          '#title_display' => 'invisible',
477
          '#options' => $table['#parent_options'],
478
          '#empty_value' => '',
479 480
          '#attributes' => array('class' => array('field-parent')),
          '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
481
          '#parents' => array('fields', $name, 'parent'),
482 483 484 485 486 487
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
          '#default_value' => $name,
          '#attributes' => array('class' => array('field-name')),
        ),
488 489 490
      ),
      'field_name' => array(
        '#type' => 'textfield',
491 492
        '#title' => t('New field name'),
        '#title_display' => 'invisible',
493 494 495 496
        // This field should stay LTR even for RTL languages.
        '#field_prefix' => '<span dir="ltr">field_',
        '#field_suffix' => '</span>&lrm;',
        '#attributes' => array('dir'=>'ltr'),
497
        '#size' => 10,
498
        '#description' => t('Field name (a-z, 0-9, _)'),
499
        '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
500 501 502
      ),
      'type' => array(
        '#type' => 'select',
503 504
        '#title' => t('Type of new field'),
        '#title_display' => 'invisible',
505
        '#options' => $field_type_options,
506
        '#empty_option' => t('- Select a field type -'),
507
        '#description' => t('Type of data to store.'),
508 509
        '#attributes' => array('class' => array('field-type-select')),
        '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
510 511 512
      ),
      'widget_type' => array(
        '#type' => 'select',
513 514
        '#title' => t('Widget for new field'),
        '#title_display' => 'invisible',
515
        '#options' => $widget_type_options,
516
        '#empty_option' => t('- Select a widget -'),
517
        '#description' => t('Form element to edit the data.'),
518 519 520
        '#attributes' => array('class' => array('widget-type-select')),
        '#cell_attributes' => array('colspan' => 3),
        '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
521
      ),
522 523 524 525
      'translatable' => array(
        '#type' => 'value',
        '#value' => FALSE,
      ),
526 527 528 529
    );
  }

  // Additional row: add existing field.
530
  $existing_field_options = field_ui_existing_field_options($entity_type, $bundle);
531 532
  if ($existing_field_options && $widget_type_options) {
    $name = '_add_existing_field';
533
    $table[$name] = array(
534
      '#attributes' => array('class' => array('draggable', 'tabledrag-leaf', 'add-new')),
535 536
      '#row_type' => 'add_new_field',
      '#region_callback' => 'field_ui_field_overview_row_region',
537 538
      'label' => array(
        '#type' => 'textfield',
539 540
        '#title' => t('Existing field label'),
        '#title_display' => 'invisible',
541 542
        '#size' => 15,
        '#description' => t('Label'),
543 544 545 546 547 548
        '#attributes' => array('class' => array('label-textfield')),
        '#prefix' => '<div class="label-input"><div class="add-new-placeholder">' . t('Add existing field') .'</div>',
        '#suffix' => '</div>',
      ),
      'weight' => array(
        '#type' => 'textfield',
549
        '#default_value' => $max_weight + 2,
550 551 552 553 554 555 556 557 558
        '#size' => 3,
        '#title_display' => 'invisible',
        '#title' => t('Weight for added field'),
        '#attributes' => array('class' => array('field-weight')),
        '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
      ),
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
559 560
          '#title' => t('Parent for existing field'),
          '#title_display' => 'invisible',
561
          '#options' => $table['#parent_options'],
562
          '#empty_value' => '',
563 564
          '#attributes' => array('class' => array('field-parent')),
          '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
565
          '#parents' => array('fields', $name, 'parent'),
566 567 568 569 570 571
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
          '#default_value' => $name,
          '#attributes' => array('class' => array('field-name')),
        ),
572 573 574
      ),
      'field_name' => array(
        '#type' => 'select',
575 576
        '#title' => t('Existing field to share'),
        '#title_display' => 'invisible',
577
        '#options' => $existing_field_options,
578
        '#empty_option' => t('- Select an existing field -'),
579
        '#description' => t('Field to share'),
580 581 582
        '#attributes' => array('class' => array('field-select')),
        '#cell_attributes' => array('colspan' => 2),
        '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
583 584 585
      ),
      'widget_type' => array(
        '#type' => 'select',
586 587
        '#title' => t('Widget for existing field'),
        '#title_display' => 'invisible',
588
        '#options' => $widget_type_options,
589
        '#empty_option' => t('- Select a widget -'),
590
        '#description' => t('Form element to edit the data.'),
591 592 593
        '#attributes' => array('class' => array('widget-type-select')),
        '#cell_attributes' => array('colspan' => 3),
        '#prefix' => '<div class="add-new-placeholder">&nbsp;</div>',
594 595 596
      ),
    );
  }
597
  $form['fields'] = $table;
598

599 600
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Save'));
601

602 603
  $form['#attached']['css'][] = drupal_get_path('module', 'field_ui') . '/field_ui.css';
  $form['#attached']['js'][] = drupal_get_path('module', 'field_ui') . '/field_ui.js';
604

605 606
  // Add settings for the update selects behavior.
  $js_fields = array();
607
  foreach ($existing_field_options as $field_name => $fields) {
608
    $field = field_info_field($field_name);
609
    $instance = field_info_instance($form['#entity_type'], $field_name, $form['#bundle']);
610 611 612
    $js_fields[$field_name] = array('label' => $instance['label'], 'type' => $field['type'], 'widget' => $instance['widget']['type']);
  }

613 614
  $form['#attached']['js'][] = array(
    'type' => 'setting',
615
    'data' => array('fields' => $js_fields, 'fieldWidgetTypes' => field_ui_widget_type_options()),
616
  );
617

618 619 620 621 622
  // Add tabledrag behavior.
  $form['#attached']['drupal_add_tabledrag'][] = array('field-overview', 'order', 'sibling', 'field-weight');
  $form['#attached']['drupal_add_tabledrag'][] = array('field-overview', 'match', 'parent', 'field-parent', 'field-parent', 'field-name');

  return $form;
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
}

/**
 * Validate handler for the field overview form.
 */
function field_ui_field_overview_form_validate($form, &$form_state) {
  _field_ui_field_overview_form_validate_add_new($form, $form_state);
  _field_ui_field_overview_form_validate_add_existing($form, $form_state);
}

/**
 * Helper function for field_ui_field_overview_form_validate.
 *
 * Validate the 'add new field' row.
 */
function _field_ui_field_overview_form_validate_add_new($form, &$form_state) {
639
  $field = $form_state['values']['fields']['_add_new_field'];
640 641 642 643 644

  // Validate if any information was provided in the 'add new field' row.
  if (array_filter(array($field['label'], $field['field_name'], $field['type'], $field['widget_type']))) {
    // Missing label.
    if (!$field['label']) {
645
      form_set_error('fields][_add_new_field][label', t('Add new field: you need to provide a label.'));
646 647 648 649
    }

    // Missing field name.
    if (!$field['field_name']) {
650
      form_set_error('fields][_add_new_field][field_name', t('Add new field: you need to provide a field name.'));
651 652 653 654 655 656 657 658
    }
    // Field name validation.
    else {
      $field_name = $field['field_name'];

      // Add the 'field_' prefix.
      if (substr($field_name, 0, 6) != 'field_') {
        $field_name = 'field_' . $field_name;
659
        form_set_value($form['fields']['_add_new_field']['field_name'], $field_name, $form_state);
660 661 662 663
      }

      // Invalid field name.
      if (!preg_match('!^field_[a-z0-9_]+$!', $field_name)) {
664
        form_set_error('fields][_add_new_field][field_name', t('Add new field: the field name %field_name is invalid. The name must include only lowercase unaccentuated letters, numbers, and underscores.', array('%field_name' => $field_name)));
665 666
      }
      if (strlen($field_name) > 32) {
667
        form_set_error('fields][_add_new_field][field_name', t("Add new field: the field name %field_name is too long. The name is limited to 32 characters, including the 'field_' prefix.", array('%field_name' => $field_name)));
668 669 670 671 672 673
      }

      // Field name already exists. We need to check inactive fields as well, so
      // we can't use field_info_fields().
      $fields = field_read_fields(array('field_name' => $field_name), array('include_inactive' => TRUE));
      if ($fields) {
674
        form_set_error('fields][_add_new_field][field_name', t('Add new field: the field name %field_name already exists.', array('%field_name' => $field_name)));
675 676 677 678 679
      }
    }

    // Missing field type.
    if (!$field['type']) {
680
      form_set_error('fields][_add_new_field][type', t('Add new field: you need to select a field type.'));
681 682 683 684
    }

    // Missing widget type.
    if (!$field['widget_type']) {
685
      form_set_error('fields][_add_new_field][widget_type', t('Add new field: you need to select a widget.'));
686 687 688 689 690
    }
    // Wrong widget type.
    elseif ($field['type']) {
      $widget_types = field_ui_widget_type_options($field['type']);
      if (!isset($widget_types[$field['widget_type']])) {
691
        form_set_error('fields][_add_new_field][widget_type', t('Add new field: invalid widget.'));
692 693 694 695 696 697 698 699 700 701 702 703
      }
    }
  }
}

/**
 * Helper function for field_ui_field_overview_form_validate.
 *
 * Validate the 'add existing field' row.
 */
function _field_ui_field_overview_form_validate_add_existing($form, &$form_state) {
  // The form element might be absent if no existing fields can be added to
704
  // this bundle.
705 706
  if (isset($form_state['values']['fields']['_add_existing_field'])) {
    $field = $form_state['values']['fields']['_add_existing_field'];
707 708 709 710 711

    // Validate if any information was provided in the 'add existing field' row.
    if (array_filter(array($field['label'], $field['field_name'], $field['widget_type']))) {
      // Missing label.
      if (!$field['label']) {
712
        form_set_error('fields][_add_existing_field][label', t('Add existing field: you need to provide a label.'));
713 714 715 716
      }

      // Missing existing field name.
      if (!$field['field_name']) {
717
        form_set_error('fields][_add_existing_field][field_name', t('Add existing field: you need to select a field.'));
718 719 720 721
      }

      // Missing widget type.
      if (!$field['widget_type']) {
722
        form_set_error('fields][_add_existing_field][widget_type', t('Add existing field: you need to select a widget.'));
723 724 725 726 727
      }
      // Wrong widget type.
      elseif ($field['field_name'] && ($existing_field = field_info_field($field['field_name']))) {
        $widget_types = field_ui_widget_type_options($existing_field['type']);
        if (!isset($widget_types[$field['widget_type']])) {
728
          form_set_error('fields][_add_existing_field][widget_type', t('Add existing field: invalid widget.'));
729 730 731 732 733 734 735 736 737 738
        }
      }
    }
  }
}

/**
 * Submit handler for the field overview form.
 */
function field_ui_field_overview_form_submit($form, &$form_state) {
739
  $form_values = $form_state['values']['fields'];
740
  $entity_type = $form['#entity_type'];
741
  $bundle = $form['#bundle'];
742
  $admin_path = _field_ui_bundle_admin_path($entity_type, $bundle);
743

744 745
  $bundle_settings = field_bundle_settings($entity_type, $bundle);

746 747 748
  // Update field weights.
  foreach ($form_values as $key => $values) {
    if (in_array($key, $form['#fields'])) {
749
      $instance = field_read_instance($entity_type, $key, $bundle);
750 751 752 753
      $instance['widget']['weight'] = $values['weight'];
      field_update_instance($instance);
    }
    elseif (in_array($key, $form['#extra'])) {
754
      $bundle_settings['extra_fields']['form'][$key]['weight'] = $values['weight'];
755 756 757
    }
  }

758
  field_bundle_settings($entity_type, $bundle, $bundle_settings);
759 760 761 762 763 764 765 766 767 768 769

  $destinations = array();

  // Create new field.
  $field = array();
  if (!empty($form_values['_add_new_field']['field_name'])) {
    $values = $form_values['_add_new_field'];

    $field = array(
      'field_name' => $values['field_name'],
      'type' => $values['type'],
770
      'translatable' => $values['translatable'],
771 772 773
    );
    $instance = array(
      'field_name' => $field['field_name'],
774
      'entity_type' => $entity_type,
775 776 777 778 779 780 781 782 783 784 785 786 787 788
      'bundle' => $bundle,
      'label' => $values['label'],
      'widget' => array(
        'type' => $values['widget_type'],
        'weight' => $values['weight'],
      ),
    );

    // Create the field and instance.
    try {
      field_create_field($field);
      field_create_instance($instance);

      $destinations[] = $admin_path . '/fields/' . $field['field_name'] . '/field-settings';
789
      $destinations[] = $admin_path . '/fields/' . $field['field_name'];
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

      // Store new field information for any additional submit handlers.
      $form_state['fields_added']['_add_new_field'] = $field['field_name'];
    }
    catch (Exception $e) {
      drupal_set_message(t('There was a problem creating field %label: @message.', array('%label' => $instance['label'], '@message' => $e->getMessage())));
    }
  }

  // Add existing field.
  if (!empty($form_values['_add_existing_field']['field_name'])) {
    $values = $form_values['_add_existing_field'];
    $field = field_info_field($values['field_name']);
    if (!empty($field['locked'])) {
      drupal_set_message(t('The field %label cannot be added because it is locked.', array('%label' => $values['label'])));
    }
    else {
      $instance = array(
        'field_name' => $field['field_name'],
809
        'entity_type' => $entity_type,
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
        'bundle' => $bundle,
        'label' => $values['label'],
        'widget' => array(
          'type' => $values['widget_type'],
          'weight' => $values['weight'],
        ),
      );

      try {
        field_create_instance($instance);
        $destinations[] = $admin_path . '/fields/' . $instance['field_name'] . '/edit';
        // Store new field information for any additional submit handlers.
        $form_state['fields_added']['_add_existing_field'] = $instance['field_name'];
      }
      catch (Exception $e) {
        drupal_set_message(t('There was a problem creating field instance %label: @message.', array('%label' => $instance['label'], '@message' => $e->getMessage())));
      }
    }
  }

  if ($destinations) {
831 832
    $destination = drupal_get_destination();
    $destinations[] = $destination['destination'];
833
    unset($_GET['destination']);
834 835
    $form_state['redirect'] = field_ui_get_destinations($destinations);
  }
836 837 838
  else {
    drupal_set_message(t('Your settings have been saved.'));
  }
839 840 841
}

/**
842
 * Menu callback; presents field display settings for a given view mode.
843
 */
844
function field_ui_display_overview_form($form, &$form_state, $entity_type, $bundle, $view_mode) {
845
  $bundle = field_extract_bundle($entity_type, $bundle);
846

847 848
  field_ui_inactive_message($entity_type, $bundle);
  $admin_path = _field_ui_bundle_admin_path($entity_type, $bundle);
849 850

  // Gather type information.
851
  $instances = field_info_instances($entity_type, $bundle);
852
  $field_types = field_info_field_types();
853
  $extra_fields = field_info_extra_fields($entity_type, $bundle, 'display');
854

855 856 857 858
  $form_state += array(
    'formatter_settings_edit' => NULL,
  );

859
  $form += array(
860
    '#entity_type' => $entity_type,
861
    '#bundle' => $bundle,
862
    '#view_mode' => $view_mode,
863
    '#fields' => array_keys($instances),
864
    '#extra' => array_keys($extra_fields),
865 866
  );

867
  if (empty($instances) && empty($extra_fields)) {
868 869 870 871
    drupal_set_message(t('There are no fields yet added. You can add new fields on the <a href="@link">Manage fields</a> page.', array('@link' => url($admin_path . '/fields'))), 'warning');
    return $form;
  }

872
  $table = array(
873
    '#type' => 'field_ui_table',
874
    '#tree' => TRUE,
875 876 877 878 879 880 881 882 883 884 885
    '#header' => array(
      t('Field'),
      t('Weight'),
      t('Parent'),
      t('Label'),
      array('data' => t('Format'), 'colspan' => 3),
    ),
    '#regions' => array(
      'visible' => array('message' => t('No field is displayed.')),
      'hidden' => array('title' => t('Hidden'), 'message' => t('No field is hidden.')),
    ),
886
    '#parent_options' => array(),
887 888 889 890
    '#attributes' => array(
      'class' => array('field-ui-overview'),
      'id' => 'field-display-overview',
    ),
891
    // Add Ajax wrapper.
892 893
    '#prefix' => '<div id="field-display-overview-wrapper">',
    '#suffix' => '</div>',
894 895 896
  );

  $field_label_options = array(
897 898 899 900
    'above' => t('Above'),
    'inline' => t('Inline'),
    'hidden' => t('<Hidden>'),
  );
901 902 903 904 905
  $extra_visibility_options = array(
    'visible' => t('Visible'),
    'hidden' => t('Hidden'),
  );

906
  // Field rows.
907
  foreach ($instances as $name => $instance) {
908
    $field = field_info_field($instance['field_name']);
909
    $display = $instance['display'][$view_mode];
910 911 912 913 914 915 916 917 918 919 920 921 922
    $table[$name] = array(
      '#attributes' => array('class' => array('draggable', 'tabledrag-leaf')),
      '#row_type' => 'field',
      '#region_callback' => 'field_ui_display_overview_row_region',
      '#js_settings' => array(
        'rowHandler' => 'field',
        'defaultFormatter' => $field_types[$field['type']]['default_formatter'],
      ),
      'human_name' => array(
        '#markup' => check_plain($instance['label']),
      ),
      'weight' => array(
        '#type' => 'textfield',
923 924
        '#title' => t('Weight for @title', array('@title' => $instance['label'])),
        '#title_display' => 'invisible',
925 926 927 928 929 930 931
        '#default_value' => $display['weight'],
        '#size' => 3,
        '#attributes' => array('class' => array('field-weight')),
      ),
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
932 933
          '#title' => t('Label display for @title', array('@title' => $instance['label'])),
          '#title_display' => 'invisible',
934
          '#options' => $table['#parent_options'],
935
          '#empty_value' => '',
936 937 938 939 940 941 942 943 944 945 946
          '#attributes' => array('class' => array('field-parent')),
          '#parents' => array('fields', $name, 'parent'),
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
          '#default_value' => $name,
          '#attributes' => array('class' => array('field-name')),
        ),
      ),
      'label' => array(
        '#type' => 'select',
947 948
        '#title' => t('Label display for @title', array('@title' => $instance['label'])),
        '#title_display' => 'invisible',
949 950 951
        '#options' => $field_label_options,
        '#default_value' => $display['label'],
      ),
952
    );
953 954 955

    $formatter_options = field_ui_formatter_options($field['type']);
    $formatter_options['hidden'] = t('<Hidden>');
956 957 958
    $table[$name]['format'] = array(
      'type' => array(
        '#type' => 'select',
959 960
        '#title' => t('Formatter for @title', array('@title' => $instance['label'])),
        '#title_display' => 'invisible',
961 962 963 964
        '#options' => $formatter_options,
        '#default_value' => $display['type'],
        '#parents' => array('fields', $name, 'type'),
        '#attributes' => array('class' => array('field-formatter-type')),
965
      ),
966
      'settings_edit_form' => array(),
967
    );
968

969 970 971 972
    // Formatter settings.

    // Check the currently selected formatter, and merge persisted values for
    // formatter settings.
973 974
    if (isset($form_state['values']['fields'][$name]['type'])) {
      $formatter_type = $form_state['values']['fields'][$name]['type'];
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    }
    else {
      $formatter_type = $display['type'];
    }
    if (isset($form_state['formatter_settings'][$name])) {
      $settings = $form_state['formatter_settings'][$name];
    }
    else {
      $settings = $display['settings'];
    }
    $settings += field_info_formatter_settings($formatter_type);

    $instance['display'][$view_mode]['type'] = $formatter_type;
    $formatter = field_info_formatter_types($formatter_type);
    $instance['display'][$view_mode]['module'] = $formatter['module'];
    $instance['display'][$view_mode]['settings'] = $settings;

    // Base button element for the various formatter settings actions.
    $base_button = array(
994
      '#submit' => array('field_ui_display_overview_multistep_submit'),
995
      '#ajax' => array(
996
        'callback' => 'field_ui_display_overview_multistep_js',
997 998 999 1000 1001 1002 1003 1004 1005
        'wrapper' => 'field-display-overview-wrapper',
        'effect' => 'fade',
      ),
      '#field_name' => $name,
    );

    if ($form_state['formatter_settings_edit'] == $name) {
      // We are currently editing this field's formatter settings. Display the
      // settings form and submit buttons.
1006
      $table[$name]['format']['settings_edit_form'] = array();
1007 1008

      $settings_form = array();
1009
      $function = $formatter['module'] . '_field_formatter_settings_form';
1010 1011 1012 1013 1014 1015 1016
      if (function_exists($function)) {
        $settings_form = $function($field, $instance, $view_mode, $form, $form_state);
      }

      if ($settings_form) {
        $table[$name]['format']['#cell_attributes'] = array('colspan' => 3);
        $table[$name]['format']['settings_edit_form'] = array(
1017 1018
          '#type' => 'container',
          '#attributes' => array('class' => array('field-formatter-settings-edit-form')),
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
          '#parents' => array('fields', $name, 'settings_edit_form'),
          'label' => array(
            '#markup' => t('Format settings:') . ' <span class="formatter-name">' . $formatter['label'] . '</span>',
          ),
          'settings' => $settings_form,
          'actions' => array(
            '#type' => 'actions',
            'save_settings' => $base_button + array(
              '#type' => 'submit',
              '#name' => $name . '_formatter_settings_update',
              '#value' => t('Update'),
              '#op' => 'update',
            ),
            'cancel_settings' => $base_button + array(
              '#type' => 'submit',
              '#name' => $name . '_formatter_settings_cancel',
              '#value' => t('Cancel'),
              '#op' => 'cancel',
              // Do not check errors for the 'Cancel' button, but make sure we
              // get the value of the 'formatter type' select.
              '#limit_validation_errors' => array(array('fields', $name, 'type')),
            ),
          ),
1042
        );
1043
        $table[$name]['#attributes']['class'][] = 'field-formatter-settings-editing';
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
      }
    }
    else {
      // Display a summary of the current formatter settings.
      $summary = module_invoke($formatter['module'], 'field_formatter_settings_summary', $field, $instance, $view_mode);
      $table[$name]['settings_summary'] = array();
      $table[$name]['settings_edit'] = array();
      if ($summary) {
        $table[$name]['settings_summary'] = array(
          '#markup' => '<div class="field-formatter-summary">' . $summary . '</div>',
1054
          '#cell_attributes' => array('class' => array('field-formatter-summary-cell')),
1055 1056 1057 1058 1059 1060 1061
        );
        $table[$name]['settings_edit'] = $base_button + array(
          '#type' => 'image_button',
          '#name' => $name . '_formatter_settings_edit',
          '#src' => 'misc/configure.png',
          '#attributes' => array('class' => array('field-formatter-settings-edit'), 'alt' => t('Edit')),
          '#op' => 'edit',
1062 1063 1064
          // Do not check errors for the 'Edit' button, but make sure we get
          // the value of the 'formatter type' select.
          '#limit_validation_errors' => array(array('fields', $name, 'type')),
1065 1066 1067 1068