View source
<?php
namespace Drupal\uc_order\Plugin\views\field;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
class FullName extends FieldPluginBase {
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
if (!empty($this->options['link_to_user'])) {
$this->additional_fields['uid'] = [
'table' => 'uc_orders',
'field' => 'uid',
];
}
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['link_to_user'] = [
'default' => FALSE,
'bool' => TRUE,
];
$options['format'] = [
'default' => 'first_last',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['link_to_user'] = [
'#title' => $this
->t('Link this field to its user'),
'#description' => $this
->t("Enable to override this field's links."),
'#type' => 'checkbox',
'#default_value' => $this->options['link_to_user'],
];
$form['format'] = [
'#type' => 'select',
'#title' => $this
->t('Format'),
'#options' => [
'first_last' => $this
->t('First Last'),
'last_c_first' => $this
->t('Last, First'),
'last_first' => $this
->t('Last First'),
],
'#default_value' => $this->options['format'],
];
}
protected function renderLink($data, $values) {
$account = \Drupal::currentUser();
if (!empty($this->options['link_to_user']) && $account
->hasPermission('access user profiles')) {
$this->options['alter']['make_link'] = TRUE;
$this->options['alter']['path'] = 'user/' . $this
->getValue($values, 'uid');
}
return $data;
}
public function render(ResultRow $values) {
$first = $this
->getValue($values);
$last = $this
->getValue($values, 'last_name');
switch ($this->options['format']) {
case 'last_first':
$output = "{$last} {$first}";
case 'last_c_first':
$output = "{$last}, {$first}";
case 'first_last':
$output = "{$first} {$last}";
}
if (isset($output)) {
return $this
->renderLink($this
->sanitizeValue($output), $values);
}
}
}