View source
<?php
namespace Drupal\entity_extra_field\Plugin\ExtraFieldType;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\Display\EntityDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\entity_extra_field\ExtraFieldTypePluginBase;
class ExtraFieldEntityLinkPlugin extends ExtraFieldTypePluginBase {
public function defaultConfiguration() {
return [
'link_text' => NULL,
'link_template' => NULL,
'link_target' => NULL,
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$configuration = $this
->getConfiguration();
$form['link_template'] = [
'#type' => 'select',
'#title' => $this
->t('Link Template'),
'#require' => TRUE,
'#options' => $this
->getEntityLinkTemplateOptions(),
'#empty_option' => $this
->t('- Select -'),
'#required' => TRUE,
'#default_value' => $configuration['link_template'],
];
$form['link_text'] = [
'#type' => 'textfield',
'#title' => $this
->t('Link Text'),
'#default_value' => $configuration['link_text'],
'#size' => 25,
'#required' => TRUE,
];
$form['link_target'] = [
'#type' => 'select',
'#title' => $this
->t('Link Target'),
'#options' => [
'_blank',
],
'#empty_option' => $this
->t('- Default -'),
'#default_value' => $configuration['link_target'],
];
return $form;
}
public function build(EntityInterface $entity, EntityDisplayInterface $display) {
$link = $this
->buildEntityLink($entity);
$accessResult = $this
->urlAccessResult($link
->getUrl());
$build = $accessResult
->isAllowed() ? $link
->toRenderable() : [];
BubbleableMetadata::createFromObject($accessResult)
->applyTo($build);
return $build;
}
public function urlAccessResult(Url $url, AccountInterface $account = NULL) {
if ($url
->isRouted()) {
$accessManager = \Drupal::service('access_manager');
return $accessManager
->checkNamedRoute($url
->getRouteName(), $url
->getRouteParameters(), $account, TRUE);
}
return AccessResult::allowed();
}
protected function buildEntityLink(EntityInterface $entity) {
$configuration = $this
->getConfiguration();
return $entity
->toLink($configuration['link_text'], $configuration['link_template'], $this
->getEntityLinkOptions());
}
protected function getEntityLinkOptions() {
$options = [];
$configuration = $this
->getConfiguration();
if ($target = $configuration['link_target']) {
$options['attributes']['target'] = $target;
}
return $options;
}
protected function getEntityLinkTemplateOptions() {
$templates = array_keys($this
->getTargetEntityTypeDefinition()
->getLinkTemplates());
return array_combine($templates, $templates);
}
}