FileName.php in File Entity (fieldable files) 8.2
File
src/Plugin/views/field/FileName.php
View source
<?php
namespace Drupal\file_entity\Plugin\views\field;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
class FileName extends FieldPluginBase {
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
if (!empty($this->options['link_to_file'])) {
$this->additional_fields['fid'] = array(
'table' => 'file_managed',
'field' => 'fid',
);
}
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['link_to_file'] = array(
'default' => FALSE,
'bool' => TRUE,
);
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['link_to_file'] = array(
'#title' => t('Link this field to view the file'),
'#description' => t("Enable to override this field's links."),
'#type' => 'checkbox',
'#default_value' => !empty($this->options['link_to_file']),
);
parent::buildOptionsForm($form, $form_state);
}
protected function renderLink($data, ResultRow $values) {
if (!empty($this->options['link_to_file']) && !empty($this->additional_fields['fid'])) {
if ($data !== NULL && $data !== '') {
$this->options['alter']['make_link'] = TRUE;
$this->options['alter']['url'] = Url::fromRoute('entity.file.canonical', [
'file' => $this
->getValue($values, 'fid'),
]);
}
else {
$this->options['alter']['make_link'] = FALSE;
}
}
return $data;
}
public function render(ResultRow $values) {
$value = $this
->getValue($values);
return $this
->renderLink($this
->sanitizeValue($value), $values);
}
}
Classes
Name |
Description |
FileName |
Field handler to provide simple renderer that allows linking to a file. |