0

I have a field definition set up like below. I want Drupal to do all the heavy lifting for me, so my definitions are minimal and rely on Drupal defaults:

    $fields[$field] = BaseFieldDefinition::create('entity_reference')
        ->setSettings([
            'target_type' => 'target_entity',
            'handler' => 'default',
            'handler_settings' => [
                'auto_create' => true,
            ],
        ])
        ->setDisplayOptions('form', array(
            'weight' => $weight,
        ));
    ;

target_entity is just a simple bundleless entity.

This creates an entity reference auto-complete field in forms, but if I type something that doesn't match any existing entities, Drupal will say that no matching entities found and will refuse to create a new one.

How do I make the auto_create setting work?

1 Answer 1

0

The answer is 'you cannot auto-create bundle-less entities in Drupal 8.2.0. I don't know if this is a bug or a feature, but you have to have a bundle for target entity ('all_target_entities' in my example) and indicate that as target bundle in the settings:

$fields[$field] = BaseFieldDefinition::create('entity_reference')
    ->setSettings([
        'target_type' => 'target_entity',
        'handler' => 'default',
        'handler_settings' => [
            'auto_create' => true,
            'target_bundles' => [
                'all_target_entities' => 'all_target_entities',
            ],
        ],
    ])
    ->setDisplayOptions('form', array(
        'weight' => $weight,
    ));
;

I think it was not the case up to some point, so stating the exact version I am having this issue with.

3
  • You should open a core issue in the entity_reference component with this.
    – Berdir
    Commented Oct 31, 2016 at 13:58
  • The issue already exists: drupal.org/node/2821352
    – Jonathan
    Commented Oct 31, 2016 at 20:36
  • Yeah, saw that, but it doesn't explicitly say it's a bug, just says it's unnnecessary. Probbaly because no one knows if this was the intention or not - there is no documentation for this feature.
    – Okneloper
    Commented Nov 1, 2016 at 10:33

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.