TitleLink.php 2.14 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
<?php

/**
 * @file
 * Contains \Drupal\aggregator\Plugin\views\field\TitleLink.
 */

namespace Drupal\aggregator\Plugin\views\field;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
12
use Drupal\views\ResultRow;
13 14 15 16 17 18 19 20
use Drupal\views\ViewExecutable;

/**
 * Defines a field handler that turns an item's title into a clickable link to
 * the original source article.
 *
 * @ingroup views_field_handlers
 *
21
 * @ViewsField("aggregator_title_link")
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
 */
class TitleLink extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);

    $this->additional_fields['link'] = 'link';
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['display_as_link'] = array('default' => TRUE);

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, &$form_state) {
    $form['display_as_link'] = array(
      '#title' => t('Display as link'),
      '#type' => 'checkbox',
      '#default_value' => !empty($this->options['display_as_link']),
    );
    parent::buildOptionsForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
60
  public function render(ResultRow $values) {
61
    $value = $this->getValue($values);
62
    return $this->renderLink($this->sanitizeValue($value), $values);
63 64 65 66 67 68 69
  }

  /**
   * Renders aggregator item's title as link.
   *
   * @param string $data
   *   The XSS safe string for the link text.
70 71
   * @param \Drupal\views\ResultRow $values
   *   The values retrieved from a single row of a view's query result.
72
   *
73 74
   * @return string
   *   Returns a string for the link text.
75
   */
76
  protected function renderLink($data, ResultRow $values) {
77 78 79 80 81 82 83 84 85 86 87 88
    $link = $this->getValue($values, 'link');
    if (!empty($this->options['display_as_link'])) {
      $this->options['alter']['make_link'] = TRUE;
      $this->options['alter']['path'] = $link;
      $this->options['alter']['html'] = TRUE;
      $this->options['alter']['absolute'] = TRUE;
    }

    return $data;
  }

}