field_ui.module 17.5 KB
Newer Older
1
<?php
2

3 4
/**
 * @file
5
 * Allows administrators to attach custom fields to fieldable types.
6 7
 */

8
use Drupal\Core\Entity\EntityInterface;
9
use Drupal\Core\Form\FormStateInterface;
10
use Drupal\Core\Render\Element;
11
use Drupal\Core\Routing\RouteMatchInterface;
12
use Drupal\Core\Entity\EntityViewModeInterface;
13
use Drupal\field_ui\FieldUI;
14
use Drupal\field_ui\Plugin\Derivative\FieldUiLocalTask;
15

16
/**
17
 * Implements hook_help().
18
 */
19
function field_ui_help($route_name, RouteMatchInterface $route_match) {
20 21
  switch ($route_name) {
    case 'help.page.field_ui':
22 23
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
24
      $output .= '<p>' . t('The Field UI module provides an administrative user interface (UI) for attaching and managing fields. Fields can be defined at the content-type level for content items and comments, at the vocabulary level for taxonomy terms, and at the site level for user accounts. Other modules may also enable fields to be defined for their data. Field types (text, image, number, etc.) are defined by modules, and collected and managed by the <a href="@field">Field module</a>. For more information, see the online handbook entry for <a href="@field_ui" target="_blank">Field UI module</a>.', array('@field' => url('admin/help/field'), '@field_ui' => 'http://drupal.org/documentation/modules/field-ui')) . '</p>';
25 26
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
27
      $output .= '<dt>' . t('Planning fields') . '</dt>';
28
      $output .= '<dd>' . t('There are several decisions you will need to make before defining a field for content, comments, etc.:') . '<dl>';
29 30 31 32 33
      $output .= '<dt>' . t('What the field will be called') . '</dt>';
      $output .= '<dd>' . t('A field has a <em>label</em> (the name displayed in the user interface) and a <em>machine name</em> (the name used internally). The label can be changed after you create the field, if needed, but the machine name cannot be changed after you have created the field.') . '</li>';
      $output .= '<dt>' . t('What type of data the field will store') . '</dt>';
      $output .= '<dd>' . t('Each field can store one type of data (text, number, file, etc.). When you define a field, you choose a particular <em>field type</em>, which corresponds to the type of data you want to store. The field type cannot be changed after you have created the field.') . '</dd>';
      $output .= '<dt>' . t('How the data will be input and displayed') . '</dt>';
34
      $output .= '<dd>' . t('Each field type has one or more available <em>widgets</em> associated with it; each widget provides a mechanism for data input when you are editing (text box, select list, file upload, etc.). Each field type also has one or more display options, which determine how the field is displayed to site visitors. The widget and display options can be changed after you have created the field.') . '</dd>';
35 36 37 38
      $output .= '<dt>' . t('How many values the field will store') . '</dt>';
      $output .= '<dd>' . t('You can store one value, a specific maximum number of values, or an unlimited number of values in each field. For example, an employee identification number field might store a single number, whereas a phone number field might store multiple phone numbers. This setting can be changed after you have created the field, but if you reduce the maximum number of values, you may lose information.') . '</dd>';
      $output .= '</dl>';
      $output .= '<dt>' . t('Reusing fields') . '</dt>';
39
      $output .= '<dd>' . t('Once you have defined a field, you can reuse it. For example, if you define a custom image field for one content type, and you need to have an image field with the same parameters on another content type, you can add the same field to the second content type, in the <em>Re-use existing field</em> area of the user interface. You could also add this field to a taxonomy vocabulary, comments, user accounts, etc.') . '</dd>';
40 41 42 43 44 45 46 47 48 49
      $output .= '<dd>' . t('Some settings of a reused field are unique to each use of the field; others are shared across all places you use the field. For example, the label of a text field is unique to each use, while the setting for the number of values is shared.') . '</dd>';
      $output .= '<dd>' . t('There are two main reasons for reusing fields. First, reusing fields can save you time over defining new fields. Second, reusing fields also allows you to display, filter, group, and sort content together by field across content types. For example, the contributed Views module allows you to create lists and tables of content. So if you use the same field on multiple content types, you can create a View containing all of those content types together displaying that field, sorted by that field, and/or filtered by that field.') . '</dd>';
      $output .= '<dt>' . t('Fields on content items') . '</dt>';
      $output .= '<dd>' . t('Fields on content items are defined at the content-type level, on the <em>Manage fields</em> tab of the content type edit page (which you can reach from the <a href="@types">Content types page</a>). When you define a field for a content type, each content item of that type will have that field added to it. Some fields, such as the Title and Body, are provided for you when you create a content type, or are provided on content types created by your installation profile.', array('@types' => url('admin/structure/types'))) . '</dd>';
      $output .= '<dt>' . t('Fields on taxonomy terms') . '</dt>';
      $output .= '<dd>' . t('Fields on taxonomy terms are defined at the taxonomy vocabulary level, on the <em>Manage fields</em> tab of the vocabulary edit page (which you can reach from the <a href="@taxonomy">Taxonomy page</a>). When you define a field for a vocabulary, each term in that vocabulary will have that field added to it. For example, you could define an image field for a vocabulary to store an icon with each term.', array('@taxonomy' => url('admin/structure/taxonomy'))) . '</dd>';
      $output .= '<dt>' . t('Fields on user accounts') . '</dt>';
      $output .= '<dd>' . t('Fields on user accounts are defined on a site-wide basis on the <a href="@fields">Manage fields tab</a> of the <a href="@accounts">Account settings</a> page. When you define a field for user accounts, each user account will have that field added to it. For example, you could add a long text field to allow users to include a biography.', array('@fields' => url('admin/config/people/accounts/fields'), '@accounts' => url('admin/config/people/accounts'))) . '</dd>';
      $output .= '<dt>' . t('Fields on comments') . '</dt>';
      $output .= '<dd>' . t('Fields on comments are defined at the content-type level, on the <em>Comment fields</em> tab of the content type edit page (which you can reach from the <a href="@types">Content types page</a>). When you add a field for comments, each comment on a content item of that type will have that field added to it. For example, you could add a website field to the comments on forum posts, to allow forum commenters to add a link to their website.', array('@types' => url('admin/structure/types'))) . '</dd>';
50
      $output .= '</dl>';
51 52 53 54
      $output .= '<dt>' . t('Managing view modes') . '</dt>';
      $output .= '<dd>' . t('Each content entity can have various "modes" for viewing. For instance, a content item could be viewed in full content mode on its own page, teaser mode in a list, or RSS mode in a feed. You can create, edit the names of, and delete view modes on the <a href="!view-modes">View modes page</a>. Once a view mode has been set up, you can choose and format fields for the view mode within each entity sub-type on the Manage display page. See the <a href="!field_ui">Field UI module help page</a> for more information.', array('!view-modes' => \Drupal::url('field_ui.entity_view_mode_list'), '!field_ui' => \Drupal::url('help.page', array('name' => 'field_ui')))) . '</dd>';
      $output .= '<dt>' . t('Managing form modes') . '</dt>';
      $output .= '<dd>' . t('Each content entity can have various editing forms appropriate for different situations, which are known as "form modes". For instance, you might want to define a quick editing mode that allows users to edit the most important fields, and a full editing mode that gives access to all the fields. You can create, edit the names of, and delete form modes on the <a href="!form-modes">Manage custom form modes page</a>. Once a form mode has been set up, you can choose which fields are available on that form within each entity sub-type on the Manage form display page. See the <a href="!field_ui">Field UI module help page</a> for more information.', array('!form-modes' => \Drupal::url('field_ui.entity_form_mode_list'), '!field_ui' => \Drupal::url('help.page', array('name' => 'field_ui')))) . '</dd>';
55 56
      return $output;

57
    case 'field_ui.list':
58 59 60 61
      return '<p>' . t('This list shows all fields currently in use for easy reference.') . '</p>';
  }
}

