8 - How can I detect when an entity is being autocreated? I have an entity_reference field that autocreates entities (i.e., the 'Create referenced entities if they don't already exist' option is enabled in the field's configuration). I'm looking for a way to set some values on those autocreated entities before they are saved (e.g., author, revision message, ...).

What I've tried so far:


hook_node_presave(), but there is no indication on the $entity object that it's being 'autocreated' through an entity reference field.
I can see that the new entities are being autocreated in \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::preSave, but it's not clear to me if/how I can override that method without implementing my own entity_reference field type.


Any suggestion for how to set values on an entity when it is being autocreated?
You need a custom EntityReferenceSelection handler plugin. An example would be how the node module sets the autocreated entity to published:

Drupal\node\Plugin\EntityReferenceSelection\NodeSelection:

  public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
    $node = parent::createNewEntity($entity_type_id, $bundle, $label, $uid);

    // In order to create a referenceable node, it needs to published.
    /** @var \Drupal\node\NodeInterface $node */
    $node-&gt;setPublished(TRUE);

    return $node;


You find more information in the plugin annotation class https://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Entity/Annotation/EntityReferenceSelection.php