You are here

class SocialMediaLinksFieldDefaultFormatter in Social Media Links Block and Field 8.2

Plugin implementation of the 'social_media_links_field_default' formatter.

Plugin annotation


@FieldFormatter(
  id = "social_media_links_field_default",
  label = @Translation("Default"),
  field_types = {
    "social_media_links_field",
  }
)

Hierarchy

Expanded class hierarchy of SocialMediaLinksFieldDefaultFormatter

File

modules/social_media_links_field/src/Plugin/Field/FieldFormatter/SocialMediaLinksFieldDefaultFormatter.php, line 23

Namespace

Drupal\social_media_links_field\Plugin\Field\FieldFormatter
View source
class SocialMediaLinksFieldDefaultFormatter extends FormatterBase {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $platforms = $this
      ->getPlatformsWithValues($items);
    if (count($platforms) < 1) {
      return [];
    }
    $iconset_style = IconsetBase::explodeStyle($items
      ->getSetting('iconset'));
    $iconset = $this
      ->getIconset($iconset_style['iconset']);
    $link_attributes = $this
      ->getSetting('link_attributes');
    foreach ($link_attributes as $key => $value) {
      if ($value === '<none>') {
        unset($link_attributes[$key]);
      }
    }
    foreach ($platforms as $platform_id => $platform) {
      $platforms[$platform_id]['element'] = (array) $iconset['instance']
        ->getIconElement($platform['instance'], $iconset_style['style']);
      $platforms[$platform_id]['attributes'] = new Attribute($link_attributes);
      if (!empty($platform['instance']
        ->getDescription())) {
        $platforms[$platform_id]['attributes']
          ->setAttribute('aria-label', $this
          ->t($platform['instance']
          ->getDescription()));
        $platforms[$platform_id]['attributes']
          ->setAttribute('title', $this
          ->t($platform['instance']
          ->getDescription()));
      }
    }
    $output = [
      '#theme' => 'social_media_links_platforms',
      '#platforms' => $platforms,
      '#appearance' => $this
        ->getSetting('appearance'),
      '#attached' => [
        'library' => [
          'social_media_links/social_media_links.theme',
        ],
      ],
    ];
    if ($iconset['instance']
      ->getPath() === 'library' && (array) ($library = $iconset['instance']
      ->getLibrary())) {
      $output['#attached']['library'] = array_merge_recursive($output['#attached']['library'], $library);
    }
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'appearance' => [],
      'link_attributes' => [],
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->getSettings();
    $element['appearance'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Appearance'),
      '#tree' => TRUE,
    ];
    $element['appearance']['orientation'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Orientation'),
      '#options' => [
        'v' => $this
          ->t('vertical'),
        'h' => $this
          ->t('horizontal'),
      ],
      '#default_value' => isset($config['appearance']['orientation']) ? $config['appearance']['orientation'] : 'h',
    ];
    $element['appearance']['show_name'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show name'),
      '#description' => $this
        ->t('Show the platform name next to the icon.'),
      '#default_value' => isset($config['appearance']['show_name']) ? $config['appearance']['show_name'] : 0,
    ];

    // Link Attributes.
    $element['link_attributes'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Link attributes'),
      '#tree' => TRUE,
    ];
    $element['link_attributes']['target'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Default target'),
      '#default_value' => isset($config['link_attributes']['target']) ? $config['link_attributes']['target'] : '<none>',
      '#options' => [
        '<none>' => $this
          ->t('Remove target attribute'),
        '_blank' => $this
          ->t('Open in a new browser window or tab (_blank)'),
        '_self' => $this
          ->t('Open in the current window (_self)'),
        '_parent' => $this
          ->t('Open in the frame that is superior to the frame the link is in (_parent)'),
        '_top' => $this
          ->t('Cancel all frames and open in full browser window (_top)'),
      ],
    ];
    $element['link_attributes']['rel'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Default rel'),
      '#default_value' => isset($config['link_attributes']['rel']) ? $config['link_attributes']['rel'] : '<none>',
      '#options' => [
        '<none>' => $this
          ->t('Remove rel attribute'),
        'nofollow' => $this
          ->t('Set nofollow'),
      ],
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $config = $this
      ->getSettings();
    $summary = [];
    if (empty($config['appearance']['orientation'])) {
      $config['appearance']['orientation'] = 'h';
    }
    if (empty($config['appearance']['show_name'])) {
      $config['appearance']['show_name'] = 0;
    }
    $orientation = $config['appearance']['orientation'] == 'v' ? $this
      ->t('vertical') : $this
      ->t('horizontal');
    $summary[] = $this
      ->t('Orientation: @orientation', [
      '@orientation' => $orientation,
    ]);
    $show_name = isset($config['appearance']['show_name']) && $config['appearance']['show_name'] ? $this
      ->t('Yes') : $this
      ->t('No');
    $summary[] = $this
      ->t('Show name: @show_name', [
      '@show_name' => $show_name,
    ]);
    return $summary;
  }

