Skip to content
Snippets Groups Projects

Issue #3414661: Serial not generating on entity save in certain contexts

1 file
+ 52
0
Compare changes
  • Side-by-side
  • Inline
+ 52
0
@@ -5,6 +5,8 @@
* The Serial module main file.
*/
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
@@ -89,6 +91,56 @@ function serial_clone_node_alter(Node &$node, $context) {
}
}
/**
* Implements hook_entity_insert().
*
* Generate serial value for other contexts
* such as hook_form_alter(), feeds import etc.
*/
function serial_entity_insert(EntityInterface $entity) {
/** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
$entity_type_manager = \Drupal::entityTypeManager();
/** @var \Drupal\Core\Entity\ContentEntityTypeInterface $content_entity_type */
$content_entity_type = $entity_type_manager
->getDefinition($entity->getEntityTypeId());
// Check if definition belongs to
// \Drupal\Core\Entity\ContentEntityTypeInterface.
// Skip generation of serial if not.
if (!$content_entity_type instanceof ContentEntityTypeInterface) {
return;
}
// Load the field definitions.
$field_definitions = \Drupal::service('entity_field.manager')
->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle());
// Loop through field definitions to look for serial field, and pre-populate
// serial value if empty.
foreach ($field_definitions as $field_name => $field_definition) {
if (!empty($field_definition->getTargetBundle())
&& $field_definition->getType() === SerialStorageInterface::SERIAL_FIELD_TYPE
&& $entity->$field_name->isEmpty()) {
/** @var \Drupal\serial\SerialStorageInterface $serial_storage */
$serial_value = \Drupal::service('serial.sql_storage')
->generateValue($field_definition, $entity, TRUE);
// Get the starting value from the storage settings.
$start_value = $field_definition->getSetting('start_value');
// Subtract one as it is already added serial storage.
$serial = ($serial_value + $start_value) - 1;
// Set serial.
$entity->set($field_name, $serial);
// Save entity.
$entity->save();
}
}
}
/**
* Implements hook_theme().
*/
Loading