Url.php

Same filename in this branch
  1. 11.x core/lib/Drupal/Core/Render/Element/Url.php
  2. 11.x core/lib/Drupal/Core/Url.php
Same filename in other branches
  1. 9 core/modules/views/src/Plugin/views/field/Url.php
  2. 9 core/lib/Drupal/Core/Render/Element/Url.php
  3. 9 core/lib/Drupal/Core/Url.php
  4. 8.9.x core/modules/views/src/Plugin/views/field/Url.php
  5. 8.9.x core/lib/Drupal/Core/Render/Element/Url.php
  6. 8.9.x core/lib/Drupal/Core/Url.php
  7. 10 core/modules/views/src/Plugin/views/field/Url.php
  8. 10 core/lib/Drupal/Core/Render/Element/Url.php
  9. 10 core/lib/Drupal/Core/Url.php

Namespace

Drupal\views\Plugin\views\field

File

core/modules/views/src/Plugin/views/field/Url.php

View source
<?php

namespace Drupal\views\Plugin\views\field;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Url as CoreUrl;
use Drupal\views\Attribute\ViewsField;
use Drupal\views\ResultRow;

/**
 * Field handler to provide simple renderer that turns a URL into a clickable link.
 *
 * @ingroup views_field_handlers
 */
class Url extends FieldPluginBase {
    
    /**
     * {@inheritdoc}
     */
    protected function defineOptions() {
        $options = parent::defineOptions();
        $options['display_as_link'] = [
            'default' => TRUE,
        ];
        return $options;
    }
    
    /**
     * Provide link to the page being visited.
     */
    public function buildOptionsForm(&$form, FormStateInterface $form_state) {
        $form['display_as_link'] = [
            '#title' => $this->t('Display as link'),
            '#type' => 'checkbox',
            '#default_value' => !empty($this->options['display_as_link']),
        ];
        parent::buildOptionsForm($form, $form_state);
    }
    
    /**
     * {@inheritdoc}
     */
    public function render(ResultRow $values) {
        $value = $this->getValue($values);
        if (!empty($this->options['display_as_link'])) {
            // @todo Views should expect and store a leading /. See:
            //   https://www.drupal.org/node/2423913
            return Link::fromTextAndUrl($this->sanitizeValue($value), CoreUrl::fromUserInput('/' . $value))
                ->toString();
        }
        else {
            return $this->sanitizeValue($value, 'url');
        }
    }

}

Classes

Title Deprecated Summary
Url Field handler to provide simple renderer that turns a URL into a clickable link.

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