DisplayOverview.php 23.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Definition of Drupal\field_ui\DisplayOverview.
 */

namespace Drupal\field_ui;

use Drupal\field_ui\OverviewBase;
11 12 13
use Drupal\Core\Entity\EntityManager;
use Drupal\field\Plugin\Type\Formatter\FormatterPluginManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
14 15 16 17 18 19

/**
 * Field UI display overview form.
 */
class DisplayOverview extends OverviewBase {

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
  /**
   * The formatter plugin manager.
   *
   * @var \Drupal\field\Plugin\Type\Formatter\FormatterPluginManager
   */
  protected $formatterManager;

  /**
   * Constructs a new DisplayOverview.
   *
   * @param \Drupal\Core\Entity\EntityManager $entity_manager
   *   The entity manager.
   * @param \Drupal\field\Plugin\Type\Formatter\FormatterPluginManager $formatter_manager
   *   The formatter plugin manager.
   */
  public function __construct(EntityManager $entity_manager, FormatterPluginManager $formatter_manager) {
    parent::__construct($entity_manager);

    $this->formatterManager = $formatter_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('plugin.manager.entity'),
      $container->get('plugin.manager.field.formatter')
    );
  }

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  /**
   * Implements Drupal\field_ui\OverviewBase::getRegions().
   */
  public function getRegions() {
    return array(
      'content' => array(
        'title' => t('Content'),
        'invisible' => TRUE,
        'message' => t('No field is displayed.')
      ),
      'hidden' => array(
        'title' => t('Disabled'),
        'message' => t('No field is hidden.')
      ),
    );
  }

  /**
69
   * Implements \Drupal\Core\Form\FormInterface::getFormID().
70
   */
71 72 73
  public function getFormID() {
    return 'field_ui_display_overview_form';
  }
74

75
  /**
76
   * Implements \Drupal\Core\Form\FormInterface::buildForm().
77
   */
78 79 80
  public function buildForm(array $form, array &$form_state, $entity_type = NULL, $bundle = NULL, $view_mode = NULL) {
    parent::buildForm($form, $form_state, $entity_type, $bundle);

81
    $this->mode = (isset($view_mode) ? $view_mode : 'default');
82 83 84 85
    // Gather type information.
    $instances = field_info_instances($this->entity_type, $this->bundle);
    $field_types = field_info_field_types();
    $extra_fields = field_info_extra_fields($this->entity_type, $this->bundle, 'display');
86
    $entity_display = entity_get_display($this->entity_type, $this->bundle, $this->mode);
87 88 89 90 91 92 93 94

    $form_state += array(
      'formatter_settings_edit' => NULL,
    );

    $form += array(
      '#entity_type' => $this->entity_type,
      '#bundle' => $this->bundle,
95
      '#view_mode' => $this->mode,
96 97 98 99 100
      '#fields' => array_keys($instances),
      '#extra' => array_keys($extra_fields),
    );

    if (empty($instances) && empty($extra_fields)) {
101
      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($this->adminPath . '/fields'))), 'warning');
