2

The issue is that adding a base field to a custom entity type in code would result in an issue of unique constraint violation as there does not seem to be a way to preset the value to the newly added field.

setInitialValue() would set the same value for all the existing entities triggering a constraint violation.

setInitialValueFromField() would not do any good as it would only allow fetching value from fields of same type. Otherwise it would be possible to utilise the value from an ID field and then replace those initial values with something more suitable.

Is there any meaningful way for doing that?

1

I think you'd need to write an update hook to first add you new base field via the EntityDefinitionUpdateManager (an example here since automated entity updates were removed.)

function example_update_8701() {
  // Add the unique constraint, etc.
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $field_storage_definition = $entity_definition_update_manager->getFieldStorageDefinition('hostname', 'comment');
  $field_storage_definition->setDefaultValueCallback(Comment::class . '::getDefaultHostname');
  $entity_definition_update_manager->updateFieldStorageDefinition($field_storage_definition);
}

Then in a post_update hook, you would load each entity and populate the new field with values in whatever manner makes sense and re-save.

The two methods mentioned in your question shouldn't be called since you're updating the existing entities rather than creating new ones.

  • Thanks you for the response. It seems to be a more meaningful solution to the issue than the one I was able to come up with. Still, would that be able to work with the cases where the column being added has a unique key/index set? Would this process be able to handle that? The system logic should be something in the lines of: add column to database, run the post_update_hook that populates the values, apply the index to the database table. – Pjotr May 10 at 10:42
  • Hmm, yeah, indexes might need to be added in the post_update_hook rather than the update hook since they would fail to be added if done before unique values were set... – jhedstrom May 15 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.