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

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

namespace Drupal\comment\Plugin\views\field;

10
use Drupal\Core\Form\FormStateInterface;
11 12 13 14 15 16 17 18
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * Handler for showing comment module's entity links.
 *
 * @ingroup views_field_handlers
 *
19
 * @ViewsField("comment_entity_link")
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 */
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;
  }

36
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
37 38
    $form['teaser'] = array(
      '#type' => 'checkbox',
39
      '#title' => $this->t('Show teaser-style link'),
40
      '#default_value' => $this->options['teaser'],
41
      '#description' => $this->t('Show the comment link in the form used on standard entity teasers, rather than the full entity form.'),
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 74
    );

    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']) : '';
  }

}