You are here

public function SwitchField::build in Display Suite 8.2

Same name and namespace in other branches
  1. 8.4 modules/ds_extras/src/Plugin/DsField/SwitchField.php \Drupal\ds_extras\Plugin\DsField\SwitchField::build()
  2. 8.3 modules/ds_extras/src/Plugin/DsField/SwitchField.php \Drupal\ds_extras\Plugin\DsField\SwitchField::build()

Renders a field.

Overrides DsFieldBase::build

File

modules/ds_extras/src/Plugin/DsField/SwitchField.php, line 55

Class

SwitchField
Plugin that generates a link to switch view mode with via ajax.

Namespace

Drupal\ds_extras\Plugin\DsField

Code

public function build() {
  $settings = $this
    ->getConfiguration();
  if (!empty($settings)) {

    /* @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $this
      ->entity();

    // Basic route parameters.
    $route_parameters = array(
      'entityType' => $entity
        ->getEntityTypeId(),
      'entityId' => $entity
        ->id(),
    );
    $selector = $this
      ->viewMode() == 'default' ? 'full' : $this
      ->viewMode();

    // Basic route options.
    $route_options = array(
      'query' => array(
        'selector' => 'view-mode-' . $selector,
      ),
      'attributes' => array(
        'class' => array(
          'use-ajax',
        ),
      ),
    );
    foreach ($settings['vms'] as $key => $value) {

      // If the label is empty, do not create a link.
      if (!empty($value)) {
        $route_parameters['viewMode'] = $key == 'default' ? 'full' : $key;
        $items[] = \Drupal::l($value, Url::fromRoute('ds_extras.switch_view_mode', $route_parameters, $route_options));
      }
    }
  }
  $output = array();
  if (!empty($items)) {
    $output = array(
      '#theme' => 'item_list',
      '#items' => $items,
      // Add the AJAX library to the field for inline switching support.
      '#attached' => array(
        'library' => array(
          'core/drupal.ajax',
        ),
      ),
    );
  }
  return $output;
}