Entity.php 2.54 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\views\Plugin\views\area\Entity.
 */

namespace Drupal\views\Plugin\views\area;

10
use Drupal\Core\Form\FormStateInterface;
11 12 13 14 15 16 17 18
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ViewExecutable;

/**
 * Provides an area handler which renders an entity in a certain view mode.
 *
 * @ingroup views_area_handlers
 *
19
 * @ViewsArea("entity")
20
 */
21
class Entity extends TokenizeAreaPluginBase {
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

  /**
   * Stores the entity type of the result entities.
   *
   * @var string
   */
  protected $entityType;

  /**
   * Overrides \Drupal\views\Plugin\views\area\AreaPluginBase::init().
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->entityType = $this->definition['entity_type'];
  }

  /**
39
   * {@inheritdoc}
40 41 42 43
   */
  protected function defineOptions() {
    $options = parent::defineOptions();

44 45 46 47
    // Per default we enable tokenize, as this is the most common use case for
    // this handler.
    $options['tokenize']['default'] = TRUE;

48
    $options['entity_id'] = array('default' => '');
49
    $options['view_mode'] = array('default' => 'default');
50
    $options['bypass_access'] = array('default' => FALSE);
51 52 53 54 55

    return $options;
  }

  /**
56
   * {@inheritdoc}
57
   */
58
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
59 60 61 62
    parent::buildOptionsForm($form, $form_state);

    $form['view_mode'] = array(
      '#type' => 'select',
63
      '#options' => \Drupal::entityManager()->getViewModeOptions($this->entityType),
64 65 66 67 68 69 70 71 72
      '#title' => t('View mode'),
      '#default_value' => $this->options['view_mode'],
    );

    $form['entity_id'] = array(
      '#title' => t('ID'),
      '#type' => 'textfield',
      '#default_value' => $this->options['entity_id'],
    );
73 74 75 76 77 78 79

    $form['bypass_access'] = array(
      '#type' => 'checkbox',
      '#title' => t('Bypass access checks'),
      '#description' => t('If enabled, access permissions for rendering the entity are not checked.'),
      '#default_value' => !empty($this->options['bypass_access']),
    );
80 81 82
  }

  /**
83
   * {@inheritdoc}
84
   */
85
  public function render($empty = FALSE) {
86
    if (!$empty || !empty($this->options['empty'])) {
87
      $entity_id = $this->tokenizeValue($this->options['entity_id']);
88 89
      $entity = entity_load($this->entityType, $entity_id);
      if ($entity && (!empty($this->options['bypass_access']) || $entity->access('view'))) {
90
        return entity_view($entity, $this->options['view_mode']);
91 92 93
      }
    }

94
    return array();
95 96 97
  }

}