Drupal 8 - Internal Link, les fonctions utiles

Internal Link, les fonctions utiles

A la fin du précédent article concernant la série sur la Création d'un module avec Drupal 8, nous avons finalisé le formulaire de notre type d'entité internal_link, puis nous avons implémenté la fonction postLoad de notre classe d'entité.

Avant de passer à la suite, à savoir l'implémentation de la classe InternalLinkListBuilder, nous allons d'abord ajouter quelques fonctions utiles à notre entité. Ces fonctions vont permettre par la suite de pouvoir récupérer des informations pertinentes sur notre entité.

Quatre fonctions vont être nécessaire pour la suite du travail:

public function isVisible() {...}
public function getFinalUrl() {...}
public function getUrlData($name = NULL, $list_builder = FALSE) {...}
public function getHighlightedData($name = NULL) {...}

Ces différentes fonctions vont servir à effectuer des tests et retourner des données depuis l'entité elle-même.

  • isVisible va tester si l'entité doit être utilisée pour le remplacement de mots sur la page courante;
  • getFinalUrl va retourner l'url finale qui sera utilisée par l'entité;
  • getUrlData va retourner un objet de type Link qui remplacera le mot spécifié dans le champ "Word/Phrase";
  • getHighlightedData va retourner la chaine de caractère qui remplacera le mot spécifié dans le champ "Word/Phrase", dans le cas ou la configuration implique de surligner le mot plutôt que de le remplacer par un lien;

Voyons maintenant le code de ces différentes fonctions

isVisible

  public function isVisible() {
    static $current_path, $path = NULL;
 
    if (!isset($path)) {
      $current_path = \Drupal::service('path.current')->getPath();
      $path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
 
      $current_path = ltrim($current_path, '/');
      $path = ltrim($path, '/');
    }
 
    $url = $this->getFinalUrl();
    if ($url == $current_path || $url == $path) {
      return FALSE;
    }
 
    // 1 = only listed pages
    $visibility = $this->getVisibility();
    $except_list = $this->getExceptList();
    $match = FALSE;
    if (!empty($except_list)) {
      $path_matcher = \Drupal::service('path.matcher');
      $match = $path_matcher->matchPath($path, $except_list);
      if ($path != $current_path) {
        $match = $match || $path_matcher->matchPath($current_path, $except_list);
      }
    }
    return (empty($except_list) || $visibility == $match) ? TRUE : FALSE;
  }

La fonction utiliser les services path.current et path.alias_manager afin de déterminer l'url et l'alias d'url de la page courante. Une fois ces informations récupérées, elle va tout d'abord tester si l'url de l'entité correspond à l'url courante. Si c'est le cas, nul besoin de traiter ce lien. Dans le cas contraire, la fonction va tester la "visibilité" de l'entité. Elle va contrôler que l'entité peut être affichée sur le chemin actuel et retourner une valeur booléene indiquant si le lien sera traité ou non.

getFinalUrl

  public function getFinalUrl() {
    $link = $this->getUrlData();
    $link_url = '';
    if ($link instanceof Link) {
      $url = $link->getUrl();
      if ($url->isRouted()) {
        $link_url = $url->getInternalPath();
      }
      else {
        $link_url = $url->getUri();
      }
    }
    return $link_url;
  }

La fonction récupère le lien final à utiliser, et, selon que ce lien est interne ou externe, va retourner l'url en allant interroger la bonne méthode.