62 63 64 65 66 67 68 69 70 71 72 73 74
/**
 * Implements hook_theme().
 */
function field_ui_theme() {
  return array(
    'field_ui_table' => array(
      'render element' => 'elements',
    ),
  );
}

/**
 * Implements hook_element_info().
75 76
 *
 * @todo Remove once https://www.drupal.org/node/2326409 is in.
77 78 79
 */
function field_ui_element_info() {
  return array(
80
    'field_ui_table' => array(
81
      '#theme' => 'field_ui_table',
82
      '#regions' => array('' => array()),
83 84 85 86
    ),
  );
}

87
/**
88
 * Implements hook_entity_type_build().
89
 */
90 91
function field_ui_entity_type_build(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
92 93
  $entity_types['field_config']->setFormClass('delete', 'Drupal\field_ui\Form\FieldConfigDeleteForm');
  $entity_types['field_config']->setListBuilderClass('Drupal\field_ui\FieldConfigListBuilder');
94
  $entity_types['field_storage_config']->setListBuilderClass('Drupal\field_ui\FieldStorageConfigListBuilder');
95 96 97 98

  foreach ($entity_types as $entity_type) {
    if ($bundle = $entity_type->getBundleOf()) {
      $entity_type
99 100 101 102 103
        ->setLinkTemplate('field_ui-fields', "field_ui.overview_$bundle")
        ->setLinkTemplate('field_ui-form-display', "field_ui.form_display_overview_$bundle")
        ->setLinkTemplate('field_ui-display', "field_ui.display_overview_$bundle");
    }
  }
104 105
}

