3 namespace Drupal\node\Plugin\views\field;
5 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\views\ResultRow;
8 use Drupal\views\ViewExecutable;
9 use Drupal\views\Plugin\views\display\DisplayPluginBase;
10 use Drupal\views\Plugin\views\field\FieldPluginBase;
13 * Field handler to provide simple renderer that allows linking to a node.
15 * - link_to_node default: Should this field have the checkbox "link to node" enabled by default.
17 * @ingroup views_field_handlers
21 class Node extends FieldPluginBase {
26 public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
27 parent::init($view, $display, $options);
29 // Don't add the additional fields to groupby
30 if (!empty($this->options['link_to_node'])) {
31 $this->additional_fields['nid'] = ['table' => 'node_field_data', 'field' => 'nid'];
38 protected function defineOptions() {
39 $options = parent::defineOptions();
40 $options['link_to_node'] = ['default' => isset($this->definition['link_to_node default']) ? $this->definition['link_to_node default'] : FALSE];
45 * Provide link to node option
47 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
48 $form['link_to_node'] = [
49 '#title' => $this->t('Link this field to the original piece of content'),
50 '#description' => $this->t("Enable to override this field's links."),
51 '#type' => 'checkbox',
52 '#default_value' => !empty($this->options['link_to_node']),
55 parent::buildOptionsForm($form, $form_state);
59 * Prepares link to the node.
62 * The XSS safe string for the link text.
63 * @param \Drupal\views\ResultRow $values
64 * The values retrieved from a single row of a view's query result.
67 * Returns a string for the link text.
69 protected function renderLink($data, ResultRow $values) {
70 if (!empty($this->options['link_to_node']) && !empty($this->additional_fields['nid'])) {
71 if ($data !== NULL && $data !== '') {
72 $this->options['alter']['make_link'] = TRUE;
73 $this->options['alter']['url'] = Url::fromRoute('entity.node.canonical', ['node' => $this->getValue($values, 'nid')]);
74 if (isset($this->aliases['langcode'])) {
75 $languages = \Drupal::languageManager()->getLanguages();
76 $langcode = $this->getValue($values, 'langcode');
77 if (isset($languages[$langcode])) {
78 $this->options['alter']['language'] = $languages[$langcode];
81 unset($this->options['alter']['language']);
86 $this->options['alter']['make_link'] = FALSE;
95 public function render(ResultRow $values) {
96 $value = $this->getValue($values);
97 return $this->renderLink($this->sanitizeValue($value), $values);