public function SerialItem::initializeEntitiesCallback in Serial Field 8
Initialize entities depending on the storage settings.
Parameters
array $form: The form where the settings form is being included in.
\Drupal\Core\Form\FormStateInterface $form_state: The form state of the (entire) configuration form.
File
- src/
Plugin/ Field/ FieldType/ SerialItem.php, line 98
Class
- SerialItem
- Plugin implementation of the 'serial' field type.
Namespace
Drupal\serial\Plugin\Field\FieldTypeCode
public function initializeEntitiesCallback(array &$form, FormStateInterface $form_state) {
// Check if existing entities have to be initialized.
$settings = $form_state
->getValue('settings');
if ((int) $settings['init_existing_entities'] === 1) {
$startValue = (int) $settings['start_value'];
// Check then first if the bundle has entities.
$fieldConfig = $this
->getFieldDefinition();
$entityTypeId = $fieldConfig
->getTargetEntityTypeId();
$storage = \Drupal::entityTypeManager()
->getStorage($entityTypeId);
$bundleKey = $storage
->getEntityType()
->getKey('bundle');
$bundle = $fieldConfig
->getTargetBundle();
$query = \Drupal::entityQuery($entityTypeId);
$query
->condition($bundleKey, $bundle);
$ids = $query
->execute();
if (count($ids) > 0) {
/** @var \Drupal\serial\SerialStorageInterface $serialStorage */
$serialStorage = \Drupal::getContainer()
->get('serial.sql_storage');
// Set serial values for existing entities.
$oldCount = $serialStorage
->initOldEntries($entityTypeId, $bundle, $fieldConfig
->getFieldStorageDefinition()
->getName(), $startValue);
if ($oldCount > 0) {
\Drupal::messenger()
->addMessage(t('Serial values have been automatically set for %count existing entities, starting from %start_value.', [
'%count' => $oldCount,
'%start_value' => $startValue,
]));
}
}
else {
\Drupal::messenger()
->addWarning(t('No entities to initialize, the next entity to be created will start from %start_value.', [
'%start_value' => $startValue,
]));
}
}
}