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

src/Plugin/Field/FieldFormatter/XtcFieldPluginERButton.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\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter;
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 Drupal\xtcentity\Entity\XtendedContent;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Plugin implementation of the 'xtcfield_plugin_button_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "xtcfield_plugin_er_button_formatter",
 *   label = @Translation("ER Button"),
 *   field_types = {
 *     "entity_reference"
 *   },
 *   quickedit = {
 *     "editor" = "plain_text"
 *   }
 * )
 */
class XtcFieldPluginERButton extends EntityReferenceEntityFormatter {

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

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form, $form_state);
    $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 = parent::settingsSummary();
    $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) {
    $view_mode = $this->getSetting('view_mode');
    $elements = [];

    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
      $item = $items[$delta];
      $handler = $this->getHandler($entity);
      if (in_array($handler->pluginId, ['dir_set'])) {
        $advSettings = Yaml::decode($this->getSetting('advanced_settings'));
      }

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

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

  /**
   * @param \Drupal\Core\Field\FieldItemInterface $item
   * @param \Drupal\xtcentity\Entity\XtendedContent $item
   *
   * @return \Drupal\Core\Url
   */
  protected function getUrl(FieldItemInterface $item, XtendedContent $entity) {
    $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 = [
        'trigger' => $item->getEntity()->get('field_nom_machine')->getString(),
        'content_entity_type' => 'node',
        'content' => \Drupal::routeMatch()->getParameter('node')->id() ?? NULL,
      ];
        $url = Url::fromRoute('xtcentity.ajax.button', $options);
    }
    return $url;
  }

  /**
   * @param \Drupal\xtcentity\Entity\XtendedContent $item
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup|string
   */
  protected function getLabel(XtendedContent $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->getName();
    }

    return $label;
  }

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

}

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

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