You are here

class LanguageItem in Custom Language field 8

Plugin implementation of the 'language' field type.

Plugin annotation


@FieldType(
  id = "language_field",
  label = @Translation("Language"),
  description = @Translation("This field stores a language as a Field."),
  default_widget = "languagefield_select",
  default_formatter = "languagefield_default",
  no_ui = FALSE,
  constraints = {
    "ComplexData" = {
      "value" = {
        "Length" = {"max" = 12},
      }
    }
  }
)

Hierarchy

Expanded class hierarchy of LanguageItem

4 files declare their use of LanguageItem
LanguageAutocompleteTagsWidget.php in src/Plugin/Field/FieldWidget/LanguageAutocompleteTagsWidget.php
LanguageAutocompleteWidget.php in src/Plugin/Field/FieldWidget/LanguageAutocompleteWidget.php
LanguageFormatter.php in src/Plugin/Field/FieldFormatter/LanguageFormatter.php
LanguageSelectWidget.php in src/Plugin/Field/FieldWidget/LanguageSelectWidget.php

File

src/Plugin/Field/FieldType/LanguageItem.php, line 33

Namespace

Drupal\languagefield\Plugin\Field\FieldType
View source
class LanguageItem extends LanguageItemBase implements OptionsProviderInterface {

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'value' => [
          'type' => 'varchar_ascii',
          'length' => $field_definition
            ->getSetting('maxlength'),
          'not null' => FALSE,
        ],
      ],
      'indexes' => [
        'value' => [
          'value',
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
    $defaultStorageSettings = [
      'maxlength' => CustomLanguageManager::LANGUAGEFIELD_LANGCODE_MAXLENGTH,
      'language_range' => [
        CustomLanguageManager::LANGUAGEFIELD_LANGUAGES_PREDEFINED => CustomLanguageManager::LANGUAGEFIELD_LANGUAGES_PREDEFINED,
      ],
      'included_languages' => [],
      'excluded_languages' => [],
      'groups' => '',
      // @see callback_allowed_values_function()
      'allowed_values_function' => 'languagefield_allowed_values',
    ] + parent::defaultStorageSettings();
    return $defaultStorageSettings;
  }

  /**
   * Gets the unified keys for Formatter and Widget display settings.
   *
   * @param string $usage
   *   Usage.
   *
   * @return array
   *   Array of options.
   */
  public static function settingsOptions($usage = 'formatter') {
    $options = [];
    $t = \Drupal::translation();
    if (\Drupal::moduleHandler()
      ->moduleExists('languageicons')) {
      if ($usage != 'widget') {
        $options += [
          'icon' => $t
            ->translate('Language icon'),
        ];
      }
    }
    $options += [
      'iso' => $t
        ->translate('ISO 639-code'),
      'name' => $t
        ->translate('Name'),
      'name_native' => $t
        ->translate('Native name'),
    ];
    return $options;
  }

  /**
   * Get language configuration value.
   *
   * @param string $code
   *   Code.
   *
   * @return string
   *   Value.
   */
  public static function getLanguageConfigurationValues($code) {
    switch ($code) {
      case LanguageInterface::LANGCODE_SITE_DEFAULT:
        $language = \Drupal::languageManager()
          ->getDefaultLanguage();
        $value = $language
          ->getId();
        break;
      case LanguageInterface::LANGCODE_NOT_SPECIFIED:
        $value = LanguageInterface::LANGCODE_NOT_SPECIFIED;
        break;
      case 'current_interface':
        $language = \Drupal::languageManager()
          ->getCurrentLanguage();
        $value = $language
          ->getId();
        break;
      case 'authors_default':
        $user = \Drupal::currentUser();
        $language_code = $user
          ->getPreferredLangcode();
        $language = !empty($language_code) ? \Drupal::languageManager()
          ->getLanguage($language_code) : \Drupal::languageManager()
          ->getCurrentLanguage();
        $value = $language
          ->getId();
        break;
      default:
        $value = $code;
    }
    return $value;
  }

  /**
   * {@inheritdoc}
   */
  public function applyDefaultValue($notify = TRUE) {

    // Default to no default value.
    $this
      ->setValue(NULL, $notify);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
    $element = parent::storageSettingsForm($form, $form_state, $has_data);
    $settings = $this
      ->getFieldDefinition()
      ->getFieldStorageDefinition()
      ->getSettings();
    $languages = $this
      ->getPossibleOptions();
    $url_1 = \Drupal::moduleHandler()
      ->moduleExists('language') ? Url::fromRoute('entity.configurable_language.collection', [], [])
      ->toString() : '';
    $url_2 = Url::fromRoute('languagefield.custom_language.collection', [], [])
      ->toString();
    $element['language_range'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Enabled languages'),
      '#description' => $this
        ->t("Installed languages can be maintained on the\n        <a href=':url_1'>Languages</a> page, when Language module is installed. Custom languages can\n        be maintained on the <a href=':url_2'>Custom Languages</a> page. (Options marked with '*' are\n        typically used as default value in a hidden widget.)", [
        ':url_1' => $url_1,
        ':url_2' => $url_2,
      ]),
      '#required' => TRUE,
      '#default_value' => $settings['language_range'],
      '#options' => [
        // The following are from Languagefield.
        CustomLanguageManager::LANGUAGEFIELD_LANGUAGES_PREDEFINED => $this
          ->t('All predefined languages'),
        // self::LANGUAGEFIELD_LANGUAGES_ENABLED =>
        // $this->t('Enabled installed languages (not functioning yet)'),
        // The following are from Drupal\Core\Language\LanguageInterface.
        LanguageInterface::STATE_CONFIGURABLE => $this
          ->t('All installed (enabled) languages (from /admin/config/regional/language)'),
        // const STATE_CONFIGURABLE = 1; -> 'en', 'de'
        CustomLanguageManager::LANGUAGEFIELD_LANGUAGES_CUSTOM => $this
          ->t('All custom languages (from /admin/config/regional/custom_language)'),
        LanguageInterface::STATE_LOCKED => $this
          ->t('All locked languages'),
        // const STATE_LOCKED = 2; -> 'und', 'zxx'
        // const STATE_ALL = 3; -> 'en', 'de', 'und', 'zxx'
        // LanguageInterface::STATE_ALL => $this->t('All installed languages'),
        // const STATE_SITE_DEFAULT = 4; -> 'en'
        // LanguageInterface::STATE_SITE_DEFAULT =>
        // $this->t("The site's default language"),
        // The following are copied from
        // LanguageConfiguration::getDefaultOptions()
        LanguageInterface::LANGCODE_SITE_DEFAULT => $this
          ->t("Site's default language (@language)", [
          '@language' => \Drupal::languageManager()
            ->getDefaultLanguage()
            ->getName(),
        ]),
        LanguageInterface::LANGCODE_NOT_SPECIFIED => $this
          ->t('Language neutral'),
        'current_interface' => $this
          ->t('Current interface language') . '*',
        'authors_default' => $this
          ->t("Author's preferred language") . '*',
      ],
    ];
    $element['included_languages'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Restrict by language'),
      '#default_value' => $settings['included_languages'],
      '#options' => [
        '' => $this
          ->t('- None -'),
      ] + $languages,
      '#description' => $this
        ->t('If no languages are selected, this filter will not be used.'),
      '#multiple' => TRUE,
      '#size' => 10,
    ];
    $element['excluded_languages'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Excluded languages'),
      '#default_value' => $settings['excluded_languages'],
      '#options' => [
        '' => $this
          ->t('- None -'),
      ] + $languages,
      '#description' => $this
        ->t('This removes individual languages from the list.'),
      '#multiple' => TRUE,
      '#size' => 10,
    ];
    $element['groups'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Language groups'),
      '#default_value' => $settings['groups'],
      '#description' => $this
        ->t("Provides a simple way to group common languages. If no groups are provided, no groupings will be used. Enter in the following format:<br/><code>cn,en,ep,ru<br/>African languages|bs,br<br/>Asian languages|cn,km,fil,ja</code>"),
      '#multiple' => TRUE,
      '#size' => 10,
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this
      ->get('value')
      ->getValue();
    return $value === NULL || $value === '';
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = [];

    // @Usage When adding parent::getConstraints(), only English is allowed.
    $max_length = $this
      ->getSetting('max_length');
    if ($max_length) {
      $constraint_manager = \Drupal::typedDataManager()
        ->getValidationConstraintManager();
      $constraints[] = $constraint_manager
        ->create('ComplexData', [
        'value' => [
          'Length' => [
            'max' => $max_length,
            'maxMessage' => $this
              ->t('%name: may not be longer than @max characters.', [
              '%name' => $this
                ->getFieldDefinition()
                ->getLabel(),
              '@max' => $max_length,
            ]),
          ],
        ],
      ]);
    }
    return $constraints;
  }

  /**
   * {@inheritdoc}
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   (optional) The user account for which to filter the possible options.
   *   If omitted, all possible options are returned.
   * @param string $format
   *   Extra parameter for formatting options.
   */
  public function getPossibleOptions(AccountInterface $account = NULL, $format = 'en') {

    // Caching as per https://www.drupal.org/node/2661204
    static $possible_options = [];
    $field_name = $this
      ->getFieldDefinition()
      ->getName();
    if (isset($possible_options[$field_name])) {
      return $possible_options[$field_name];
    }

    // No need to cache this data. It is a hardcoded list.
    $languages = \Drupal::languageManager()
      ->getStandardLanguageList();

    // Add the custom languages to the list.
    $languages += CustomLanguageManager::getCustomLanguageList();

    // Format the array to Options format.
    foreach ($languages as $langcode => $language_names) {
      $language_name = '';
      switch ($format) {
        case 'en':
          $language_name .= $this
            ->t($language_names[0]);
          break;
        case 'loc':
          $language_name .= $language_names[1];
          break;
        case 'both':
          $language_name .= $this
            ->t($language_names[0]);
          if (mb_strlen($language_names[1])) {
            $language_name .= ' (' . $language_names[1] . ')';
          }
          $language_name .= ' [' . $langcode . ']';
          break;
      }
      $possible_options[$field_name][$langcode] = $language_name;
    }
    asort($possible_options[$field_name]);
    return $possible_options[$field_name];
  }

  /**
   * {@inheritdoc}
   */
  public function getPossibleValues(AccountInterface $account = NULL) {
    $options = $this
      ->getPossibleOptions($account);
    return array_keys($options);
  }

  /**
   * {@inheritdoc}
   */
  public function getSettableValues(AccountInterface $account = NULL) {
    $options = $this
      ->getSettableOptions($account);
    return array_keys($options);
  }

  /**
   * {@inheritdoc}
   */
  public function getSettableOptions(AccountInterface $account = NULL) {

    // Caching as per https://www.drupal.org/node/2661204
    static $settable_options;
    $field_name = $this
      ->getFieldDefinition()
      ->getName();
    if (!isset($settable_options[$field_name])) {
      $settings = $this
        ->getFieldDefinition()
        ->getSettings();
      $settable_options[$field_name] = CustomLanguageManager::allowedValues($settings);
    }
    return $settable_options[$field_name];
  }

  /* ************************************
   *  End of use Drupal\Core\TypedData\OptionsProviderInterface.
   */

  /* ************************************
   *  Start of contrib functions.
   */

  /**
   * Gets the Native name. (Should be added to \Drupal\Core\Language\Language.)
   */
  public function getNativeName() {
    $value = $this->value;
    switch ($value) {
      case 'und':
        $name = '';
        break;
      default:
        $standard_languages = \Drupal::languageManager()
          ->getStandardLanguageList();
        $standard_languages += CustomLanguageManager::getCustomLanguageList();
        $name = $standard_languages[$value][1];
        break;
    }
    return $name;
  }

}

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
FieldItemBase::calculateDependencies public static function Calculates dependencies for field items. Overrides FieldItemInterface::calculateDependencies 2
FieldItemBase::calculateStorageDependencies public static function Calculates dependencies for field items on the storage level. Overrides FieldItemInterface::calculateStorageDependencies 1
FieldItemBase::defaultFieldSettings public static function Defines the field-level settings for this plugin. Overrides FieldItemInterface::defaultFieldSettings 7
FieldItemBase::delete public function Defines custom delete behavior for field values. Overrides FieldItemInterface::delete 2
FieldItemBase::deleteRevision public function Defines custom revision delete behavior for field values. Overrides FieldItemInterface::deleteRevision
FieldItemBase::fieldSettingsForm public function Returns a form for the field-level settings. Overrides FieldItemInterface::fieldSettingsForm 7
FieldItemBase::fieldSettingsFromConfigData public static function Returns a settings array in the field type's canonical representation. Overrides FieldItemInterface::fieldSettingsFromConfigData 1
FieldItemBase::fieldSettingsToConfigData public static function Returns a settings array that can be stored as a configuration value. Overrides FieldItemInterface::fieldSettingsToConfigData 1
FieldItemBase::getEntity public function Gets the entity that field belongs to. Overrides FieldItemInterface::getEntity
FieldItemBase::getFieldDefinition public function Gets the field definition. Overrides FieldItemInterface::getFieldDefinition
FieldItemBase::getLangcode public function Gets the langcode of the field values held in the object. Overrides FieldItemInterface::getLangcode
FieldItemBase::getSetting protected function Returns the value of a field setting.
FieldItemBase::getSettings protected function Returns the array of field settings.
FieldItemBase::mainPropertyName public static function Returns the name of the main property, if any. Overrides FieldItemInterface::mainPropertyName 8
FieldItemBase::onDependencyRemoval public static function Informs the plugin that a dependency of the field will be deleted. Overrides FieldItemInterface::onDependencyRemoval 1
FieldItemBase::postSave public function Defines custom post-save behavior for field values. Overrides FieldItemInterface::postSave 2
FieldItemBase::preSave public function Defines custom presave behavior for field values. Overrides FieldItemInterface::preSave 7
FieldItemBase::storageSettingsFromConfigData public static function Returns a settings array in the field type's canonical representation. Overrides FieldItemInterface::storageSettingsFromConfigData 2
FieldItemBase::storageSettingsToConfigData public static function Returns a settings array that can be stored as a configuration value. Overrides FieldItemInterface::storageSettingsToConfigData 2
FieldItemBase::view public function Returns a renderable array for a single field item. Overrides FieldItemInterface::view
FieldItemBase::writePropertyValue protected function Different to the parent Map class, we avoid creating property objects as far as possible in order to optimize performance. Thus we just update $this->values if no property object has been created yet. Overrides Map::writePropertyValue
FieldItemBase::__construct public function Constructs a TypedData object given its definition and context. Overrides TypedData::__construct 1
FieldItemBase::__get public function Magic method: Gets a property value. Overrides FieldItemInterface::__get 2
FieldItemBase::__isset public function Magic method: Determines whether a property is set. Overrides FieldItemInterface::__isset
FieldItemBase::__set public function Magic method: Sets a property value. Overrides FieldItemInterface::__set 1
FieldItemBase::__unset public function Magic method: Unsets a property. Overrides FieldItemInterface::__unset
LanguageItem::applyDefaultValue public function Applies the default value. Overrides LanguageItem::applyDefaultValue
LanguageItem::defaultStorageSettings public static function Defines the storage-level settings for this plugin. Overrides FieldItemBase::defaultStorageSettings
LanguageItem::generateSampleValue public static function Generates placeholder field values. Overrides FieldItemBase::generateSampleValue
LanguageItem::getConstraints public function Gets a list of validation constraints. Overrides TypedData::getConstraints
LanguageItem::getLanguageConfigurationValues public static function Get language configuration value.
LanguageItem::getNativeName public function Gets the Native name. (Should be added to \Drupal\Core\Language\Language.)
LanguageItem::getPossibleOptions public function Overrides LanguageItem::getPossibleOptions
LanguageItem::getPossibleValues public function Returns an array of possible values. Overrides LanguageItem::getPossibleValues
LanguageItem::getSettableOptions public function Returns an array of settable values with labels for display. Overrides LanguageItem::getSettableOptions
LanguageItem::getSettableValues public function Returns an array of settable values. Overrides LanguageItem::getSettableValues
LanguageItem::isEmpty public function Determines whether the data structure is empty. Overrides Map::isEmpty
LanguageItem::onChange public function React to changes to a child property or item. Overrides Map::onChange
LanguageItem::propertyDefinitions public static function Defines field item properties. Overrides FieldItemInterface::propertyDefinitions
LanguageItem::schema public static function Returns the schema for the field. Overrides LanguageItem::schema
LanguageItem::settingsOptions public static function Gets the unified keys for Formatter and Widget display settings.
LanguageItem::setValue public function Sets the data value. Overrides FieldItemBase::setValue
LanguageItem::storageSettingsForm public function Returns a form for the storage-level settings. Overrides FieldItemBase::storageSettingsForm
Map::$definition protected property The data definition. Overrides TypedData::$definition
Map::$properties protected property The array of properties.
Map::$values protected property An array of values for the contained properties.
Map::get public function Gets a property object. Overrides ComplexDataInterface::get
Map::getIterator public function
Map::getProperties public function Gets an array of property objects. Overrides ComplexDataInterface::getProperties
Map::getString public function Returns a string representation of the data. Overrides TypedData::getString
Map::getValue public function Gets the data value. Overrides TypedData::getValue 1
Map::set public function Sets a property value. Overrides ComplexDataInterface::set
Map::toArray public function Returns an array of all property values. Overrides ComplexDataInterface::toArray 1
Map::__clone public function Magic method: Implements a deep clone.
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.
TypedData::$name protected property The property name.
TypedData::$parent protected property The parent typed data object.
TypedData::createInstance public static function Constructs a TypedData object given its definition and context. Overrides TypedDataInterface::createInstance
TypedData::getDataDefinition public function Gets the data definition. Overrides TypedDataInterface::getDataDefinition
TypedData::getName public function Returns the name of a property or item. Overrides TypedDataInterface::getName
TypedData::getParent public function Returns the parent data structure; i.e. either complex data or a list. Overrides TypedDataInterface::getParent
TypedData::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
TypedData::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
TypedData::getPropertyPath public function Returns the property path of the data. Overrides TypedDataInterface::getPropertyPath
TypedData::getRoot public function Returns the root of the typed data tree. Overrides TypedDataInterface::getRoot
TypedData::setContext public function Sets the context of a property or item via a context aware parent. Overrides TypedDataInterface::setContext
TypedData::validate public function Validates the currently set data value. Overrides TypedDataInterface::validate
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2