EntityLink.php 1.9 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\comment\Plugin\views\field;

5
use Drupal\Core\Form\FormStateInterface;
6 7 8 9 10 11 12 13
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * Handler for showing comment module's entity links.
 *
 * @ingroup views_field_handlers
 *
14
 * @ViewsField("comment_entity_link")
15 16 17 18 19 20 21 22 23 24
 */
class EntityLink extends FieldPluginBase {

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

25 26 27
  /**
   * {@inheritdoc}
   */
28 29
  protected function defineOptions() {
    $options = parent::defineOptions();
30
    $options['teaser'] = array('default' => FALSE);
31 32 33
    return $options;
  }

34 35 36
  /**
   * {@inheritdoc}
   */
37
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
38 39
    $form['teaser'] = array(
      '#type' => 'checkbox',
40
      '#title' => $this->t('Show teaser-style link'),
41
      '#default_value' => $this->options['teaser'],
42
      '#description' => $this->t('Show the comment link in the form used on standard entity teasers, rather than the full entity form.'),
43 44 45 46 47
    );

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

48 49 50
  /**
   * {@inheritdoc}
   */
51 52 53
  public function query() {}

  /**
54
   * {@inheritdoc}
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
   */
  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']) : '';
  }

}