3 namespace Drupal\file\Plugin\views\field;
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\views\ResultRow;
7 use Drupal\views\ViewExecutable;
8 use Drupal\views\Plugin\views\display\DisplayPluginBase;
9 use Drupal\views\Plugin\views\field\FieldPluginBase;
12 * Field handler to provide simple renderer that allows linking to a file.
14 * @ingroup views_field_handlers
18 class File extends FieldPluginBase {
23 public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
24 parent::init($view, $display, $options);
26 if (!empty($options['link_to_file'])) {
27 $this->additional_fields['uri'] = 'uri';
34 protected function defineOptions() {
35 $options = parent::defineOptions();
36 $options['link_to_file'] = ['default' => FALSE];
41 * Provide link to file option
43 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
44 $form['link_to_file'] = [
45 '#title' => $this->t('Link this field to download the file'),
46 '#description' => $this->t("Enable to override this field's links."),
47 '#type' => 'checkbox',
48 '#default_value' => !empty($this->options['link_to_file']),
50 parent::buildOptionsForm($form, $form_state);
54 * Prepares link to the file.
57 * The XSS safe string for the link text.
58 * @param \Drupal\views\ResultRow $values
59 * The values retrieved from a single row of a view's query result.
62 * Returns a string for the link text.
64 protected function renderLink($data, ResultRow $values) {
65 if (!empty($this->options['link_to_file']) && $data !== NULL && $data !== '') {
66 $this->options['alter']['make_link'] = TRUE;
67 // @todo Wrap in file_url_transform_relative(). This is currently
68 // impossible. As a work-around, we could add the 'url.site' cache context
69 // to ensure different file URLs are generated for different sites in a
70 // multisite setup, including HTTP and HTTPS versions of the same site.
71 // But unfortunately it's impossible to bubble a cache context here.
72 // Fix in https://www.drupal.org/node/2646744.
73 $this->options['alter']['path'] = file_create_url($this->getValue($values, 'uri'));
82 public function render(ResultRow $values) {
83 $value = $this->getValue($values);
84 return $this->renderLink($this->sanitizeValue($value), $values);