ContactLink.php

Same filename in other branches
  1. 9 core/modules/contact/src/Plugin/views/field/ContactLink.php
  2. 8.9.x core/modules/contact/src/Plugin/views/field/ContactLink.php
  3. 11.x core/modules/contact/src/Plugin/views/field/ContactLink.php

Namespace

Drupal\contact\Plugin\views\field

File

core/modules/contact/src/Plugin/views/field/ContactLink.php

View source
<?php

namespace Drupal\contact\Plugin\views\field;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\views\Attribute\ViewsField;
use Drupal\views\Plugin\views\field\LinkBase;
use Drupal\views\ResultRow;

/**
 * Defines a field that links to the user contact page, if access is permitted.
 *
 * @ingroup views_field_handlers
 */
class ContactLink extends LinkBase {
    
    /**
     * {@inheritdoc}
     */
    public function buildOptionsForm(&$form, FormStateInterface $form_state) {
        parent::buildOptionsForm($form, $form_state);
        $form['text']['#title'] = $this->t('Link label');
        $form['text']['#required'] = TRUE;
        $form['text']['#default_value'] = empty($this->options['text']) ? $this->getDefaultLabel() : $this->options['text'];
    }
    
    /**
     * {@inheritdoc}
     */
    protected function getUrlInfo(ResultRow $row) {
        $entity = $this->getEntity($row);
        if (!$entity) {
            return NULL;
        }
        return Url::fromRoute('entity.user.contact_form', [
            'user' => $entity->id(),
        ]);
    }
    
    /**
     * {@inheritdoc}
     */
    protected function renderLink(ResultRow $row) {
        $entity = $this->getEntity($row);
        if (!$entity) {
            return '';
        }
        $this->options['alter']['make_link'] = TRUE;
        $this->options['alter']['url'] = $this->getUrlInfo($row);
        $title = $this->t('Contact %user', [
            '%user' => $entity->label(),
        ]);
        $this->options['alter']['attributes'] = [
            'title' => $title,
        ];
        if (!empty($this->options['text'])) {
            return $this->options['text'];
        }
        else {
            return $title;
        }
    }
    
    /**
     * {@inheritdoc}
     */
    protected function getDefaultLabel() {
        return $this->t('contact');
    }

}

Classes

Title Deprecated Summary
ContactLink Defines a field that links to the user contact page, if access is permitted.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.