You are here

public function View::addDisplay in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/views/src/Entity/View.php \Drupal\views\Entity\View::addDisplay()
  2. 10 core/modules/views/src/Entity/View.php \Drupal\views\Entity\View::addDisplay()

Adds a new display handler to the view, automatically creating an ID.

Parameters

string $plugin_id: (optional) The plugin type from the Views plugin annotation. Defaults to 'page'.

string $title: (optional) The title of the display. Defaults to NULL.

string $id: (optional) The ID to use, e.g., 'default', 'page_1', 'block_2'. Defaults to NULL.

Return value

string|bool The key to the display in $view->display, or FALSE if no plugin ID was provided.

Overrides ViewEntityInterface::addDisplay

File

core/modules/views/src/Entity/View.php, line 151

Class

View
Defines a View configuration entity class.

Namespace

Drupal\views\Entity

Code

public function addDisplay($plugin_id = 'page', $title = NULL, $id = NULL) {
  if (empty($plugin_id)) {
    return FALSE;
  }
  $plugin = Views::pluginManager('display')
    ->getDefinition($plugin_id);
  if (empty($plugin)) {
    $plugin['title'] = t('Broken');
  }
  if (empty($id)) {
    $id = $this
      ->generateDisplayId($plugin_id);

    // Generate a unique human-readable name by inspecting the counter at the
    // end of the previous display ID, e.g., 'page_1'.
    if ($id !== 'default') {
      preg_match("/[0-9]+/", $id, $count);
      $count = $count[0];
    }
    else {
      $count = '';
    }
    if (empty($title)) {

      // If there is no title provided, use the plugin title, and if there are
      // multiple displays, append the count.
      $title = $plugin['title'];
      if ($count > 1) {
        $title .= ' ' . $count;
      }
    }
  }
  $display_options = [
    'display_plugin' => $plugin_id,
    'id' => $id,
    // Cast the display title to a string since it is an object.
    // @see \Drupal\Core\StringTranslation\TranslatableMarkup
    'display_title' => (string) $title,
    'position' => $id === 'default' ? 0 : count($this->display),
    'display_options' => [],
  ];

  // Add the display options to the view.
  $this->display[$id] = $display_options;
  return $id;
}