  /**
   * Get the platforms that have values.
   *
   * @return array
   *   $platforms.
   */
  protected function getPlatformsWithValues(FieldItemListInterface $items) {
    $platform_settings = $items
      ->getSetting('platforms');
    $all_platforms_available = TRUE;
    foreach ($platform_settings as $platform_id => $platform) {
      if ($platform['enabled']) {
        $all_platforms_available = FALSE;
        break;
      }
    }
    $platforms = [];
    foreach ($items as $item) {

      // We have two possible structures where the platform values can be
      // stored.
      // * If the select widget was used the values are saved in two fields
      // (platform and value).
      // * If the default list widget was used the values are saved in a
      // multidimensional array structure (platform_values).
      if (empty($item->platform_values)) {

        // Select widget fields handling.
        if ($all_platforms_available || isset($platform_settings[$item->platform]['enabled']) && $platform_settings[$item->platform]['enabled']) {
          $platforms[$item->platform] = [
            'value' => $item->value,
            'weight' => $platform_settings[$item->platform]['weight'],
            'description' => $platform_settings[$item->platform]['description'],
          ];
        }
      }
      else {

        // Default list field handling.
        $platform_values = $item->platform_values;
        foreach ($platform_values as $platform_id => $platform_value) {
          if ($all_platforms_available || !empty($platform_value['value']) && isset($platform_settings[$platform_id]['enabled']) && $platform_settings[$platform_id]['enabled']) {
            $platforms[$platform_id] = [
              'value' => $platform_value['value'],
              'weight' => $platform_settings[$platform_id]['weight'],
              'description' => $platform_settings[$platform_id]['description'],
            ];
          }
        }
      }
    }
    return \Drupal::service('plugin.manager.social_media_links.platform')
      ->getPlatformsWithValue($platforms);
  }

  /**
   * Get the iconset.
   *
   * @param string $iconset
   *   The iconset id.
   *
   * @return array
   *   $iconsets
   */
  protected function getIconset($iconset) {
    $iconsets = \Drupal::service('plugin.manager.social_media_links.iconset')
      ->getIconsets();
    return $iconsets[$iconset];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormatterBase::$fieldDefinition protected property The field definition.
FormatterBase::$label protected property The label display setting.
FormatterBase::$settings protected property The formatter settings. Overrides PluginSettingsBase::$settings
FormatterBase::$viewMode protected property The view mode.
FormatterBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 11
FormatterBase::getFieldSetting protected function Returns the value of a field setting.
FormatterBase::getFieldSettings protected function Returns the array of field settings.
FormatterBase::isApplicable public static function Returns if the formatter can be used for the provided field. Overrides FormatterInterface::isApplicable 14
FormatterBase::prepareView public function Allows formatters to load information for field values being displayed. Overrides FormatterInterface::prepareView 2
FormatterBase::view public function Builds a renderable array for a fully themed field. Overrides FormatterInterface::view 1
FormatterBase::__construct public function Constructs a FormatterBase object. Overrides PluginBase::__construct 11
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
SocialMediaLinksFieldDefaultFormatter::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsBase::defaultSettings
SocialMediaLinksFieldDefaultFormatter::getIconset protected function Get the iconset.
SocialMediaLinksFieldDefaultFormatter::getPlatformsWithValues protected function Get the platforms that have values.
SocialMediaLinksFieldDefaultFormatter::settingsForm public function Returns a form to configure settings for the formatter. Overrides FormatterBase::settingsForm
SocialMediaLinksFieldDefaultFormatter::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FormatterBase::settingsSummary
SocialMediaLinksFieldDefaultFormatter::viewElements public function Builds a renderable array for a field value. Overrides FormatterInterface::viewElements
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.