You are here

public function OnlyOne::existsNodesContentType in Allow a content type only once (Only One) 8

Returns if exists nodes of a content type in the actual language.

Parameters

string $content_type: Content type machine name.

string $language: The language to check. If the variable is not provided and the site is multilingual the actual language will be taken.

Return value

int If exists nodes return the first node nid otherwise return 0.

Overrides OnlyOneInterface::existsNodesContentType

File

src/OnlyOne.php, line 127

Class

OnlyOne
Class OnlyOne.

Namespace

Drupal\onlyone

Code

public function existsNodesContentType($content_type, $language = NULL) {

  // Getting the entity query instance.
  $query = $this->entityTypeManager
    ->getStorage('node')
    ->getQuery();
  $query
    ->condition('type', $content_type);

  // The site is multilingual?
  if ($this->languageManager
    ->isMultilingual()) {
    if (empty($language)) {
      $language = $this->languageManager
        ->getCurrentLanguage()
        ->getId();
    }

    // Adding the language condition.
    $query
      ->condition('langcode', $language);
  }
  $nids = $query
    ->execute();

  // Extracting the nid from the array.
  $nid = count($nids) ? array_pop($nids) : 0;
  return $nid;
}