102 103 104 105 106
      return $form;
    }

    $table = array(
      '#type' => 'field_ui_table',
107
      '#pre_render' => array(array($this, 'tablePreRender')),
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
      '#tree' => TRUE,
      '#header' => array(
        t('Field'),
        t('Weight'),
        t('Parent'),
        t('Label'),
        array('data' => t('Format'), 'colspan' => 3),
      ),
      '#regions' => $this->getRegions(),
      '#parent_options' => drupal_map_assoc(array_keys($this->getRegions())),
      '#attributes' => array(
        'class' => array('field-ui-overview'),
        'id' => 'field-display-overview',
      ),
      // Add Ajax wrapper.
      '#prefix' => '<div id="field-display-overview-wrapper">',
      '#suffix' => '</div>',
    );

    $field_label_options = array(
      'above' => t('Above'),
      'inline' => t('Inline'),
130
      'hidden' => '<' . t('Hidden') . '>',
131 132
    );
    $extra_visibility_options = array(
133
      'visible' => t('Visible'),
134 135 136 137 138
      'hidden' => t('Hidden'),
    );

    // Field rows.
    foreach ($instances as $name => $instance) {
139 140
      $field = field_info_field($name);
      $display_options = $entity_display->getComponent($name);
141

142 143 144
      $table[$name] = array(
        '#attributes' => array('class' => array('draggable', 'tabledrag-leaf')),
        '#row_type' => 'field',
145
        '#region_callback' => array($this, 'getRowRegion'),
146 147 148 149 150 151 152 153 154 155 156
        '#js_settings' => array(
          'rowHandler' => 'field',
          'defaultFormatter' => $field_types[$field['type']]['default_formatter'],
        ),
        'human_name' => array(
          '#markup' => check_plain($instance['label']),
        ),
        'weight' => array(
          '#type' => 'textfield',
          '#title' => t('Weight for @title', array('@title' => $instance['label'])),
          '#title_display' => 'invisible',
157
          '#default_value' => $display_options ? $display_options['weight'] : '0',
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
          '#size' => 3,
          '#attributes' => array('class' => array('field-weight')),
        ),
        'parent_wrapper' => array(
          'parent' => array(
            '#type' => 'select',
            '#title' => t('Label display for @title', array('@title' => $instance['label'])),
            '#title_display' => 'invisible',
            '#options' => $table['#parent_options'],
            '#empty_value' => '',
            '#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',
          '#title' => t('Label display for @title', array('@title' => $instance['label'])),
          '#title_display' => 'invisible',
          '#options' => $field_label_options,
182
          '#default_value' => $display_options ? $display_options['label'] : 'above',
183 184 185
        ),
      );

186
      $formatter_options = $this->formatterManager->getOptions($field['type']);
187
      $formatter_options['hidden'] = '<' . t('Hidden') . '>';
188 189 190 191 192 193
      $table[$name]['format'] = array(
        'type' => array(
          '#type' => 'select',
          '#title' => t('Formatter for @title', array('@title' => $instance['label'])),
          '#title_display' => 'invisible',
          '#options' => $formatter_options,
194
          '#default_value' => $display_options ? $display_options['type'] : 'hidden',
195 196 197 198 199 200 201 202 203
          '#parents' => array('fields', $name, 'type'),
          '#attributes' => array('class' => array('field-formatter-type')),
        ),
        'settings_edit_form' => array(),
      );

      // Check the currently selected formatter, and merge persisted values for
      // formatter settings.
      if (isset($form_state['values']['fields'][$name]['type'])) {
204
        $display_options['type'] = $form_state['values']['fields'][$name]['type'];
205 206
      }
      if (isset($form_state['formatter_settings'][$name])) {
207 208 209 210 211
        $display_options['settings'] = $form_state['formatter_settings'][$name];
      }

      // Get the corresponding formatter object.
      if ($display_options && $display_options['type'] != 'hidden') {
212
        $formatter = $this->formatterManager->getInstance(array(
213
          'instance' => $instance,
214
          'view_mode' => $this->mode,
215 216 217 218 219
          'configuration' => $display_options
        ));
      }
      else {
        $formatter = NULL;
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
      }

      // Base button element for the various formatter settings actions.
      $base_button = array(
        '#submit' => array(array($this, 'multistepSubmit')),
        '#ajax' => array(
          'callback' => array($this, 'multistepAjax'),
          '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.
        $table[$name]['format']['settings_edit_form'] = array();

        if ($formatter) {
          $formatter_type_info = $formatter->getDefinition();

          // Generate the settings form and allow other modules to alter it.
          $settings_form = $formatter->settingsForm($form, $form_state);
          $context = array(
            'formatter' => $formatter,
            'field' => $field,
            'instance' => $instance,
247
            'view_mode' => $this->mode,
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
            'form' => $form,
          );
          drupal_alter('field_formatter_settings_form', $settings_form, $form_state, $context);

          if ($settings_form) {
            $table[$name]['format']['#cell_attributes'] = array('colspan' => 3);
            $table[$name]['format']['settings_edit_form'] = array(
              '#type' => 'container',
              '#attributes' => array('class' => array('field-formatter-settings-edit-form')),
              '#parents' => array('fields', $name, 'settings_edit_form'),
              'label' => array(
                '#markup' => t('Format settings:') . ' <span class="formatter-name">' . $formatter_type_info['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')),
                ),
              ),
            );
            $table[$name]['#attributes']['class'][] = 'field-formatter-settings-editing';
          }
        }
      }
      else {
        $table[$name]['settings_summary'] = array();
        $table[$name]['settings_edit'] = array();

        if ($formatter) {
          // Display a summary of the current formatter settings, and (if the
          // summary is not empty) a button to edit them.
          $summary = $formatter->settingsSummary();

          // Allow other modules to alter the summary.
          $context = array(
            'formatter' => $formatter,
            'field' => $field,
            'instance' => $instance,
299
            'view_mode' => $this->mode,
300 301 302
          );
          drupal_alter('field_formatter_settings_summary', $summary, $context);

303
          if (!empty($summary)) {
304
            $table[$name]['settings_summary'] = array(
305
              '#markup' => '<div class="field-formatter-summary">' . implode('<br />', $summary) . '</div>',
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
              '#cell_attributes' => array('class' => array('field-formatter-summary-cell')),
            );
            $table[$name]['settings_edit'] = $base_button + array(
              '#type' => 'image_button',
              '#name' => $name . '_formatter_settings_edit',
              '#src' => 'core/misc/configure-dark.png',
              '#attributes' => array('class' => array('field-formatter-settings-edit'), 'alt' => t('Edit')),
              '#op' => 'edit',
              // 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')),
              '#prefix' => '<div class="field-formatter-settings-edit-wrapper">',
              '#suffix' => '</div>',
            );
          }
        }
      }
    }

    // Non-field elements.
    foreach ($extra_fields as $name => $extra_field) {
327 328
      $display_options = $entity_display->getComponent($name);

329 330 331
      $table[$name] = array(
        '#attributes' => array('class' => array('draggable', 'tabledrag-leaf')),
        '#row_type' => 'extra_field',
332
        '#region_callback' => array($this, 'getRowRegion'),
333 334 335 336 337 338 339 340
        '#js_settings' => array('rowHandler' => 'field'),
        'human_name' => array(
          '#markup' => check_plain($extra_field['label']),
        ),
        'weight' => array(
          '#type' => 'textfield',
          '#title' => t('Weight for @title', array('@title' => $extra_field['label'])),
          '#title_display' => 'invisible',
341
          '#default_value' => $display_options ? $display_options['weight'] : 0,
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
          '#size' => 3,
          '#attributes' => array('class' => array('field-weight')),
        ),
        'parent_wrapper' => array(
          'parent' => array(
            '#type' => 'select',
            '#title' => t('Parents for @title', array('@title' => $extra_field['label'])),
            '#title_display' => 'invisible',
            '#options' => $table['#parent_options'],
            '#empty_value' => '',
            '#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')),
          ),
        ),
        'empty_cell' => array(
          '#markup' => '&nbsp;',
        ),
        'format' => array(
          'type' => array(
            '#type' => 'select',
            '#title' => t('Visibility for @title', array('@title' => $extra_field['label'])),
            '#title_display' => 'invisible',
            '#options' => $extra_visibility_options,
370
            '#default_value' => $display_options ? 'visible' : 'hidden',
371 372 373 374 375 376 377 378 379 380 381 382
            '#parents' => array('fields', $name, 'type'),
            '#attributes' => array('class' => array('field-formatter-type')),
          ),
        ),
        'settings_summary' => array(),
        'settings_edit' => array(),
      );
    }

    $form['fields'] = $table;

    // Custom display settings.
