You are here

class ExtraFieldEntityLinkPlugin in Entity Extra Field 2.0.x

Same name and namespace in other branches
  1. 8 src/Plugin/ExtraFieldType/ExtraFieldEntityLinkPlugin.php \Drupal\entity_extra_field\Plugin\ExtraFieldType\ExtraFieldEntityLinkPlugin

Define the extra field entity link type.

Plugin annotation


@ExtraFieldType(
  id = "entity_link",
  label = @Translation("Entity link")
)

Hierarchy

Expanded class hierarchy of ExtraFieldEntityLinkPlugin

File

src/Plugin/ExtraFieldType/ExtraFieldEntityLinkPlugin.php, line 33

Namespace

Drupal\entity_extra_field\Plugin\ExtraFieldType
View source
class ExtraFieldEntityLinkPlugin extends ExtraFieldTypePluginBase {

  /**
   * The access manager service.
   *
   * @var \Drupal\Core\Access\AccessManagerInterface
   */
  protected $accessManager;

  /**
   * Extra field type view constructor.
   *
   * @param array $configuration
   *   The plugin configuration.
   * @param string $plugin_id
   *   The plugin identifier.
   * @param mixed $plugin_definition
   *   The plugin definition.
   * @param \Drupal\Core\Utility\Token $token
   *   The token service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Routing\RouteMatchInterface $current_route_match
   *   The current route match service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager service.
   * @param \Drupal\Core\Access\AccessManagerInterface $access_manager
   *   The access manager service.
   */
  public function __construct(array $configuration, string $plugin_id, $plugin_definition, Token $token, ModuleHandlerInterface $module_handler, RouteMatchInterface $current_route_match, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, AccessManagerInterface $access_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $token, $module_handler, $current_route_match, $entity_type_manager, $entity_field_manager);
    $this->accessManager = $access_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('token'), $container
      ->get('module_handler'), $container
      ->get('current_route_match'), $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('access_manager'));
  }

  /**
   * {@inheritDoc}
   */
  public function defaultConfiguration() : array {
    return [
      'link_text' => NULL,
      'link_template' => NULL,
      'link_target' => NULL,
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritDoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) : array {
    $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;
  }

  /**
   * Build the render array of the extra field type contents.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity type the extra field is being attached too.
   * @param \Drupal\Core\Entity\Display\EntityDisplayInterface $display
   *   The entity display the extra field is apart of.
   *
   * @return array
   *   The extra field renderable array.
   *
   * @throws \Drupal\Core\Entity\EntityMalformedException
   */
  public function build(EntityInterface $entity, EntityDisplayInterface $display) : array {
    $link = $this
      ->buildEntityLink($entity);

    // Link and Url seem not to have convenience methods for access including
    // cacheability. So inlining a variant of \Drupal\Core\Url::access.
    $accessResult = $this
      ->urlAccessResult($link
      ->getUrl());
    $build = $accessResult
      ->isAllowed() ? $link
      ->toRenderable() : [];
    BubbleableMetadata::createFromObject($accessResult)
      ->applyTo($build);
    return $build;
  }

  /**
   * A copy of \Drupal\Core\Url::access that returns cacheability.
   *
   * @param \Drupal\Core\Url $url
   *   The url.
   * @param \Drupal\Core\Session\AccountInterface|null $account
   *   (optional) Run access checks for this account. Defaults to the current
   *   user.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   Returns url access result object.
   */
  public function urlAccessResult(Url $url, AccountInterface $account = NULL) : AccessResultInterface {
    if ($url
      ->isRouted()) {
      return $this->accessManager
        ->checkNamedRoute($url
        ->getRouteName(), $url
        ->getRouteParameters(), $account, TRUE);
    }
    return AccessResult::allowed();
  }

  /**
   * Build the entity link.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity instance.
   *
   * @return \Drupal\Core\Link
   *   The entity link instance.
   *
   * @throws \Drupal\Core\Entity\EntityMalformedException
   */
  protected function buildEntityLink(EntityInterface $entity) : Link {
    $configuration = $this
      ->getConfiguration();
    return $entity
      ->toLink($configuration['link_text'], $configuration['link_template'], $this
      ->getEntityLinkOptions());
  }

  /**
   * Get the entity link options.
   *
   * @return array
   *   An array of the link options.
   */
  protected function getEntityLinkOptions() : array {
    $options = [];
    $configuration = $this
      ->getConfiguration();
    if ($target = $configuration['link_target']) {
      $options['attributes']['target'] = $target;
    }
    return $options;
  }

  /**
   * Get entity link template options.
   *
   * @return array
   *   An array of the entity template options.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function getEntityLinkTemplateOptions() : array {
    $templates = array_keys($this
      ->getTargetEntityTypeDefinition()
      ->getLinkTemplates());
    return array_combine($templates, $templates);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
ExtraFieldEntityLinkPlugin::$accessManager protected property The access manager service.
ExtraFieldEntityLinkPlugin::build public function Build the render array of the extra field type contents. Overrides ExtraFieldTypePluginInterface::build
ExtraFieldEntityLinkPlugin::buildConfigurationForm public function Form constructor. Overrides ExtraFieldTypePluginBase::buildConfigurationForm
ExtraFieldEntityLinkPlugin::buildEntityLink protected function Build the entity link.
ExtraFieldEntityLinkPlugin::create public static function Creates an instance of the plugin. Overrides ExtraFieldTypePluginBase::create
ExtraFieldEntityLinkPlugin::defaultConfiguration public function Gets default configuration for this plugin. Overrides ExtraFieldTypePluginBase::defaultConfiguration
ExtraFieldEntityLinkPlugin::getEntityLinkOptions protected function Get the entity link options.
ExtraFieldEntityLinkPlugin::getEntityLinkTemplateOptions protected function Get entity link template options.
ExtraFieldEntityLinkPlugin::urlAccessResult public function A copy of \Drupal\Core\Url::access that returns cacheability.
ExtraFieldEntityLinkPlugin::__construct public function Extra field type view constructor. Overrides ExtraFieldTypePluginBase::__construct
ExtraFieldTypePluginBase::$currentRouteMatch protected property
ExtraFieldTypePluginBase::$entityFieldManager protected property
ExtraFieldTypePluginBase::$entityTypeManager protected property
ExtraFieldTypePluginBase::$moduleHandler protected property
ExtraFieldTypePluginBase::$token protected property
ExtraFieldTypePluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 2
ExtraFieldTypePluginBase::extraFieldPluginAjax protected function Get extra field plugin ajax properties.
ExtraFieldTypePluginBase::extraFieldPluginAjaxCallback public function Get extra field plugin ajax.
ExtraFieldTypePluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ExtraFieldTypePluginBase::getEntityFieldReferenceTypes protected function Get entity field reference types.
ExtraFieldTypePluginBase::getEntityTokenData protected function Get entity token data.
ExtraFieldTypePluginBase::getEntityTokenTypes protected function Get entity token types.
ExtraFieldTypePluginBase::getPluginFormStateValue protected function Get plugin form state value.
ExtraFieldTypePluginBase::getTargetEntityTypeBundle protected function Get target entity type bundle.
ExtraFieldTypePluginBase::getTargetEntityTypeDefinition protected function Get target entity type definition.
ExtraFieldTypePluginBase::getTargetEntityTypeId protected function Get target entity type identifier.
ExtraFieldTypePluginBase::label public function Display the extra field plugin label. Overrides ExtraFieldTypePluginInterface::label
ExtraFieldTypePluginBase::processEntityToken protected function Process the entity token text.
ExtraFieldTypePluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ExtraFieldTypePluginBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm 1
ExtraFieldTypePluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 1
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance.
PluginDependencyTrait::moduleHandler protected function Wraps the module handler. 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. 1
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.