EntityLink.php 1.89 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<?php

/**
 * @file
 * Contains \Drupal\comment\Plugin\views\field\EntityLink.
 */

namespace Drupal\comment\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * Handler for showing comment module's entity links.
 *
 * @ingroup views_field_handlers
 *
18
 * @ViewsField("comment_entity_link")
19 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
 */
class EntityLink extends FieldPluginBase {

  /**
   * Stores the result of node_view_multiple for all rows to reuse it later.
   *
   * @var array
   */
  protected $build;

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['teaser'] = array('default' => FALSE, 'bool' => TRUE);
    return $options;
  }

  public function buildOptionsForm(&$form, &$form_state) {
    $form['teaser'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show teaser-style link'),
      '#default_value' => $this->options['teaser'],
      '#description' => t('Show the comment link in the form used on standard entity teasers, rather than the full entity form.'),
    );

    parent::buildOptionsForm($form, $form_state);
  }

  public function query() {}

  /**
   * Implements \Drupal\views\Plugin\views\field\FieldPluginBase::pre_render().
   */
  public function preRender(&$values) {
    // Render all nodes, so you can grep the comment links.
    $entities = array();
    foreach ($values as $row) {
      $entity = $row->_entity;
      $entities[$entity->id()] = $entity;
    }
    if ($entities) {
      $this->build = entity_view_multiple($entities, $this->options['teaser'] ? 'teaser' : 'full');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
    $entity = $this->getEntity($values);

    // Only render the links, if they are defined.
    return !empty($this->build[$entity->id()]['links']['comment__comment']) ? drupal_render($this->build[$entity->id()]['links']['comment__comment']) : '';
  }

}