383
    if ($this->mode == 'default') {
384
      $view_modes = entity_get_view_modes($this->entity_type);
385 386 387
      // Only show the settings if there is more than one view mode.
      if (count($view_modes) > 1) {
        $form['modes'] = array(
388
          '#type' => 'details',
389
          '#title' => t('Custom display settings'),
390
          '#collapsed' => TRUE,
391 392 393 394 395 396 397 398
        );
        // Collect options and default values for the 'Custom display settings'
        // checkboxes.
        $options = array();
        $default = array();
        $view_mode_settings = field_view_mode_settings($this->entity_type, $this->bundle);
        foreach ($view_modes as $view_mode_name => $view_mode_info) {
          $options[$view_mode_name] = $view_mode_info['label'];
399
          if (!empty($view_mode_settings[$view_mode_name]['status'])) {
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
            $default[] = $view_mode_name;
          }
        }
        $form['modes']['view_modes_custom'] = array(
          '#type' => 'checkboxes',
          '#title' => t('Use custom display settings for the following view modes'),
          '#options' => $options,
          '#default_value' => $default,
        );
      }
    }

    // In overviews involving nested rows from contributed modules (i.e
    // field_group), the 'format type' selects can trigger a series of changes
    // in child rows. The #ajax behavior is therefore not attached directly to
    // the selects, but triggered by the client-side script through a hidden
    // #ajax 'Refresh' button. A hidden 'refresh_rows' input tracks the name of
    // affected rows.
    $form['refresh_rows'] = array('#type' => 'hidden');
    $form['refresh'] = array(
      '#type' => 'submit',
      '#value' => t('Refresh'),
      '#op' => 'refresh_table',
      '#submit' => array(array($this, 'multistepSubmit')),
      '#ajax' => array(
        'callback' => array($this, 'multistepAjax'),
        'wrapper' => 'field-display-overview-wrapper',
        'effect' => 'fade',
        // The button stays hidden, so we hide the Ajax spinner too. Ad-hoc
        // spinners will be added manually by the client-side script.
        'progress' => 'none',
      ),
432
      '#attributes' => array('class' => array('element-invisible'))
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    );

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

    $form['#attached']['library'][] = array('field_ui', 'drupal.field_ui');

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

    return $form;
  }

  /**
448
   * Overrides \Drupal\field_ui\OverviewBase::submitForm().
449
   */