getUrlData

  public function getUrlData($name = NULL, $list_builder = FALSE) {
 
    $list_builder = intval($list_builder);
    static $store = [];
 
    // Prepare entity and try to get current translation
    // if possible.
    $internal_link = $this;
    $language = NULL;
    if ($this->isTranslatable()) {
      $current_language_type = $list_builder ? LanguageInterface::TYPE_INTERFACE : LanguageInterface::TYPE_CONTENT;
      $language = $this->languageManager()->getCurrentLanguage($current_language_type);
      if ($this->hasTranslation($language->getId())) {
        $internal_link = $this->getTranslation($language->getId());
      }
    }
 
    // Get entity name if not passed as parameter
    // to be sure to have a value.
    if (!isset($name)) {
      $name = $internal_link->getName();
    }
 
    if (!isset($store[$list_builder][$name])) {
 
      // Build link options.
      $options = [];
      if (isset($language)) {
        $options['language'] = $language;
      }
      $title = $internal_link->getUrlTitle();
      $options += [
        'attributes' => [
          'title' => $title,
        ],
      ];
      if (!empty($internal_link->getClass())) {
        $options['attributes']['class'] = explode(' ', $internal_link->getClass());
      }
      if (!empty($internal_link->getRel())) {
        $options['attributes']['rel'] = $internal_link->getRel();
      }
 
      // Prepare variables to build URL.
      $url_type = $internal_link->getUrlType();
      $label = '';
      $uri = '';
      $url = NULL;
      switch ($url_type) {
 
        // We just want to build URL from URI.
        case 'standard' :
          $uri = $internal_link->get('url')->value;
          $label = $name;
          $url = Url::fromUri($uri);
          break;
 
        // We must build URL from selected entity.
        case 'entity' :
          $entity = $this->getEntity();
          $url = $entity->toUrl();
          $uri = $url->getInternalPath();
          $label = $name;
          break;
      }
 
      if (isset($url)) {
        if ($list_builder) {
          // Build title with full entity informations.
          $att = [
            'label: ' . $label,
            'uri: ' . $uri,
          ];
          $attributes = $options['attributes'];
          foreach ($attributes as $key => $value) {
            $att[] = $key . ': ' . (is_array($value) ? implode(' ', $value) : $value);
          }
          $options['attributes']['title'] = implode(chr(13), $att);
        }
 
        // Set options to URL and build final link.
        $url->setOptions($options);
        $store[$list_builder][$name] = Link::fromTextAndUrl($name, $url);
      }
      else {
        $store[$list_builder][$name] = t('No data');
      }
    }
    return $store[$list_builder][$name];
  }

La fonction va d'abord récupérer la bonne traduction du lien, pour ensuite effectuer une série de tests afin de construire le lien selon que l'url est de type "standard" ou "entité". L'argument $name va nous permettre d'indiquer exactement le contenu textuel du lien (dans le cas ou il est insensible à la casse, nous pourrions avoir un texte à remplacer en majuscule alors que la valeur "Word/Phrase" est en minuscule). L'argument $list_builder indique si le lien est utilisé dans un affichage de type liste, ce qui permet de construire un attribut "title" plus conséquent, contenant des informations utiles sur le lien. Dans le cas ou $list_builder est valorisé à FALSE, l'attribut "title" sera rempli avec la valeur du champ "Titre d'url".

Nous stockons la construction du lien dans un tableau statique afin de ne pas avoir à effectuer ce processus à chaque fois que le même lien est demandé lors d'une seule requête.

getHighlightedData

  public function getHighlightedData($name = NULL) {
    static $store = [];
 
    // Prepare entity and try to get current translation
    // if possible.
    $internal_link = $this;
    if ($this->isTranslatable()) {
      $current_language_type = LanguageInterface::TYPE_CONTENT;
      $langcode = $this->languageManager()->getCurrentLanguage($current_language_type)->getId();
      if ($this->hasTranslation($langcode)) {
        $internal_link = $this->getTranslation($langcode);
      }
    }
 
    // Get entity name if not passed as parameter
    // to be sure to have a value.
    if (!isset($name)) {
      $name = $internal_link->getName();
    }
 
    if (!isset($store[$name])) {
      // Compute data to get highlighted word.
      $data = '[span';
      if (!empty($internal_link->getClass())) {
        $data .= ' class="' . $internal_link->getClass() . '"';
      }
      $data .= ']' . $name . '[/span]';
 
      $store[$name] = $data;
    }
    return $store[$name];
  }

