xtcentity-2.x-dev/src/Plugin/Field/FieldFormatter/XtcFieldPluginButton.php

src/Plugin/Field/FieldFormatter/XtcFieldPluginButton.php
<?php

namespace Drupal\xtcentity\Plugin\Field\FieldFormatter;

use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Url;
use Drupal\xtc\XtendedContent\API\XtcLoaderHandler;
use Drupal\xtc\XtendedContent\API\XtcLoaderProfile;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Plugin implementation of the 'xtcfield_plugin_button_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "xtcfield_plugin_button_formatter",
 *   label = @Translation("Button"),
 *   field_types = {
 *     "xtcfield_plugin_profile"
 *   },
 *   quickedit = {
 *     "editor" = "plain_text"
 *   }
 * )
 */
class XtcFieldPluginButton extends FormatterBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The button formatter settings.
   *
   * @var ImmutableConfig
   */
  protected $config;

  /**
   * Construct a xtcfield_plugin_button_formatter object.
   *
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param FieldDefinitionInterface $field_definition
   *   Defines an interface for entity field definitions.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
   * @param array $third_party_settings
   *   Any third party settings.
   * @param EntityTypeManagerInterface $entity_type_manager
   *   Entity manager service.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritDoc}.
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
      $configuration['third_party_settings'],
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'show_custom_label' => FALSE,
      'custom_label' => '',
      'show_description' => FALSE,
      'advanced_settings' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = [];
    $settings = $this->getSettings();

    $form['show_custom_label'] = [
      '#type' => 'checkbox',
      '#title' => $this->t("Show Custom Label?"),
      '#attributes' => [
        'id' => 'show-custom-label',
      ],
      '#default_value' => $settings['show_custom_label'],
      '#states' => [
        'visible' => [
          '#show-description' => ['checked' => FALSE],
        ],
      ],
    ];

    $form['custom_label'] = [
      '#type' => 'textfield',
      '#title' => $this->t("Custom Label"),
      '#states' => [
        'visible' => [
          '#show-custom-label' => ['checked' => TRUE],
        ],
      ],
      '#default_value' => $settings['custom_label'],
    ];
    $form['advanced_settings'] = [
      '#type' => 'textarea',
      '#title' => $this->t("Advanced settings"),
      '#default_value' => $settings['advanced_settings'],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    $settings = $this->getSettings();

    $summary['show_custom_label'] = $this->t(
      "<strong>Show custom label?</strong>: @result",
      ['@result' => (bool) $settings['show_custom_label'] ? $this->t("Yes") : $this->t("No")]
    );
    if($settings['show_custom_label']) {
      $summary['custom_label'] = "<strong>Custom label</strong>: " . $settings['custom_label'];
    }
    $summary['advanced_settings'] = $this->t(
      "<strong>Advanced settings</strong>: @result",
      ['@result' => (bool) !empty($settings['advanced_settings']) ? $this->t("defined") : $this->t("undefined")]
    );
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $handler = $this->getHandler($item);
      if (in_array($handler->pluginId, ['dir_set'])) {
        $advSettings = Yaml::decode($this->getSetting('advanced_settings'));
      }

      $link_title = $this->getLabel($item);
      $elements[$delta] = [
        '#type' => 'link',
        '#title' => $link_title,
        '#attributes' => [
          'class' => ['button'],
        ],
        '#disabled' => ! \Drupal::currentUser()->hasPermission('administer xtended content entities'),
        '#url' => $this->getUrl($item),
      ];
    }

    return $elements;
  }

  /**
   * @param $item
   *
   * @return \Drupal\xtc\PluginManager\XtcHandler\XtcHandlerPluginBase|null
   */
  protected function getHandler($item) {
    $handler = NULL;
    $profileName = $item->getValue()['value'];
    $profile = XtcLoaderProfile::load($profileName);
    if(!empty($profile['handler'])){
      $handler = XtcLoaderHandler::get($profile['handler']);
    }
    return $handler;
  }

  /**
   * Gets the url.
   *
   * @param \Drupal\Core\Field\FieldItemInterface $item
   *
   * @return \Drupal\Core\Url
   */
  protected function getUrl(FieldItemInterface $item) {
    $url = NULL;
    $settings = $this->getSettings();
    if(!empty($item->getValue()['uri'])) {
      $url = Url::fromUri($item->getValue()['uri']);
      // Set the attributes of the url.
      $url->setOption(
        'attributes', [
          'class' => $this->getClass(),
        ]
      );
    } else {
      $options = [
        'xtc' => $item->getEntity()->id(),
        'content_entity_type' => 'node',
        'content' => \Drupal::routeMatch()->getParameter('node')->id() ?? NULL,
      ];
        $url = Url::fromRoute('xtcentity.ajax.button', $options);
    }
    return $url;
  }

  /**
   * Gets the label of the button.
   *
   * @param \Drupal\Core\Field\FieldItemInterface $item
   *
   * @return string
   */
  protected function getLabel(FieldItemInterface $item) {
    $settings = $this->getSettings();
    $label = "";

    if ((bool) $settings['show_custom_label']) {
      $label = $this->t($settings['custom_label']);
    }
    else {
      // If it is a link field, we get the text.
      $label = $item->getEntity()->get('name')->getString();
    }

    return $label;
  }

  /**
   * Gets the class of the formatter.
   *
   * @return mixed
   */
  protected function getClass() {
    return [];
  }

}

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

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