3

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?

0

1 Answer 1

3

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->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

1
  • 1
    That worked, thanks! One thing to note is the plugin id naming convention, see drupal.org/project/drupal/issues/2649712. For a node selection plugin for example, I only got it to work when I gave it the id default:node (so <group_name>:<entity_type>).
    – brunodbo
    Commented Apr 5, 2018 at 1:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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