Skip to content

Instantly share code, notes, and snippets.

@pcambra
Created December 14, 2019 16:40
Show Gist options
  • Save pcambra/0983533ab3a54778f2f0a8b8b7dc495a to your computer and use it in GitHub Desktop.
Save pcambra/0983533ab3a54778f2f0a8b8b7dc495a to your computer and use it in GitHub Desktop.
<?php
namespace Drupal\log\Plugin\views\field;
use Drupal\Core\Entity\EntityMalformedException;
use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
/**
* Field handler to return the Log entity's label.
*
* @ingroup views_field_handlers
*
* @see \Drupal\views\Plugin\views\field\EntityLabel
*
* @ViewsField("log_entity_label")
*/
class LogLabel extends FieldPluginBase {
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['link_to_entity'] = ['default' => FALSE];
return $options;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['link_to_entity'] = [
'#title' => $this->t('Link to entity'),
'#description' => $this->t('Make entity label a link to entity page.'),
'#type' => 'checkbox',
'#default_value' => !empty($this->options['link_to_entity']),
];
parent::buildOptionsForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function query() {
// Leave empty to avoid a query on this field.
}
/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
$entity = $values->_entity;
if (!empty($this->options['link_to_entity'])) {
try {
$this->options['alter']['url'] = $entity->toUrl();
$this->options['alter']['make_link'] = TRUE;
}
catch (UndefinedLinkTemplateException $e) {
$this->options['alter']['make_link'] = FALSE;
}
catch (EntityMalformedException $e) {
$this->options['alter']['make_link'] = FALSE;
}
}
return $this->sanitizeValue($entity->label());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment