You are here

class FieldTimerCountdownFormatter in Field Timer 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/Field/FieldFormatter/FieldTimerCountdownFormatter.php \Drupal\field_timer\Plugin\Field\FieldFormatter\FieldTimerCountdownFormatter

Plugin implementation of the 'field_timer_countdown' formatter.

Plugin annotation


@FieldFormatter(
  id = "field_timer_countdown",
  label = @Translation("jQuery Countdown"),
  field_types = {
    "datetime"
  }
)

Hierarchy

Expanded class hierarchy of FieldTimerCountdownFormatter

File

src/Plugin/Field/FieldFormatter/FieldTimerCountdownFormatter.php, line 25

Namespace

Drupal\field_timer\Plugin\Field\FieldFormatter
View source
class FieldTimerCountdownFormatter extends FieldTimerCountdownFormatterBase implements ContainerFactoryPluginInterface {

  /**
   * Provides language.default service.
   *
   * {@inheritdoc}
   */
  const JS_KEY = 'jquery.countdown';

  /**
   * Provides language.default service.
   *
   * @var \Drupal\Core\Language\LanguageDefault
   */
  protected $languageDefault;

  /**
   * {@inheritdoc}
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, TimeInterface $time, LanguageDefault $languageDefault) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings, $time);
    $this->languageDefault = $languageDefault;
  }

  /**
   * {@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('datetime.time'), $container
      ->get('language.default'));
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    $settings = [
      'use_system_language' => FALSE,
      'regional' => 'en',
      'format' => 'dHMS',
      'layout' => '',
      'compact' => 0,
      'significant' => 0,
      'timeSeparator' => ':',
      'padZeroes' => 0,
    ] + parent::defaultSettings();
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = parent::viewElements($items, $langcode);
    $language = $this
      ->getLanguage($langcode);
    if ($language != 'en') {
      $elements['#attached']['library'][] = 'field_timer/' . static::LIBRARY_NAME . '.' . $language;
    }
    $keys = $this
      ->getItemKeys($items);
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#markup' => '<span class="field-timer-jquery-countdown" data-field-timer-key="' . $keys[$delta] . '" data-timestamp="' . $this
          ->getTimestamp($item) . '"></span>',
      ];
    }
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form, $form_state);
    $useSystemLanguageDescription = $this
      ->t('If this option is checked, it will try to ' . 'use appropriate translation from internal files and fallback to the ' . 'site\'s default language or English if nothing is found. Otherwise it ' . 'provides option \'Region\' to configure which translation to use for ' . 'each language on the site.');
    $form['use_system_language'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Use system language'),
      '#default_value' => $this
        ->getSetting('use_system_language'),
      '#description' => $useSystemLanguageDescription,
      '#attributes' => [
        'class' => [
          'field-timer-use-system-language',
        ],
      ],
    ];
    $form['regional'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Language'),
      '#default_value' => $this
        ->getSetting('regional'),
      '#options' => $this
        ->languageOptions(),
      '#states' => [
        'invisible' => [
          'input.field-timer-use-system-language' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['format'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Format'),
      '#default_value' => $this
        ->getSetting('format'),
      '#description' => $this
        ->t('See <a href=":url" target="_blank">documentation</a> for this parameter.', [
        ':url' => $this
          ->getDocumentationLink([
          'fragment' => 'format',
        ]),
      ]),
    ];
    $form['layout'] = [
      '#type' => 'textarea',
      '#rows' => 3,
      '#cols' => 60,
      '#title' => $this
        ->t('Layout'),
      '#default_value' => $this
        ->getSetting('layout'),
      '#description' => $this
        ->t('See <a href=":url" target="_blank">documentation</a> for this parameter.', [
        ':url' => $this
          ->getDocumentationLink([
          'fragment' => 'layout',
        ]),
      ]),
    ];
    $form['compact'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Display in compact format'),
      '#default_value' => $this
        ->getSetting('compact'),
    ];
    $form['significant'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Granularity'),
      '#options' => range(0, 7),
      '#default_value' => $this
        ->getSetting('significant'),
    ];
    $form['timeSeparator'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Time separator'),
      '#default_value' => $this
        ->getSetting('timeSeparator'),
    ];
    $form['padZeroes'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Pad with zeroes'),
      '#default_value' => $this
        ->getSetting('padZeroes'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = parent::settingsSummary();
    $useSystemLanguage = $this
      ->getSetting('use_system_language');
    $summary[] = $this
      ->t('Use system language: %use_system_language', [
      '%use_system_language' => $useSystemLanguage ? $this
        ->t('Yes') : $this
        ->t('No'),
    ]);
    if (!$useSystemLanguage) {
      $language = $this
        ->getSetting('regional');
      $summary[] = $this
        ->t('Language: %language', [
        '%language' => $this
          ->languageOptions()[$language],
      ]);
    }
    $summary[] = $this
      ->t('Format: %format', [
      '%format' => $this
        ->getSetting('format'),
    ]);
    $summary[] = $this
      ->t('Layout: %layout', [
      '%layout' => $this
        ->getSetting('layout'),
    ]);
    $summary[] = $this
      ->t('Compact: %compact', [
      '%compact' => $this
        ->getSetting('compact') ? $this
        ->t('Yes') : $this
        ->t('No'),
    ]);
    $summary[] = $this
      ->t('Granularity: %significant', [
      '%significant' => $this
        ->getSetting('significant'),
    ]);
    $summary[] = $this
      ->t('Time separator: %timeSeparator', [
      '%timeSeparator' => $this
        ->getSetting('timeSeparator'),
    ]);
    $summary[] = $this
      ->t('Pad with zeroes: %padZeroes', [
      '%padZeroes' => $this
        ->getSetting('padZeroes') ? $this
        ->t('Yes') : $this
        ->t('No'),
    ]);
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  protected function preparePluginSettings(FieldItemInterface $item, $langcode) {
    $settings = parent::preparePluginSettings($item, $langcode);
    unset($settings['use_system_language']);
    $settings['regional'] = $this
      ->getLanguage($langcode);
    return $settings;
  }

  /**
   * Gets language to use for jquery.countdown.
   *
   * @param string $langcode
   *   Language code.
   *
   * @return string
   *   Language code.
   */
  protected function getLanguage($langcode) {

    // Fallback to English.
    $language = 'en';
    if ($this
      ->getSetting('use_system_language')) {
      $languages = $this
        ->languageOptions();

      // Try content language.
      if (isset($languages[$langcode])) {
        $language = $langcode;
      }
      else {
        $defaultLangcode = $this->languageDefault
          ->get()
          ->getId();

        // Try default language.
        if (isset($languages[$defaultLangcode])) {
          $language = $defaultLangcode;
        }
      }
    }
    else {
      $language = $this
        ->getSetting('regional');
    }
    return $language;
  }

  /**
   * Gets language options.
   *
   * @return array
   *   Array of language options.
   */
  protected function languageOptions() {
    return [
      'sq' => t('Albanian'),
      'ar' => t('Arabic'),
      'hy' => t('Armenian'),
      'bn' => t('Bengali/Bangla'),
      'bs' => t('Bosnian'),
      'bg' => t('Bulgarian'),
      'my' => t('Burmese'),
      'ca' => t('Catalan'),
      'zh-CN' => t('Chinese/Simplified'),
      'zh-TW' => t('Chinese/Traditional'),
      'hr' => t('Croatian'),
      'cs' => t('Czech'),
      'da' => t('Danish'),
      'nl' => t('Dutch'),
      'et' => t('Estonian'),
      'en' => t('English'),
      'fa' => t('Farsi/Persian'),
      'fi' => t('Finnish'),
      'fo' => t('Faroese'),
      'fr' => t('French'),
      'gl' => t('Galician'),
      'de' => t('German'),
      'el' => t('Greek'),
      'gu' => t('Gujarati'),
      'he' => t('Hebrew'),
      'hu' => t('Hungarian'),
      'id' => t('Indonesian'),
      'is' => t('Icelandic'),
      'it' => t('Italian'),
      'ja' => t('Japanese'),
      'kn' => t('Kannada'),
      'ko' => t('Korean'),
      'lv' => t('Latvian'),
      'lt' => t('Lithuanian'),
      'mk' => t('Macedonian'),
      'ml' => t('Malayalam'),
      'ms' => t('Malaysian'),
      'nb' => t('Norvegian'),
      'pl' => t('Polish'),
      'pt-BR' => t('Portuguese/Brazilian'),
      'ro' => t('Romanian'),
      'ru' => t('Russian'),
      'sr' => t('Serbian'),
      'sk' => t('Slovak'),
      'sl' => t('Slovenian'),
      'es' => t('Spanish'),
      'sv' => t('Swedish'),
      'th' => t('Thai'),
      'tr' => t('Turkish'),
      'uk' => t('Ukrainian'),
      'ur' => t('Urdu'),
      'uz' => t('Uzbek'),
      'vi' => t('Vietnamese'),
      'cy' => t('Welsh'),
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FieldTimerCountdownFormatter::$languageDefault protected property Provides language.default service.
FieldTimerCountdownFormatter::create public static function Creates an instance of the plugin. Overrides FieldTimerCountdownFormatterBase::create
FieldTimerCountdownFormatter::defaultSettings public static function Defines the default settings for this plugin. Overrides FieldTimerCountdownFormatterBase::defaultSettings
FieldTimerCountdownFormatter::getLanguage protected function Gets language to use for jquery.countdown.
FieldTimerCountdownFormatter::JS_KEY constant Provides language.default service. Overrides FieldTimerJsFormatterBase::JS_KEY
FieldTimerCountdownFormatter::languageOptions protected function Gets language options.
FieldTimerCountdownFormatter::preparePluginSettings protected function Prepares array of settings used to initialize jQuery plugin. Overrides FieldTimerCountdownFormatterBase::preparePluginSettings
FieldTimerCountdownFormatter::settingsForm public function Returns a form to configure settings for the formatter. Overrides FieldTimerCountdownFormatterBase::settingsForm
FieldTimerCountdownFormatter::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FieldTimerCountdownFormatterBase::settingsSummary
FieldTimerCountdownFormatter::viewElements public function Builds a renderable array for a field value. Overrides FieldTimerJsFormatterBase::viewElements
FieldTimerCountdownFormatter::__construct public function FieldTimerCountdownFormatterBase constructor. Overrides FieldTimerCountdownFormatterBase::__construct
FieldTimerCountdownFormatterBase::$time protected property
FieldTimerCountdownFormatterBase::getDocumentationLink protected function
FieldTimerCountdownFormatterBase::LIBRARY_NAME constant Plugin name used to render timer/countdown widget. Overrides FieldTimerJsFormatterBase::LIBRARY_NAME
FieldTimerCountdownFormatterBase::typeOptions protected function
FieldTimerCountdownFormatterBase::TYPE_AUTO constant Formatter types.
FieldTimerJsFormatterBase::$itemKeys protected property Stores set of unique html ids for current items.
FieldTimerJsFormatterBase::generateJsSettings protected function Generates JS settings for the field.
FieldTimerJsFormatterBase::getItemKeys protected function Generates unique ids for the field items.
FieldTimerJsFormatterBase::getTimestamp protected function Retrieves timestamp from field item.
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::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
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
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 2
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
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
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.