smsplatform-1.0.x-dev/modules/smsplatform_sendtophone/src/Plugin/Field/FieldFormatter/SmsLinkFormatter.php

modules/smsplatform_sendtophone/src/Plugin/Field/FieldFormatter/SmsLinkFormatter.php
<?php

declare(strict_types=1);

namespace Drupal\smsplatform_sendtophone\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Defines a SMS field formatter.
 *
 * @FieldFormatter(
 *   id = \Drupal\smsplatform_sendtophone\Plugin\Field\FieldFormatter\SmsLinkFormatter::PLUGIN_ID,
 *   label = @Translation("SMS Link"),
 *   field_types = {"text"}
 * )
 */
class SmsLinkFormatter extends FormatterBase {

  public const PLUGIN_ID = 'sms_link';

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected RequestStack $requestStack;

  /**
   * The destination used by the current request.
   *
   * @var string
   */
  protected string $destination;

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];
    foreach ($items as $delta => $item) {
      $text = strip_tags($item->value);
      $this->destination = '';
      $query = $this->requestStack->getCurrentRequest()->query;
      if ($query->has('destination')) {
        $this->destination = $query->get('destination');
      }
      $element[$delta] = [
        '#type' => 'markup',
        'text' => [
          '#type' => 'markup',
          '#markup' => $text,
          '#prefix' => '<span class="sms-sendtophone-inline">',
          '#suffix' => '</span>',
        ],
        'link' => [
          '#type' => 'link',
          '#prefix' => ' (',
          '#suffix' => ')',
          '#title' => $this->t('Send to phone'),
          '#url' => Url::fromRoute(
            'smsplatform_sendtophone.page',
            [
              'type' => 'field',
            ],
            [
              'query' => [
                'text' => $text,
                'destination' => $this->destination,
              ],
            ],
          ),
          '#attributes' => [
            'title' => $this->t('Send this text via SMS.'),
            'class' => 'sms-sendtophone',
          ],
        ],
      ];
    }
    return $element;
  }

}

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

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