106
/**
107
 * Implements hook_entity_bundle_create().
108
 */
109
function field_ui_entity_bundle_create($entity_type, $bundle) {
110 111
  // When a new bundle is created, the menu needs to be rebuilt to add our
  // menu item tabs.
112
  \Drupal::service('router.builder')->setRebuildNeeded();
113 114
}

115 116 117 118 119 120
/**
 * Implements hook_entity_bundle_rename().
 */
function field_ui_entity_bundle_rename($entity_type, $bundle_old, $bundle_new) {
  // When a bundle is renamed, the menu needs to be rebuilt to add our
  // menu item tabs.
121
  \Drupal::service('router.builder')->setRebuildNeeded();
122 123
}

124
/**
125 126
 * Implements hook_form_FORM_ID_alter().
 *
127
 * Adds a button 'Save and manage fields' to the 'Create content type' form.
128 129 130
 *
 * @see node_type_form()
 * @see field_ui_form_node_type_form_submit()
131
 */
132
function field_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {
133
  // We want to display the button only on add page.
134
  if ($form_state->getFormObject()->getEntity()->isNew()) {
135 136 137 138
    $form['actions']['save_continue'] = $form['actions']['submit'];
    $form['actions']['save_continue']['#value'] = t('Save and manage fields');
    $form['actions']['save_continue']['#weight'] = $form['actions']['save_continue']['#weight'] + 5;
    $form['actions']['save_continue']['#submit'][] = 'field_ui_form_node_type_form_submit';
139 140
    // Hide the 'Save content type' button.
    $form['actions']['submit']['#access'] = FALSE;
141 142 143
  }
}

144
/**
145
 * Implements hook_entity_operation().
146
 */
147 148
function field_ui_entity_operation(EntityInterface $entity) {
  $operations = array();
149
  $info = $entity->getEntityType();
150 151
  // Add manage fields and display links if this entity type is the bundle
  // of another.
152
  if ($bundle_of = $info->getBundleOf()) {
153 154
    $account = \Drupal::currentUser();
    if ($account->hasPermission('administer '. $bundle_of . ' fields')) {
155 156 157
      $operations['manage-fields'] = array(
        'title' => t('Manage fields'),
        'weight' => 15,
158
      ) + $entity->urlInfo('field_ui-fields')->toArray();
159
    }
160
    if ($account->hasPermission('administer '. $bundle_of . ' form display')) {
161 162 163
      $operations['manage-form-display'] = array(
        'title' => t('Manage form display'),
        'weight' => 20,
164
      ) + $entity->urlInfo('field_ui-form-display')->toArray();
165
    }
166
    if ($account->hasPermission('administer '. $bundle_of . ' display')) {
167 168 169
      $operations['manage-display'] = array(
        'title' => t('Manage display'),
        'weight' => 25,
170
      ) + $entity->urlInfo('field_ui-display')->toArray();
171 172
    }
  }
173 174

  return $operations;
175 176
}

177
/**
178
 * Form submission handler for the 'Save and manage fields' button.
179 180
 *
 * @see field_ui_form_node_type_form_alter()
181
 */
182
function field_ui_form_node_type_form_submit($form, FormStateInterface $form_state) {
183
  if ($form_state->getTriggeringElement()['#parents'][0] === 'save_continue' && $route_info = FieldUI::getOverviewRouteInfo('node', $form_state->getValue('type'))) {
184
    $form_state->setRedirectUrl($route_info);
185 186
  }
}
187

188 189 190 191
/**
 * Implements hook_view_mode_presave().
 */
