You are here

public function SerialSQLStorage::initOldEntries in Serial Field 8

Initializes the value of a new serial field in existing entities.

Parameters

string $entityTypeId: Entity type id.

string $entityBundle: Entity bundle (entity type) name.

string $fieldName: Field name.

int $startValue: The value to start the serial increment with.

Return value

int Amount of entries that were updated.

Overrides SerialStorageInterface::initOldEntries

File

src/SerialSQLStorage.php, line 189

Class

SerialSQLStorage
Serial storage service definition.

Namespace

Drupal\serial

Code

public function initOldEntries($entityTypeId, $entityBundle, $fieldName, $startValue) {
  $storage = $this->entityTypeManager
    ->getStorage($entityTypeId);
  $query = $storage
    ->getQuery();

  // @todo shall we assign serial id to unpublished as well?
  // $query->condition('status', 1);
  $bundleKey = $storage
    ->getEntityType()
    ->getKey('bundle');
  $query
    ->condition($bundleKey, $entityBundle);
  $query
    ->accessCheck(FALSE);
  $entityIds = $query
    ->execute();
  $updated = 0;
  $storageName = $this
    ->createStorageName($entityTypeId, $entityBundle, $fieldName);
  foreach ($entityIds as $entityId) {
    $entity = $storage
      ->loadUnchanged($entityId);
    $serial = $this
      ->generateValueFromName($storageName);

    // @todo review multilingual
    $entity->{$fieldName}->value = $startValue + $serial - 1;
    if ($entity
      ->save() === SAVED_UPDATED) {
      ++$updated;
    }
  }
  return $updated;
}