450
  public function submitForm(array &$form, array &$form_state) {
451
    $form_values = $form_state['values'];
452
    $display = entity_get_display($this->entity_type, $this->bundle, $this->mode);
453

454
    // Collect data for 'regular' fields.
455 456 457 458
    foreach ($form['#fields'] as $field_name) {
      // Retrieve the stored instance settings to merge with the incoming
      // values.
      $values = $form_values['fields'][$field_name];
459 460 461

      if ($values['type'] == 'hidden') {
        $display->removeComponent($field_name);
462
      }
463 464 465 466 467 468 469 470 471 472 473 474 475 476
      else {
        // Get formatter settings. They lie either directly in submitted form
        // values (if the whole form was submitted while some formatter
        // settings were being edited), or have been persisted in $form_state.
        $settings = array();
        if (isset($values['settings_edit_form']['settings'])) {
          $settings = $values['settings_edit_form']['settings'];
        }
        elseif (isset($form_state['formatter_settings'][$field_name])) {
          $settings = $form_state['formatter_settings'][$field_name];
        }
        elseif ($current_options = $display->getComponent($field_name)) {
          $settings = $current_options['settings'];
        }
477

478 479 480
        // Only save settings actually used by the selected formatter.
        $default_settings = field_info_formatter_settings($values['type']);
        $settings = array_intersect_key($settings, $default_settings);
481

482 483 484 485 486 487 488
        $display->setComponent($field_name, array(
          'label' => $values['label'],
          'type' => $values['type'],
          'weight' => $values['weight'],
          'settings' => $settings,
        ));
      }
489 490
    }

491
    // Collect data for 'extra' fields.
492
    foreach ($form['#extra'] as $name) {
493 494 495 496 497 498 499 500
      if ($form_values['fields'][$name]['type'] == 'hidden') {
        $display->removeComponent($name);
      }
      else {
        $display->setComponent($name, array(
          'weight' => $form_values['fields'][$name]['weight'],
        ));
      }
501 502
    }

503 504 505 506
    // Save the display.
    $display->save();

    // Handle the 'view modes' checkboxes if present.
507
    if ($this->mode == 'default' && !empty($form_values['view_modes_custom'])) {
508
      $entity_info = entity_get_info($this->entity_type);
509
      $view_modes = entity_get_view_modes($this->entity_type);
510 511 512 513
      $bundle_settings = field_bundle_settings($this->entity_type, $this->bundle);
      $view_mode_settings = field_view_mode_settings($this->entity_type, $this->bundle);

      foreach ($form_values['view_modes_custom'] as $view_mode => $value) {
514
        if (!empty($value) && empty($view_mode_settings[$view_mode]['status'])) {
515 516 517 518 519 520 521 522
          // If no display exists for the newly enabled view mode, initialize
          // it with those from the 'default' view mode, which were used so
          // far.
          if (!entity_load('entity_display', $this->entity_type . '.' . $this->bundle . '.' . $view_mode)) {
            $display = entity_get_display($this->entity_type, $this->bundle, 'default')->createCopy($view_mode);
            $display->save();
          }

523
          $view_mode_label = $view_modes[$view_mode]['label'];
524
          $path = $this->entityManager->getAdminPath($this->entity_type, $this->bundle) . "/display/$view_mode";
525 526
          drupal_set_message(t('The %view_mode mode now uses custom display settings. You might want to <a href="@url">configure them</a>.', array('%view_mode' => $view_mode_label, '@url' => url($path))));
        }
527
        $bundle_settings['view_modes'][$view_mode]['status'] = !empty($value);
528 529
      }

530 531 532
      // Save updated bundle settings.
      field_bundle_settings($this->entity_type, $this->bundle, $bundle_settings);
    }
533

534 535 536 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 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    drupal_set_message(t('Your settings have been saved.'));
  }

  /**
   * Form submission handler for multistep buttons.
   */
  public function multistepSubmit($form, &$form_state) {
    $trigger = $form_state['triggering_element'];
    $op = $trigger['#op'];

    switch ($op) {
      case 'edit':
        // Store the field whose settings are currently being edited.
        $field_name = $trigger['#field_name'];
        $form_state['formatter_settings_edit'] = $field_name;
        break;

      case 'update':
        // Store the saved settings, and set the field back to 'non edit' mode.
        $field_name = $trigger['#field_name'];
        $values = $form_state['values']['fields'][$field_name]['settings_edit_form']['settings'];
        $form_state['formatter_settings'][$field_name] = $values;
        unset($form_state['formatter_settings_edit']);
        break;

      case 'cancel':
        // Set the field back to 'non edit' mode.
        unset($form_state['formatter_settings_edit']);
        break;

      case 'refresh_table':
        // If the currently edited field is one of the rows to be refreshed, set
        // it back to 'non edit' mode.
        $updated_rows = explode(' ', $form_state['values']['refresh_rows']);
        if (isset($form_state['formatter_settings_edit']) && in_array($form_state['formatter_settings_edit'], $updated_rows)) {
          unset($form_state['formatter_settings_edit']);
        }
        break;
    }

    $form_state['rebuild'] = TRUE;
  }

  /**
   * Ajax handler for multistep buttons.
   */
  public function multistepAjax($form, &$form_state) {
    $trigger = $form_state['triggering_element'];
    $op = $trigger['#op'];

    // Pick the elements that need to receive the ajax-new-content effect.
    switch ($op) {
      case 'edit':
        $updated_rows = array($trigger['#field_name']);
        $updated_columns = array('format');
        break;

      case 'update':
      case 'cancel':
        $updated_rows = array($trigger['#field_name']);
        $updated_columns = array('format', 'settings_summary', 'settings_edit');
        break;

      case 'refresh_table':
        $updated_rows = array_values(explode(' ', $form_state['values']['refresh_rows']));
        $updated_columns = array('settings_summary', 'settings_edit');
        break;
    }

    foreach ($updated_rows as $name) {
      foreach ($updated_columns as $key) {
        $element = &$form['fields'][$name][$key];
        $element['#prefix'] = '<div class="ajax-new-content">' . (isset($element['#prefix']) ? $element['#prefix'] : '');
        $element['#suffix'] = (isset($element['#suffix']) ? $element['#suffix'] : '') . '</div>';
      }
    }

    // Return the whole table.
    return $form['fields'];
  }
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631

  /**
   * Returns the region to which a row in the display overview belongs.
   *
   * @param array $row
   *   The row element.
   *
   * @return string|null
   *   The region name this row belongs to.
   */
  public function getRowRegion($row) {
    switch ($row['#row_type']) {
      case 'field':
      case 'extra_field':
        return ($row['format']['type']['#value'] == 'hidden' ? 'hidden' : 'content');
    }
  }

632
}