improvements-2.x-dev/src/Plugin/ExtraField/Display/ReadMoreLink.php

src/Plugin/ExtraField/Display/ReadMoreLink.php
<?php

namespace Drupal\improvements\Plugin\ExtraField\Display;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Url;
use Drupal\druhels\ArrayHelper;
use Drupal\extra_field_plus\Plugin\ExtraFieldPlusDisplayFormattedBase;

/**
 * @ExtraFieldDisplay(
 *   id = "read_more_link",
 *   label = @Translation("Read More link"),
 *   bundles = {
 *     "node.*",
 *     "taxonomy_term.*",
 *   },
 *   visible = false,
 * )
 */
class ReadMoreLink extends ExtraFieldPlusDisplayFormattedBase {

  /**
   * {@inheritdoc}
   */
  protected static function defaultExtraFieldSettings(): array {
    $values = parent::defaultExtraFieldSettings();

    $values += [
      'text' => 'Read more',
      'url' => '',
      'attributes' => '',
    ];

    return $values;
  }

  /**
   * {@inheritDoc}
   */
  public static function extraFieldSettingsForm(): array {
    $form = [];

    $form['text'] = [
      '#type' => 'textfield',
      '#title' => t('Link text'),
      '#description' => t('In english'),
    ];

    $form['url'] = [
      '#type' => 'textfield',
      '#title' => t('Custom link URL'),
      '#description' => t('Leave empty if you want link to entity page.') . ' ' . t('This field supports tokens.'),
    ];

    $form['attributes'] = [
      '#type' => 'textarea',
      '#title' => t('HTML attributes'),
      '#description' => t('Format') . ': <code>attribute-name: attribute-value</code>',
      '#rows' => 2,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(ContentEntityInterface $entity): array {
    $formatter_settings = $this->getEntityExtraFieldSettings();
    $link_url = $entity->toUrl();

    if ($formatter_settings['url']) {
      $link_url = Url::fromUserInput(\Drupal::token()->replace($formatter_settings['url'], [$entity->getEntityTypeId() => $entity]));
    }

    $attributes = $formatter_settings['attributes'] ? ArrayHelper::formatKeyValueListAsArray($formatter_settings['attributes'], ': ') : [];

    return [
      '#type' => 'link',
      '#title' => t($formatter_settings['text']),
      '#url' => $link_url,
      '#attributes' => ArrayHelper::formatArrayAsAttributes($attributes),
    ];
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc