3 namespace Drupal\views\Plugin\views\field;
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\views\ResultRow;
9 * Field handler to present a link to an entity.
11 * @ingroup views_field_handlers
13 * @ViewsField("entity_link")
15 class EntityLink extends LinkBase {
20 public function render(ResultRow $row) {
21 return $this->getEntity($row) ? parent::render($row) : [];
27 protected function renderLink(ResultRow $row) {
28 if ($this->options['output_url_as_text']) {
29 return $this->getUrlInfo($row)->toString();
31 return parent::renderLink($row);
37 protected function getUrlInfo(ResultRow $row) {
38 $template = $this->getEntityLinkTemplate();
39 return $this->getEntity($row)->toUrl($template)->setAbsolute($this->options['absolute']);
43 * Returns the entity link template name identifying the link route.
46 * The link template name.
48 protected function getEntityLinkTemplate() {
55 protected function getDefaultLabel() {
56 return $this->t('view');
62 protected function defineOptions() {
63 $options = parent::defineOptions();
64 $options['output_url_as_text'] = ['default' => FALSE];
65 $options['absolute'] = ['default' => FALSE];
72 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
73 $form['output_url_as_text'] = [
74 '#type' => 'checkbox',
75 '#title' => $this->t('Output the URL as text'),
76 '#default_value' => $this->options['output_url_as_text'],
79 '#type' => 'checkbox',
80 '#title' => $this->t('Use absolute link (begins with "http://")'),
81 '#default_value' => $this->options['absolute'],
82 '#description' => $this->t('Enable this option to output an absolute link. Required if you want to use the path as a link destination.'),
84 parent::buildOptionsForm($form, $form_state);
85 // Only show the 'text' field if we don't want to output the raw URL.
86 $form['text']['#states']['visible'][':input[name="options[output_url_as_text]"]'] = ['checked' => FALSE];