function field_ui_view_mode_presave(EntityViewModeInterface $view_mode) {
192
  \Drupal::service('router.builder')->setRebuildNeeded();
193 194 195 196 197 198
}

/**
 * Implements hook_view_mode_delete().
 */
function field_ui_view_mode_delete(EntityViewModeInterface $view_mode) {
199
  \Drupal::service('router.builder')->setRebuildNeeded();
200
}
201 202 203 204 205 206 207 208 209 210 211 212 213

/**
 * 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'];
214
  $table = array('#type' => 'table');
215 216

  // Add table headers and attributes.
217 218 219
  foreach (array('#header', '#attributes') as $key) {
    if (isset($elements[$key])) {
      $table[$key] = $elements[$key];
220 221 222 223 224 225
    }
  }

  // Determine the colspan to use for region rows, by checking the number of
  // columns in the headers.
  $columns_count = 0;
226
  foreach ($table['#header'] as $header) {
227 228 229 230 231 232 233 234 235
    $columns_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']) && empty($region['invisible'])) {
236
      $table['#rows'][] = array(
237 238 239 240 241 242 243 244 245
        'class' => array('region-title', 'region-' . $region_name_class . '-title'),
        'no_striping' => TRUE,
        'data' => array(
          array('data' => $region['title'], 'colspan' => $columns_count),
        ),
      );
    }
    if (isset($region['message'])) {
      $class = (empty($region['rows_order']) ? 'region-empty' : 'region-populated');
246
      $table['#rows'][] = array(
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        'class' => array('region-message', 'region-' . $region_name_class . '-message', $class),
        'no_striping' => TRUE,
        'data' => array(
          array('data' => $region['message'], 'colspan' => $columns_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'];
      }

      // Render children as table cells.
265
      foreach (Element::children($element) as $cell_key) {
266 267 268 269 270 271 272 273 274 275
        $child = &$element[$cell_key];
        // Do not render a cell for children of #type 'value'.
        if (!(isset($child['#type']) && $child['#type'] == 'value')) {
          $cell = array('data' => drupal_render($child));
          if (isset($child['#cell_attributes'])) {
            $cell += $child['#cell_attributes'];
          }
          $row['data'][] = $cell;
        }
      }
276
      $table['#rows'][] = $row;
277 278 279
    }
  }

280
  return drupal_render($table);
281 282
}

283 284 285 286 287 288 289 290
/**
 * Implements hook_local_tasks_alter().
 */
function field_ui_local_tasks_alter(&$local_tasks) {
  $container = \Drupal::getContainer();
  $local_task = FieldUiLocalTask::create($container, 'field_ui.fields');
  $local_task->alterLocalTasks($local_tasks);
}
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

/**
 * Implements hook_entity_type_alter().
 */
function field_ui_entity_type_alter(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $form_mode = $entity_types['entity_form_mode'];
  $form_mode->setListBuilderClass('Drupal\field_ui\EntityFormModeListBuilder');
  $form_mode->setFormClass('add', 'Drupal\field_ui\Form\EntityFormModeAddForm');
  $form_mode->setFormClass('edit', 'Drupal\field_ui\Form\EntityDisplayModeEditForm');
  $form_mode->setFormClass('delete', 'Drupal\field_ui\Form\EntityDisplayModeDeleteForm');
  $form_mode->set('admin_permission', 'administer display modes');
  $form_mode->setLinkTemplate('delete-form', 'field_ui.entity_form_mode.delete_form');
  $form_mode->setLinkTemplate('edit-form', 'field_ui.entity_form_mode.edit_form');

  $view_mode = $entity_types['entity_view_mode'];
  $view_mode->setListBuilderClass('Drupal\field_ui\EntityDisplayModeListBuilder');
  $view_mode->setFormClass('add', 'Drupal\field_ui\Form\EntityDisplayModeAddForm');
  $view_mode->setFormClass('edit', 'Drupal\field_ui\Form\EntityDisplayModeEditForm');
  $view_mode->setFormClass('delete', 'Drupal\field_ui\Form\EntityDisplayModeDeleteForm');
  $view_mode->set('admin_permission', 'administer display modes');
  $view_mode->setLinkTemplate('delete-form', 'field_ui.entity_view_mode.delete_form');
  $view_mode->setLinkTemplate('edit-form', 'field_ui.entity_view_mode.edit_form');
}