La fonction est du même accabit que getUrlData, à ceci près qu'elle va construire non pas un lien mais une chaîne de caractère entourée d'une balise [span]. (Encore une fois, désolé pour l'utilisation des crochets, mon filtre de codage ne semble pas autoriser des balises HTML dans du code PHP...)

La classe InternalLink (presque) finalisée

Voici finalement le code complet (ou presque) de notre classe InternalLink. La classe n'est pas encore totalement finalisée, car nous devrons encore y rajouter une méthode pour la gestion du cache des données, mais notre entité est déjà entièrement fonctionnelle sans ça.

/**
 * @file
 * Contains \Drupal\internal_link\Entity\InternalLink.
 */
 
namespace Drupal\internal_link\Entity;
 
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\Entity;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\internal_link\InternalLinkInterface;
use Drupal\user\UserInterface;
 
/**
 * Defines the Internal link entity.
 *
 * @ingroup internal_link
 *
 * @ContentEntityType(
 *   id = "internal_link",
 *   label = @Translation("Internal link"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\internal_link\InternalLinkListBuilder",
 *     "views_data" = "Drupal\internal_link\Entity\InternalLinkViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\internal_link\Form\InternalLinkForm",
 *       "add" = "Drupal\internal_link\Form\InternalLinkForm",
 *       "edit" = "Drupal\internal_link\Form\InternalLinkForm",
 *       "delete" = "Drupal\internal_link\Form\InternalLinkDeleteForm",
 *     },
 *     "access" = "Drupal\internal_link\InternalLinkAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\internal_link\InternalLinkHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "internal_link",
 *   data_table = "internal_link_field_data",
 *   translatable = TRUE,
 *   admin_permission = "administer internal link entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "uid",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/internal_link/{internal_link}",
 *     "add-form" = "/admin/structure/internal_link/add",
 *     "edit-form" = "/admin/structure/internal_link/{internal_link}/edit",
 *     "delete-form" = "/admin/structure/internal_link/{internal_link}/delete",
 *     "collection" = "/admin/structure/internal_link",
 *   },
 *   field_ui_base_route = "internal_link.settings"
 * )
 */
class InternalLink extends ContentEntityBase implements InternalLinkInterface {
  use EntityChangedTrait;
 
  /**
   * Number of time we found this link to replace in text.
   *
   * @var integer
   */
  private $count = 0;
  /**
   * Get counter.
   *
   * @return integer
   *   The current counter value.
   */
  public function getCount() {
    return $this->count;
  }
  /**
   * Set counter.
   *
   * @param integer $increment
   *   The counter increment.
   */
  public function setCount($increment) {
    $this->count += $increment;
  }
  /**
   * Initialize counter.
   */
  public function initializeCount() {
    $this->count = 0;
  }
 
  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
 
    parent::preCreate($storage_controller, $values);
    $values += [
      'uid' => \Drupal::currentUser()->id(),
    ];
  }
 
  /**
   * Implements postLoad to set correct target type
   * on existing internal links
   *
   * @param EntityStorageInterface $storage
   * @param array $entities
   */
  public static function postLoad(EntityStorageInterface $storage, array &$entities) {
 
    // Iterate on each entity and set
    // correct target_type setting
    foreach ($entities as $id => $entity) {
      $url_entity_type = $entity->url_entity_type->value;
      if (!empty($url_entity_type) && $url_entity_type != '_none') {
        // We must set target type to the field definition (bundle instance)
        // and to the field-storage definition (entity-type instance)
        $current = $entity->entity_id->getFieldDefinition()->getSetting('target_type');
        if ($current != $url_entity_type) {
          $entity->entity_id->getFieldDefinition()->setSetting('target_type', $url_entity_type);
        }
        $current = $entity->entity_id->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type');
        if ($current != $url_entity_type) {
          $entity->entity_id->getFieldDefinition()->getFieldStorageDefinition()->setSetting('target_type', $url_entity_type);
        }
      }
    }
  }
 
 
  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }
 
  /**
   * Get the name as lowercase.
   *
   * @return string
   *   Lower cased name.
   */
  public function getLowerName() {
    return strtolower($this->getName());
  }
 
  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }
 
  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }
 
  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }
 
  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('uid')->entity;
  }
 
  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('uid')->target_id;
  }
 
  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('uid', $uid);
    return $this;
  }
 
  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('uid', $account->id());
    return $this;
  }
 
  /**
   * {@inheritdoc}
   */
  public function isPublished() {
    return (bool) $this->getEntityKey('status');
  }
 
  /**
   * {@inheritdoc}
   */
  public function setPublished($published) {
    $this->set('status', $published ? NODE_PUBLISHED : NODE_NOT_PUBLISHED);
    return $this;
  }
 
 
  /**
   * Get all possible modes.
   *
   * @return array
   *   An associative array with key/label
   */
  public static function getModes() {
    return [
      INTERNAL_LINK_MODE_ALL => t('All modes'),
      INTERNAL_LINK_MODE_MANUAL => t('Manual'),
      INTERNAL_LINK_MODE_AUTO => t('Automatic'),
    ];
  }
 
  /**
   * Retrieve mode.
   *
   * @return integer
   *   The internal link mode to use.
   */
  public function getMode() {
    return $this->get('mode')->value;
  }
 
  /**
   * Get mode label switch mode data.
   *
   * @param integer $mode
   *   The mode as integer.
   *
   * @return string
   *   The mode label
   *
   * @throws \RuntimeException
   * @see InternalLink::getModes().
   */
  public function getModeLabel($mode) {
    $modes = InternalLink::getModes();
    if (isset($modes[$mode])) {
      return $modes[$mode];
    }
    throw new \RuntimeException(t('%mode is not a valid internal-link mode.', ['%mode' => $mode]));
  }
 
  /**
   * Retrieve case sensitive state.
   *
   * @return boolean
   *   Case sensitive state.
   */
  public function getCaseSensitive() {
    return $this->get('case_sensitive')->value;
  }
 
  /**
   * Get all possible url types.
   *
   * @return array
   *   An associative array with key/label
   */
  public static function getUrlTypes() {
    return [
      'standard' => t('Standard'),
      'entity' => t('Entity'),
    ];
  }
 
  /**
   * Get type of url.
   *
   * @return string
   *   The type of URL.
   *
   * @see InternalLink::getUrlTypes().
   */
  public function getUrlType() {
    return $this->get('url_type')->value;
  }
 
  /**
   * Get URL type label switch url type data.
   *
   * @param string $url_type
   *   The type of URL.
   * @return string
   *   The URL type label.
   * @throws \RuntimeException
   */
  public function getUrlTypeLabel($url_type) {
    $url_types = $this->getUrlTypes();
    if (isset($url_types[$url_type])) {
      return $url_types[$url_type];
    }
    throw new \RuntimeException(t('%url_type is not a valid internal-link url type.', ['%url_type' => $url_type]));
  }
 
  /**
   * Get URL value.
   *
   * @return string
   *   The URL value.
   */
  public function getUrl() {
    return $this->get('url')->value;
  }
 
  /**
   * Get the URL entity type.
   *
   * @return string
   *   The type o entity type used to get URL.
   */
  public function getUrlEntityType() {
    return $this->get('url_entity_type')->value;
  }
 
  /**
   * Get the selected entity ID.
   *
   * @return integer
   *   The selected entity ID.
   */
  public function getEntityId() {
    return $this->get('entity_id')->target_id;
  }
 
  /**
   * Get the selected entity.
   *
   * @return EntityInterface
   *   The selected entity if url-type is "entity", else NULL.
   */
  public function getEntity() {
    $entity = NULL;
    if ($this->getUrlType() == 'entity') {
      $entity = $this->entityTypeManager()->getStorage($this->getUrlEntityType())->load($this->getEntityId());
    }
    return $entity;
  }
 
  /**
   * Get title to apply to link.
   *
   * @return string
   *   The title of the link.
   */
  public function getUrlTitle() {
    return $this->get('url_title')->value;
  }
  /**
   * Get class(es) to apply to link.
   *
   * @return string
   *   The class(es) of the link.
   */
  public function getClass() {
    return $this->get('class')->value;
  }
  /**
   * Get relationship to apply to link (rel attribute).
   *
   * @return string
   *   The relationship of the link.
   */
  public function getRel() {
    return $this->get('rel')->value;
  }
 
  /**
   * Get data to display if "Highlight words" setting
   * is requested instead of display complete link.
   *
   * @param string $name
   *   The string to highlight.
   *
   * @return string
   *   The final highlighted link.
   */
  public function getHighlightedData($name = NULL) {
    static $store = [];
 
    // Prepare entity and try to get current translation
    // if possible.
    $internal_link = $this;
    if ($this->isTranslatable()) {
      $current_language_type = LanguageInterface::TYPE_CONTENT;
      $langcode = $this->languageManager()->getCurrentLanguage($current_language_type)->getId();
      if ($this->hasTranslation($langcode)) {
        $internal_link = $this->getTranslation($langcode);
      }
    }
 
    // Get entity name if not passed as parameter
    // to be sure to have a value.
    if (!isset($name)) {
      $name = $internal_link->getName();
    }
 
    if (!isset($store[$name])) {
      // Compute data to get highlighted word.
      $data = '[span';
      if (!empty($internal_link->getClass())) {
        $data .= ' class="' . $internal_link->getClass() . '"';
      }
      $data .= ']' . $name . '[/span]';
 
      $store[$name] = $data;
    }
    return $store[$name];
  }
 
  /**
   * Get URL data to display.
   *
   * @param string $name
   *   The word to use in the link.
   * @param boolean $list_builder
   *   To know if we must embed all informations
   *   in tooltip text or only the title. Useful
   *   when displaying links in administration lists.
   *
   * @return string
   *   The final builded URL.
   */
  public function getUrlData($name = NULL, $list_builder = FALSE) {
 
    $list_builder = intval($list_builder);
    static $store = [];
 
    // Prepare entity and try to get current translation
    // if possible.
    $internal_link = $this;
    $language = NULL;
    if ($this->isTranslatable()) {
      $current_language_type = $list_builder ? LanguageInterface::TYPE_INTERFACE : LanguageInterface::TYPE_CONTENT;
      $language = $this->languageManager()->getCurrentLanguage($current_language_type);
      if ($this->hasTranslation($language->getId())) {
        $internal_link = $this->getTranslation($language->getId());
      }
    }
 
    // Get entity name if not passed as parameter
    // to be sure to have a value.
    if (!isset($name)) {
      $name = $internal_link->getName();
    }
 
    if (!isset($store[$list_builder][$name])) {
 
      // Build link options.
      $options = [];
      if (isset($language)) {
        $options['language'] = $language;
      }
      $title = $internal_link->getUrlTitle();
      $options += [
        'attributes' => [
          'title' => $title,
        ],
      ];
      if (!empty($internal_link->getClass())) {
        $options['attributes']['class'] = explode(' ', $internal_link->getClass());
      }
      if (!empty($internal_link->getRel())) {
        $options['attributes']['rel'] = $internal_link->getRel();
      }
 
      // Prepare variables to build URL.
      $url_type = $internal_link->getUrlType();
      $label = '';
      $uri = '';
      $url = NULL;
      switch ($url_type) {
 
        // We just want to build URL from URI.
        case 'standard' :
          $uri = $internal_link->get('url')->value;
          $label = $name;
          $url = Url::fromUri($uri);
          break;
 
        // We must build URL from selected entity.
        case 'entity' :
          $entity = $this->getEntity();
          $url = $entity->toUrl();
          $uri = $url->getInternalPath();
          $label = $name;
          break;
      }
 
      if (isset($url)) {
        if ($list_builder) {
          // Build title with full entity informations.
          $att = [
            'label: ' . $label,
            'uri: ' . $uri,
          ];
          $attributes = $options['attributes'];
          foreach ($attributes as $key => $value) {
            $att[] = $key . ': ' . (is_array($value) ? implode(' ', $value) : $value);
          }
          $options['attributes']['title'] = implode(chr(13), $att);
        }
 
        // Set options to URL and build final link.
        $url->setOptions($options);
        $store[$list_builder][$name] = Link::fromTextAndUrl($name, $url);
      }
      else {
        $store[$list_builder][$name] = t('No data');
      }
    }
    return $store[$list_builder][$name];
  }
 
  /**
   * Get visibility state.
   *
   * @return boolean
   *   Indicate the visibility state:
   *   - 0 = visible on all pages except listed pages;
   *   - 1 = only visible on listed pages;
   */
  public function getVisibility() {
    return $this->get('visibility')->value;
  }
 
  /**
   * Get exceptions pages list.
   *
   * @return string
   *   List of paths used by visibility settings.
   */
  public function getExceptList() {
    return $this->get('except_list')->value;
  }
 
  /**
   * Get final URL value switch URL data.
   *
   * @return string
   *   The final URL value.
   */
  public function getFinalUrl() {
    $link = $this->getUrlData();
    $link_url = '';
    if ($link instanceof Link) {
      $url = $link->getUrl();
      if ($url->isRouted()) {
        $link_url = $url->getInternalPath();
      }
      else {
        $link_url = $url->getUri();
      }
    }
    return $link_url;
  }
 
  /**
   * Test visibility of entity.
   * We check if the current entity must
   * be applied on the current page.
   *
   * @return boolean
   *   TRUE if the current entity must be added to parsing, else FALSE.
   */
  public function isVisible() {
    static $current_path, $path = NULL;
 
    if (!isset($path)) {
      $current_path = \Drupal::service('path.current')->getPath();
      $path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
 
      $current_path = ltrim($current_path, '/');
      $path = ltrim($path, '/');
    }
 
    $url = $this->getFinalUrl();
    if ($url == $current_path || $url == $path) {
      return FALSE;
    }
 
    // 1 = only listed pages
    $visibility = $this->getVisibility();
    $except_list = $this->getExceptList();
    $match = FALSE;
    if (!empty($except_list)) {
      $path_matcher = \Drupal::service('path.matcher');
      $match = $path_matcher->matchPath($path, $except_list);
      if ($path != $current_path) {
        $match = $match || $path_matcher->matchPath($current_path, $except_list);
      }
    }
    return (empty($except_list) || $visibility == $match) ? TRUE : FALSE;
  }
 
  /**
   * Get weight.
   *
   * @return integer
   *   weight of entity.
   */
  public function getWeight() {
    return $this->get('weight')->value;
  }
 
 
  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
 
    $fields['id'] = BaseFieldDefinition::create('integer')
    ->setLabel(t('ID'))
    ->setDescription(t('The ID of the Internal link entity.'))
    ->setReadOnly(TRUE);
 
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
    ->setLabel(t('UUID'))
    ->setDescription(t('The UUID of the Internal link entity.'))
    ->setReadOnly(TRUE);
 
    $fields['created'] = BaseFieldDefinition::create('created')
    ->setLabel(t('Created'))
    ->setDescription(t('The time that the entity was created.'))
    ->setDisplayOptions('form', [
      'type' => 'datetime_timestamp',
      'weight' => 10,
    ])
    ->setDisplayConfigurable('form', TRUE);
 
    $fields['changed'] = BaseFieldDefinition::create('changed')
    ->setLabel(t('Changed'))
    ->setDescription(t('The time that the entity was last edited.'));
 
 
 
    $fields['langcode'] = BaseFieldDefinition::create('language')
    ->setLabel(t('Language code'))
    ->setDescription(t('The language code for the Internal link entity.'))
    ->setDisplayOptions('form', [
      'type' => 'language_select',
      'weight' => -10,
    ])
    ->setDisplayConfigurable('form', TRUE);
 
 
    $modes = InternalLink::getModes();
 
    $fields['mode'] = BaseFieldDefinition::create('list_integer')
    ->setLabel(t('Mode'))
    ->setDescription(t('The mode of application.'))
    ->setSetting('unsigned', TRUE)
    ->setRequired(TRUE)
    ->setSetting('allowed_values', $modes)
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 0,
    ])
    ->setDisplayOptions('form', [
      'type' => 'options_select',
      'weight' => 0,
    ])
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['name'] = BaseFieldDefinition::create('string')
    ->setLabel(t('Word/Phrase'))
    ->setDescription(t('The word or phrase you wish to convert to a link. This field is case sensitive.'))
    ->setSettings([
      'max_length' => 100,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setTranslatable(TRUE)
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 2,
    ])
    ->setDisplayOptions('form', [
      'type' => 'textfield',
      'weight' => 2,
    ])
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['case_sensitive'] = BaseFieldDefinition::create('boolean')
    ->setLabel(t('Case sensitive'))
    ->setDescription(t('By default Internal Link are case sensitive. Uncheck the checkbox if you want this particular Internal Link to be case insensitive.'))
    ->setDefaultValue(TRUE)
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 4,
    ])
    ->setDisplayOptions('form', [
      'settings' => ['display_label' => TRUE],
      'weight' => 4,
    ])
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['url_type'] = BaseFieldDefinition::create('list_string')
    ->setLabel(t('URL type'))
    ->setDescription(t('The type of URL: standard link or entity link.'))
    ->setRequired(TRUE)
    ->setTranslatable(TRUE)
    ->setSetting('allowed_values', InternalLink::getUrlTypes())
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 4.5,
    ])
    ->setDisplayOptions('form', [
      'type' => 'options_select',
      'weight' => 4.5,
    ])
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['url'] = BaseFieldDefinition::create('string')
    ->setLabel(t('URL'))
    ->setDescription(t('The URL of the page to link to. External links must start with %http or %https and will be open in new window.', ['%http' => 'http://', '%https' => 'https://']))
    ->setTranslatable(TRUE)
    ->setSettings([
      'max_length' => 255,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 4.8,
    ])
    ->setDisplayOptions('form', [
      'type' => 'textfield',
      'weight' => 4.8,
    ])
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);
 
 
    $entity_types = [];
    $etm = \Drupal::entityTypeManager();
    foreach($etm->getDefinitions() as $id => $definition) {
      if (is_a($definition , 'Drupal\Core\Entity\ContentEntityType')
          && $id != 'internal_link') {
        $entity_types[$id] = $definition->getLabel();
      }
    }
 
    $fields['url_entity_type'] = BaseFieldDefinition::create('list_string')
    ->setLabel(t('Entity type'))
    ->setDescription(t('The entity type to find url. Select an entity before search the matching URL.'))
    ->setSetting('allowed_values', $entity_types)
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 5,
    ])
    ->setDisplayOptions('form', [
      'type' => 'options_select',
      'empty_value' => '_none',
      'empty_label' => t('None'),
      'weight' => 5,
    ])
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['entity_id'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Entity'))
    ->setDescription(t('The entity to link to.'))
    ->setTranslatable(TRUE)
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 6,
    ])
    ->setDisplayOptions('form', [
      'type' => 'entity_reference_autocomplete',
      'weight' => 6,
      'settings' => [
        'match_operator' => 'CONTAINS',
        'size' => '60',
        'autocomplete_type' => 'tags',
        'placeholder' => '',
      ],
    ])
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['url_title'] = BaseFieldDefinition::create('string')
    ->setLabel(t('Url title'))
    ->setDescription(t('Title for the above URL. It will be embedded in the created link and appear as a tooltip when hovering the mouse over the link.'))
    ->setTranslatable(TRUE)
    ->setSettings([
      'max_length' => 255,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 8,
    ])
    ->setDisplayOptions('form', [
      'type' => 'textfield',
      'weight' => 8,
    ])
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['class'] = BaseFieldDefinition::create('string')
    ->setLabel(t('Class'))
    ->setDescription(t('Use this to add a class for the link. Default value is "internal-link".'))
    ->setSettings([
      'max_length' => 255,
      'text_processing' => 0,
    ])
    ->setDefaultValue('internal-link')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 10,
    ])
    ->setDisplayOptions('form', [
      'type' => 'textfield',
      'weight' => 10,
    ])
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['rel'] = BaseFieldDefinition::create('string')
    ->setLabel(t('Relationship'))
    ->setDescription(t('Use this to add a rel attribute to the link.'))
    ->setSettings([
      'max_length' => 50,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 12,
    ])
    ->setDisplayOptions('form', [
      'type' => 'textfield',
      'weight' => 12,
    ])
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['visibility'] = BaseFieldDefinition::create('boolean')
    ->setLabel(t('Visibility'))
    ->setDescription(t('Show links on specific pages'))
    ->setSetting('unsigned', TRUE)
    ->setRequired(TRUE)
    ->setDefaultValue(0)
    ->setSetting('on_label', t('Only the listed pages'))
    ->setSetting('off_label', t('All pages except those listed'))
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 14,
    ])
    ->setDisplayOptions('form', [
      'type' => 'options_buttons',
      'weight' => 14,
    ])
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['except_list'] = BaseFieldDefinition::create('string_long')
    ->setLabel(t('Except list'))
    ->setDescription(t('Specify pages by using their paths. Enter one path per line. E.g. node/1.'))
    ->setTranslatable(TRUE)
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 16,
    ])
    ->setDisplayOptions('form', [
      'type' => 'textarea',
      'weight' => 16,
    ])
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);
 
 
    $fields['weight'] = BaseFieldDefinition::create('integer')
    ->setLabel(t('Weight'))
    ->setDescription(t('Weight of the word. Lighter weights are higher up, heavier weights go down.'))
    ->setSetting('unsigned', FALSE)
    ->setRequired(TRUE)
    ->setDefaultValue(0)
    ->setTranslatable(TRUE)
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 18,
    ])
    ->setDisplayOptions('form', [
      'type' => 'number',
      'weight' => 18,
    ]);
 
 
 
 
    $fields['status'] = BaseFieldDefinition::create('boolean')
    ->setLabel(t('Publishing status'))
    ->setDescription(t('A boolean indicating whether the Internal link is published.'))
    ->setDefaultValue(TRUE)
    ->setTranslatable(TRUE)
    ->setDisplayOptions('form', [
      'type' => 'checkbox',
      'weight' => 30,
    ])
    ->setDisplayConfigurable('form', TRUE);
 
    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Authored by'))
    ->setDescription(t('The user ID of author of the Internal link entity.'))
    ->setRevisionable(TRUE)
    ->setSetting('target_type', 'user')
    ->setSetting('handler', 'default')
    ->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')
    ->setTranslatable(TRUE)
    ->setDisplayOptions('view', [
      'label' => 'hidden',
      'type' => 'author',
      'weight' => 32,
    ])
    ->setDisplayOptions('form', [
      'type' => 'entity_reference_autocomplete',
      'weight' => 32,
      'settings' => [
        'match_operator' => 'CONTAINS',
        'size' => '60',
        'autocomplete_type' => 'tags',
        'placeholder' => '',
      ],
    ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);
 
    return $fields;
  }
}

 

Ajouter un commentaire

CAPTCHA
Cette question permet de savoir si vous êtes un visiteur ou un robot de soumission de spams