Skip to content
Language.php 2.05 KiB
Newer Older
 * Contains \Drupal\Core\TypedData\Plugin\DataType\Language.

/**
 * Defines the 'language' data type.
 *
 * The plain value of a language is the language object, i.e. an instance of
 * \Drupal\Core\Language\Language. For setting the value the language object or
 * the language code as string may be passed.
 *
 * @DataType(
 *   id = "language",
 *   label = @Translation("Language"),
 *   description = @Translation("A language object.")
 * )
  protected $id;

  /**
   * @var \Drupal\Core\Language
   */
  protected $language;
   * @return \Drupal\Core\Language\LanguageInterface|null
    if (!isset($this->language) && $this->id) {
      $this->language = \Drupal::languageManager()->getLanguage($this->id);
   *
   * Both the langcode and the language object may be passed as value.
   */
  public function setValue($value, $notify = TRUE) {
    // Support passing language objects.
    if (is_object($value)) {
      $this->id = $value->getId();
    }
    elseif (isset($value) && !is_scalar($value)) {
      throw new \InvalidArgumentException('Value is no valid langcode or language object.');
      $this->language = NULL;
    }
    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
   */
  public function getString() {
    $language = $this->getValue();
    return $language ? $language->getName() : '';

  /**
   * {@inheritdoc}
   */
  public function id() {
    if (isset($this->id)) {
      return $this->id;
    }
    elseif (isset($this->language)) {
      return $this->language->getId();