Problem/Motivation

Autocreate a is a great UX option for Entity Reference fields. Currently it is not available if you choose "Views" as the "Reference method", which is necessary if you want to filter the available choices.

Proposed resolution

Create an auto create EntityReferenceSelection plugin which extends ViewsSelection.

Remaining tasks

See #96
See #98
Review

User interface changes

Entity reference field type will have one more reference method Views: Filter by an entity reference view and allow autocreation.
When this option is selected and Create referenced entities if they don't already exist is checked, new referenced entities with title will be created. If more then one bundle exists for referenced entity, then a Store new items in select option will be shown to choose the bundle.

API changes

None.

Data model changes

None.

CommentFileSizeAuthor
#118 2800875-118-Autocreate_for_entity_reference_selection_handlers_drupal11.patch13.59 KBsboden
#115 2800875-115-b-views_selection_autocreate_drupal_11.patch2.39 KBsboden
#115 2800875-115-a-selection_plugin_manager_drupal_11.patch1.26 KBsboden
#112 autocreate-entity-reference-selection-handlers-that-extend-viewsselection-10.4.x.patch16.21 KBurashima82
#109 2800875-109-autocreate-entity-reference-selection-handlers-that-extend-viewsselection-10.3.x.patch16.17 KBlisagodare
#108 2800875-108-autocreate-entity-reference-selection-handlers-that-extend-viewsselection-10.3.x.patch11.86 KBlisagodare
#107 2800875-nr-bot.txt90 bytesneeds-review-queue-bot
#92 entity_ref.png161.86 KBnarendrar
#86 interdiff_84-86.txt1.64 KBpradhumanjain2311
#86 2800875-86.patch11.81 KBpradhumanjain2311
#84 interdiff_83-84.txt455 bytespooja saraah
#84 2800875-84.patch11.33 KBpooja saraah
#83 2800875-83.patch11.34 KBmedha kumari
#82 reroll_diff_70-82.txt5.16 KBimmaculatexavier
#82 2800875-82.patch18.32 KBimmaculatexavier
#70 interdiff_67-70.txt707 bytesvsujeetkumar
#70 2800875-70.patch18.05 KBvsujeetkumar
#69 2800875-8.9-69.patch4.97 KBimalabya
#67 2800875-67.patch17.62 KBsuresh prabhu parkala
#64 2800875-64.patch17.7 KBashu1629
#59 2800875-59.patch15.78 KBchr.fritsch
#59 interdiff-2800875-57-59.txt4.63 KBchr.fritsch
#57 interdiff-2800875-55-57.txt1.94 KBchr.fritsch
#57 2800875-57.patch15.28 KBchr.fritsch
#55 2800875-55.patch14.62 KBchr.fritsch
#50 2800875-50.patch13.5 KBchr.fritsch
#45 2800875-45.patch7.13 KBchr.fritsch
#42 core-2800875-autocreate-for-entity-reference-fields-that-use-views-reference-method.patch6.29 KBrob230
#41 2800875-40.patch6.94 KBpatrickfweston
#39 drupal-2800875-38-onto-2174633-Autocreate-for-Entity-Reference-fields.patch7.02 KBgeek-merlin
#38 2800875-34.patch6.72 KBDirst
#33 2800875-33.patch6.5 KBnaveenvalecha
#26 autocreate_for_entity-2800875-25.patch6.59 KBmirsoft
#24 autocreate_for_entity-2800875-24.patch6.8 KBwelly
#22 autocreate_for_entity-2800875-22.patch6.77 KBwelly
#21 interdiff-2800875-19-21.txt949 bytesmitsuroseba
#21 drupal-autocreate-2800875-21.patch6.68 KBmitsuroseba
#20 drupal-autocreate-2800875-19.patch6.61 KBcriz
#19 drupal-autocreate-2800875-19.patch1.51 KBcriz
#8 Autocreate for views entity reference method.png48.63 KBjonathanshaw
#7 drupal-autocreate-2800875-6.patch6.65 KBjonathanshaw
#5 drupal-autocreate-2800875-3.patch5.97 KBjonathanshaw
#2 drupal-autocreate-2800875.patch6.1 KBjonathanshaw

Issue fork drupal-2800875

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

jonathanjfshaw created an issue. See original summary.

jonathanshaw’s picture

StatusFileSize
new6.1 KB
jonathanshaw’s picture

Status: Active » Needs review

Let's see what testbot makes of my first core patch ...

Status: Needs review » Needs work

The last submitted patch, 2: drupal-autocreate-2800875.patch, failed testing.

jonathanshaw’s picture

Status: Needs work » Needs review
StatusFileSize
new5.97 KB

Status: Needs review » Needs work

The last submitted patch, 5: drupal-autocreate-2800875-3.patch, failed testing.

jonathanshaw’s picture

Status: Needs work » Needs review
StatusFileSize
new6.65 KB

Revised views.entity_reference.schema.yml to fix test fails.

jonathanshaw’s picture

Added screenshot.

jonathanshaw’s picture

Looks like we need an EntityReferenceAutocreateTestTrait to share logic between EntityReferenceAutocreateTest and views/SelectionTest, now that this patch adds autocreate to the views selection handler.

jonathanshaw’s picture

Yched said in #2577963: Let entity_ref Selection handlers be in charge of the field validation IS:

ViewsSelector is inherently incompatible with "autosave". You cannot validate that an $entity that isn't in the database yet will match a given View.

With this patch if you autocreate an entity incompatible with the view, it is created and referenced when you save the parent form. But if you go to save the form again, it fails validation with "This entity (node: xxx) cannot be referenced."

Is there a way to work round this limitation? There are many valid uses for the ViewsSelection that are not compromised by this problem:

Could we just have a warning under the text "Create referenced entities if they don't already exist" that said
"Warning: you must make sure that entities created in this way are not filtered from the view selected above."

jonathanshaw’s picture

Issue summary: View changes

Fixed screenshot link

amateescu’s picture

Could we just have a warning under the text "Create referenced entities if they don't already exist" that said
"Warning: you must make sure that entities created in this way are not filtered from the view selected above."

The problem is that the user has no control over the autocreate process, so even if we would display that help text, they would have to write code somewhere in order to make sure that autocreated entities are valid for a specific view.

With that in mind, the easiest way for them to use autocreate with a views selection would be to write a custom selection plugin that extends the views one and imeplement SelectionWithAutocreateInterface, so they have full control over the createNewEntity() and validateReferenceableNewEntities() methods.

So, what we could do in this patch is to add autocreate support for selections that *extend* ViewsSelection, even if the base views selection can not support it by default. What do you think?

jonathanshaw’s picture

The problem is that the user has no control over the autocreate process, so even if we would display that help text, they would have to write code somewhere in order to make sure that autocreated entities are valid for a specific view.

What I had in mind is that the field values of an autocreated entity are basically predictable. The title/label is the only one the content author controls, the rest are the just default values for a new entity of that type. Therefore in the 98% use case it is relatively simple for the sitebuilder to make sure that a newly autocreated entity is not filtered out of the entity reference view.

It's works straightforwardly as long as:
1) the view does not filter by title
2) the view does not filter out an entity having a default value for one of the other fields.
3) the view does not filter by a field/property whose value depends on something the sitebuilder cannot predict or control like the time, user or title.

If the sitebuilder gets this wrong, the entity is still created, but it does not show up in the entity reference field because it is invalid for that. This is bad UX, hence the need for a warning. But it's easy to identify, recover from and prevent this problem, so I'm suggesting a warning is all we need.

Just how cast-iron does our procedure have to be to "make sure that autocreated entities are valid for a specific view". I'm suggesting the sitebuilder can ensure this manually by keeping the view filters simple; maybe you're saying that's not strong enough?

P.S. Ignore the patch for now, there are some things I want to improve in it if the feature in general is endorsed.

amateescu’s picture

Just how cast-iron does our procedure have to be to "make sure that autocreated entities are valid for a specific view". I'm suggesting the sitebuilder can ensure this manually by keeping the view filters simple; maybe you're saying that's not strong enough?

That's exactly what I'm saying :) IMO, the list of things that a view shouldn't filter on is quite large (and open-ended really) and makes the entire views selection handler kind of useless.

And that's why I proposed to change the direction of the issue to "allow subclasses of the views selection to provide autocreate support", because at least in that case there is some code involved which has to ensure that the autocreated entities are valid.

almaudoh’s picture

--- a/core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/EntityReferenceAutocompleteWidget.php
+++ b/core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/EntityReferenceAutocompleteWidget.php
@@ -142,12 +142,13 @@ public function massageFormValues(array $values, array $form, FormStateInterface
    */
   protected function getAutocreateBundle() {
     $bundle = NULL;
-    if ($this->getSelectionHandlerSetting('auto_create') && $target_bundles = $this->getSelectionHandlerSetting('target_bundles')) {
+    if ($this->getSelectionHandlerSetting('auto_create')) {
       // If there's only one target bundle, use it.
+      $target_bundles = $this->getSelectionHandlerSetting('target_bundles');
       if (count($target_bundles) == 1) {
         $bundle = reset($target_bundles);
       }
-      // Otherwise use the target bundle stored in selection handler settings.
+      // Otherwise use the autocreate bundle stored in selection handler settings.
       elseif (!$bundle = $this->getSelectionHandlerSetting('auto_create_bundle')) {
         // If no bundle has been set as auto create target means that there is
         // an inconsistency in entity reference field settings.
@@ -158,7 +159,6 @@ protected function getAutocreateBundle() {
         ), E_USER_WARNING);
       }
     }
-
     return $bundle;

+1. This part of the patch is actually a bug-fix, I have a similar situation where I want to use the entity_reference_autocomplete_tags widget for an entity_reference field that has no bundles and I also want to use auto_create. But $target_bundles = $this->getSelectionHandlerSetting('target_bundles') is in the way because once you define 'target_bundles', then DefaultSelection::buildEntityQuery() fails because my entity has no bundles.
I'm wondering if this could be pulled out into a separate bug-fix issue.

+      if ($entity_type->hasKey('bundle')) {
+        $entity_type = $this->configuration['target_type'];
+        $bundles = $this->entityManager->getBundleInfo($entity_type);
+        $bundle_options = array();
+        foreach ($bundles as $bundle_name => $bundle_info) {
+          $bundle_options[$bundle_name] = $bundle_info['label'];
+        }
+        natsort($bundle_options);

Why are we re-initializing $entity_type inside the if statement?

+  /**
+   * {@inheritdoc}
+   */
+  public function validateReferenceableNewEntities(array $entities) {
+    return $entities;
+    return array_filter($entities, function ($entity) {
+      if (isset($this->configuration['handler_settings']['auto_create_bundle'])) {
+        return ($entity->bundle() === $this->configuration['handler_settings']['auto_create_bundle']);
+      }
+      return TRUE;
+    });
+  }
+

The second return statement will never run.

jonathanshaw’s picture

@amateescu #14

what we could do in this patch is to add autocreate support for selections that *extend* ViewsSelection, even if the base views selection can not support it by default. What do you think?

Agreed

@almaudoh #15

This part of the patch is actually a bug-fix, I have a similar situation ... I'm wondering if this could be pulled out into a separate bug-fix issue.

Agreed, it would be good to make a separate issue.

Regarding the code issues you point out, that's just bad code of mine. The whole patch needs redoing anyway.

jonathanshaw’s picture

Status: Needs review » Needs work

This part of the patch is actually a bug-fix, I have a similar situation ... I'm wondering if this could be pulled out into a separate bug-fix issue.

Created #2821352: EntityReferenceAutocompleteWidget::getAutocreateBundle() unnecessarily requires the 'target_bundles' setting, some guidance needed on whether/what tests are needed.

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.0-alpha1 will be released the week of January 30, 2017, which means new developments and disruptive changes should now be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

criz’s picture

StatusFileSize
new1.51 KB

This is just a reroll of the patch from #7 for 8.4.x. Needs some work. For example splitting out the part for #2821352: EntityReferenceAutocompleteWidget::getAutocreateBundle() unnecessarily requires the 'target_bundles' setting.

criz’s picture

StatusFileSize
new6.61 KB

Sorry, this is the right one.

mitsuroseba’s picture

StatusFileSize
new6.68 KB
new949 bytes

Add additional check for 'auto_create' settings.

welly’s picture

Status: Needs work » Needs review
StatusFileSize
new6.77 KB

Patch at #7 wasn't applying to 8.3.x. Rerolled and tested - works great. Thanks all. Will need tests though.

welly’s picture

Apologies to @mitsuroseba - hadn't refreshed my browser window while I was uploading my patch.

welly’s picture

StatusFileSize
new6.8 KB

Minor amend to the patch

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.0-alpha1 will be released the week of July 31, 2017, which means new developments and disruptive changes should now be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

mirsoft’s picture

StatusFileSize
new6.59 KB

Patch rerolled for 8.4.0 / 8.5.x-dev . Manually tested. Still needs automated tests.

mirsoft’s picture

Issue tags: +Needs tests
jonathanshaw’s picture

@amteescu in #12 / #14 said:

the easiest way for them to use autocreate with a views selection would be to write a custom selection plugin that extends the views one and imeplement SelectionWithAutocreateInterface, so they have full control over the createNewEntity() and validateReferenceableNewEntities() methods.

IMO, the list of things that a view shouldn't filter on is quite large (and open-ended really) and makes the entire views selection handler kind of useless.

And that's why I proposed to change the direction of the issue to "allow subclasses of the views selection to provide autocreate support", because at least in that case there is some code involved which has to ensure that the autocreated entities are valid.

As I interpret it this means the most helpful thing core could do for ViewsSelection handler is:

  1. Keep auto_create and auto_create_bundle in the schema and settings array
  2. Keep the config form code, but show it only if the selection handler implements SelectionWithAutocreateInterface
  3. Keep createNewEntity but remove validateReferenceableNewEntities()

If we do it this way, then the minimum someone has to do is create a new class extending ViewsSelection, declare they implement SelectionWithAutocreateInterface, and add a validateReferenceableNewEntities() method that returns TRUE.

Alternatively if it is against Drupal's DX patterns to put unused base code like this in ViewsSelection then perhaps we could put this base code in a ViewsSelectionWithAutocreateBase class.

amateescu’s picture

@jonathanjfshaw, the first and the second points from #28 are spot on, but I don't agree with the third one. createNewEntity() and validateReferenceableNewEntities() go hand in hand in regards to what fields need to be created by createNewEntity() so that the created entity is valid for validateReferenceableNewEntities().

If we do it this way, then the minimum someone has to do is create a new class extending ViewsSelection, declare they implement SelectionWithAutocreateInterface, and add a validateReferenceableNewEntities() method that returns TRUE.

That would be the minimum, yes, but in reality validateReferenceableNewEntities() has to implement the proper checks for the field values that were assigned in createNewEntity().

Alternatively if it is against Drupal's DX patterns to put unused base code like this in ViewsSelection then perhaps we could put this base code in a ViewsSelectionWithAutocreateBase class.

To make sure that we don't put unused code in core we need at least one test implementation of a selection handler that extends ViewsSelection and uses the auto-create functionality :)

amateescu’s picture

Status: Needs review » Needs work

I think we agree on the direction for this patch so NW is a better status.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.0-alpha1 will be released the week of January 17, 2018, which means new developments and disruptive changes should now be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.6.x-dev » 8.7.x-dev

Drupal 8.6.0-alpha1 will be released the week of July 16, 2018, which means new developments and disruptive changes should now be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

naveenvalecha’s picture

Assigned: Unassigned » naveenvalecha
StatusFileSize
new6.5 KB

Here's straight reroll for 8.7.x
Next: Add tests and address the direction
Assigning to myself for it.

anavarre’s picture

Naveen, are you still working on this?

anavarre’s picture

Assigned: naveenvalecha » Unassigned

Unassigning for now.

pancho’s picture

Version: 8.7.x-dev » 8.8.x-dev

Drupal 8.7.0-alpha1 will be released the week of March 11, 2019, which means new developments and disruptive changes should now be targeted against the 8.8.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Dirst’s picture

StatusFileSize
new6.72 KB

Hello, this patch works with 8.7.2

geek-merlin’s picture

Patch flying in with a plain rebase of this onto #2174633: View output is not used for entityreference options, which i currently needed.
(Nothing really happens here but some context lines change.)

If that one goes in first, as expected, we can simply click 'rebase'. Otherwise we can ignore.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

patrickfweston’s picture

StatusFileSize
new6.94 KB

I've rerolled the patch in #38 for Drupal 8.8 and have tested it on our site.

rob230’s picture

For some reason #37 and #39 do not apply to 8.7 for me. I've rerolled #39 so that it will apply.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

rynebl’s picture

#42 worked for 8.9.2, awesome stuff.

chr.fritsch’s picture

geek-merlin’s picture

jonathanshaw’s picture

Title: Autocreate for Entity Reference fields that use Views reference method » Autocreate for Entity Reference selection handlers that extend ViewsSelection
chr.fritsch’s picture

Status: Postponed » Needs work

Blocker is in. We still need tests

jonathanshaw’s picture

The whole approach needs reworking per #28 / #29

chr.fritsch’s picture

Status: Needs work » Needs review
StatusFileSize
new13.5 KB

Here is the new approach.

jonathanshaw’s picture

Issue tags: -Needs tests

Yay! That's a huge step forward.

  1. +++ b/core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/EntityReferenceAutocompleteWidget.php
    @@ -159,6 +159,11 @@ public function massageFormValues(array $values, array $form, FormStateInterface
    +      // If a bundle is explicitly defined, use it.
    +      if ($bundle = $this->getSelectionHandlerSetting('auto_create_bundle')) {
    +        return $bundle;
    +      }
    +
    
    @@ -169,9 +174,7 @@ protected function getAutocreateBundle() {
    +      else {
    

    I don't understand why these changes are needed.

  2. +++ b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
    @@ -167,6 +182,37 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta
    +        $form['auto_create'] = [
    ...
    +          $form['auto_create_bundle'] = [
    

    I'm concerned about the relationship of this code with the similar code in the DefaultSelection plugin class.
    Why is it not identical?
    If it can be identical, should it be on SelectionPluginBase?
    Should it be a trait?

chr.fritsch’s picture

1. Without putting that code up front, in the test I never got the auto_create_bundle value, because without target_bundles always the entity_type was returned.

2. Indeed. It's exactly the same like in DefaultSelection. So theortically I think it's possible to move that code to SelectionPluginBase, but that would require some refactoring. For example the base class then needs to implement ContainerFactoryPluginInterface. I am not sure how much of that felt in the scope of this issue.

jonathanshaw’s picture

Status: Needs review » Reviewed & tested by the community

OK about #51.1, and for #51.2 let's see what the committer wants.

alexpott’s picture

Status: Reviewed & tested by the community » Needs work
  1. +++ b/core/modules/views/config/schema/views.entity_reference.schema.yml
    @@ -20,3 +20,14 @@ entity_reference_selection.views:
    +    auto_create:
    +      type: boolean
    +      label: 'Create referenced entities if they don''t already exist'
    +    auto_create_bundle:
    +      type: string
    +      label: 'Bundle assigned to the auto-created entities.'
    
    +++ b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
    @@ -116,6 +129,8 @@ public function defaultConfiguration() {
    +      'auto_create' => FALSE,
    +      'auto_create_bundle' => NULL,
    

    I think the addition of these default values means that we're going to need an update function for existing fields and we might need to consider something similar to views_view_presave() so that configuration stored in config/install is also updated.

  2. +++ b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
    @@ -82,10 +93,11 @@ class ViewsSelection extends SelectionPluginBase implements ContainerFactoryPlug
    -  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, RendererInterface $renderer) {
    +  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, ModuleHandlerInterface $module_handler, AccountInterface $current_user, RendererInterface $renderer) {
    

    We need to add the argument to the end and provide a NULL default and do the deprecation dance. Otherwise we'll brake some contrib modules - see http://grep.xnddx.ru/search?text=extends+ViewsSelection&filename= - at least entity_reference_views_token will be broken.

  3. +++ b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
    @@ -167,6 +182,37 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta
    +            '#title' => $this->t('Store new items in'),
    

    This is odd text but it is repeated from DefaultSelection.

    This kind of makes me wonder if SelectionPluginBase should implement a helper method to add these fields. Not sure. Could get messy - but the duplicate code / UI text is also icky.

chr.fritsch’s picture

Status: Needs work » Needs review
StatusFileSize
new14.62 KB

After chatting with @alexpott, we agreed on that we should change the direction of this a bit. The new patch now contains an entirely new selection plugin that extends the views plugin. This has some advantages:

  1. No upgrade path needed
  2. No constructor changes
  3. No conditional schema (a views plugin without autocreate that still contains the schema entries)
alexpott’s picture

+++ b/core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginBase.php
@@ -86,4 +86,38 @@ public function submitConfigurationForm(array &$form, FormStateInterface $form_s
 
+  protected function buildAutocreateConfigurationForm(array $form, $bundles) {
...
+
+  protected function getBundleOptions($bundles) {

We need some documentation of these methods.

chr.fritsch’s picture

StatusFileSize
new15.28 KB
new1.94 KB

Added the missing docs.

jonathanshaw’s picture

+1 to the direction.

  1. +++ b/core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginBase.php
    @@ -86,4 +86,60 @@ public function submitConfigurationForm(array &$form, FormStateInterface $form_s
    +    if ($this instanceof SelectionWithAutocreateInterface) {
    

    Does checking for SelectionWithAutocreateInterface makes sense now that this method is only called explicitly on a handler that wants it.

  2. +++ b/core/lib/Drupal/Core/Entity/Plugin/EntityReferenceSelection/DefaultSelection.php
    @@ -259,30 +259,9 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta
    -    if ($entity_type->hasKey('bundle')) {
    -      $bundles = array_intersect_key($bundle_options, array_filter((array) $configuration['target_bundles']));
    -      $form['auto_create_bundle'] = [
    

    The defaultselection plugin can be used on bundleless entities. It looks like we might still be showing the auto create bundle setting in this case, which seems like poor UX

  3. +++ b/core/lib/Drupal/Core/Entity/Plugin/EntityReferenceSelection/DefaultSelection.php
    @@ -259,30 +259,9 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta
    +    $bundles = $entity_type->hasKey('bundle') ? $this->entityTypeBundleInfo->getBundleInfo($entity_type->id()) : [];
    +    $bundles = array_intersect_key($bundles, array_filter((array) $configuration['target_bundles']));
    +    $form = $this->buildAutocreateConfigurationForm($form, $this->getBundleOptions($bundles));
    

    Assembling the bundles has some fairly complex logic here, which is also duplicated in ViewsSelectionWithAutocreateBase. Why not move it into buildAutocreateConfigurationForm() and call getBundleOptions() from there?

  4. The only point to creating the new method getBundleOptions() would be to keep things DRY, but I think you forgot to replace the existing code that does the same thing earlier in DefaultSelection::buildConfigurationForm(). i.e. this method should be called twice not once.
  5. I'm concerned about test coverage for bundleless entities, especially with the default selection plugin with has so much usage in the wild.
chr.fritsch’s picture

StatusFileSize
new4.63 KB
new15.78 KB

Thank you @jonathanshaw

Regarding:

#58-1:
You are right. I removed the if clause

#58-2:

+++ b/core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginBase.php
@@ -86,4 +86,60 @@ public function submitConfigurationForm(array &$form, FormStateInterface $form_s
+      $form['auto_create_bundle'] = [
+        '#type' => 'select',
+        '#title' => $this->t('Store new items in'),
+        '#options' => $bundles,
+        '#default_value' => $this->configuration['auto_create_bundle'],
+        '#access' => count($bundles) > 1,
+        '#states' => [
+          'visible' => [
+            ':input[name="settings[handler_settings][auto_create]"]' => ['checked' => TRUE],
+          ],
+        ],
+        '#weight' => -1,
+      ];

We only show the form element when there are multiple bundles available.

#58-3:
I moved getBundleOptions() into the autocreate form.

#58-4:
Nice catch. Used getBundleOptions() at the beginning of the form now as well.

#58-5:
We are having a lot of tests for the default selection handler in core/modules/field/tests/src/Functional/EntityReference/. What are you missing?

jonathanshaw’s picture

  1. +++ b/core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginBase.php
    @@ -86,4 +86,58 @@ public function submitConfigurationForm(array &$form, FormStateInterface $form_s
    +   *   An array of bundle labels keyed be the bundle name.
    

    nit: 'by' the bundle name.

  2. +++ b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsAutocreateSelectionBase.php
    @@ -0,0 +1,67 @@
    +  protected function setEntityTypeBundleInfo(EntityTypeBundleInfoInterface $entityTypeBundleInfo) {
    +    $this->entityTypeBundleInfo = $entityTypeBundleInfo;
    +  }
    

    According to @alexpott's comment in https://www.previousnext.com.au/blog/safely-extending-drupal-8-plugin-cl... you don't need the setter method here. Not sure what the preferred approach is.

  3. Thanks to your work in #2821352: EntityReferenceAutocompleteWidget::getAutocreateBundle() unnecessarily requires the 'target_bundles' setting we have EntityReferenceAutocreateTest::testNoBundles(), which is great. EntityReferenceAdminTest::testMultipleTargetBundles() covers the auto create settings UI for cases where there are multiple bundles. But I see no coverage for single bundle and bundleless entities. I don't like to ask for it, but touching DefaultSelection makes me nervous.
jonathanshaw’s picture

+++ b/core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/EntityReferenceAutocompleteWidget.php
@@ -159,6 +159,11 @@ public function massageFormValues(array $values, array $form, FormStateInterface
+      // If a bundle is explicitly defined, use it.
+      if ($bundle = $this->getSelectionHandlerSetting('auto_create_bundle')) {
+        return $bundle;
+      }

This looks like it will change the behavior of autocreate on fields that reference deleted bundles. Probably for the better.

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

ashu1629’s picture

Version: 9.2.x-dev » 9.1.x-dev
Assigned: Unassigned » ashu1629
Status: Needs review » Needs work
Issue tags: +Needs reroll

The patch mentioned in #59 is not working with drupal 9.1+ versions. Requesting a reroll for this patch.

ashu1629’s picture

Status: Needs work » Needs review
Issue tags: -Needs reroll
StatusFileSize
new17.7 KB

Adding rerolled patch which works with Drupal 9.1.7. Please review.

ashu1629’s picture

Assigned: ashu1629 » Unassigned
jonathanshaw’s picture

Status: Needs review » Needs work
suresh prabhu parkala’s picture

Status: Needs work » Needs review
StatusFileSize
new17.62 KB

Tried to fix custom commands failure. Please review.

Status: Needs review » Needs work

The last submitted patch, 67: 2800875-67.patch, failed testing. View results

imalabya’s picture

StatusFileSize
new4.97 KB

Needed a Patch for 8.9.x.

vsujeetkumar’s picture

StatusFileSize
new18.05 KB
new707 bytes

Fixed fail tests because of "Undefined variable: selected_bundles", Please have a look and advise.

vsujeetkumar’s picture

Status: Needs work » Needs review

brentgees made their first commit to this issue’s fork.

brentg’s picture

Rerolled the patch from #33 to be compatible with the 8.9.x version

benito25’s picture

I had this problem with Inline Entity Form Complexe in Drupal 9.2.

I added patch 70 and it's work perfectly.

Thanks a lot.

damiengr’s picture

Patch #70 works perfectly with Drupal 9.2
Thank you !

ultrabob’s picture

Status: Needs review » Reviewed & tested by the community

I've applied this patch on a site exhibiting the reported issue and it cleaned it up nicely.

I also had a quick look at the patch, and I'm admittedly not deeply familiar with the part of code it is addressing, but everything looked reasonable.

Finally, the approach is non-destructive, it is not changing existing behaviors, rather it adds a second way of selecting a views filter to allow creating a new entity. This should not break any existing installs.

It looks very good to me.

Version: 9.1.x-dev » 9.3.x-dev

Drupal 9.1.10 (June 4, 2021) and Drupal 9.2.10 (November 24, 2021) were the last bugfix releases of those minor version series. Drupal 9 bug reports should be targeted for the 9.3.x-dev branch from now on, and new development or disruptive changes should be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

jnrfred’s picture

Patch in #70 works for me too on Drupal 9.2

pminf’s picture

Using patch from #70 seems to workaround an Inline Entity Form issue: "Referencing new entity fails when reference method is view or entity is unpublished". Note that I don't have to enable the auto_create setting to make it work. Choosing "Views: Filter by an entity reference view and allow autocreation" as a reference method is enough. I'm wondering why this reference method solves the IEF issue. Could someone please give me some insights so that I can rely on this patch?

quietone’s picture

Version: 9.3.x-dev » 10.0.x-dev
Status: Reviewed & tested by the community » Needs work
Issue tags: +Needs reroll

The latest patch here is for 9.1.x and it needs to be on 10.0.x, changing version. The patch does not apply to 10.0.x, adding reroll tag. And might as well make sure there is a 9.5.x version as well.

immaculatexavier’s picture

Status: Needs work » Needs review
StatusFileSize
new18.32 KB
new5.16 KB

Rerolled patch against 10.0.x
Attached Reroll diff against #70

medha kumari’s picture

Version: 10.0.x-dev » 10.1.x-dev
Issue tags: -Needs reroll
StatusFileSize
new11.34 KB

Rerolled patch #82 with 10.1.x.

pooja saraah’s picture

StatusFileSize
new11.33 KB
new455 bytes

Fixed failed commands on #83
Attached patch against Drupal 10.1.x

nod_’s picture

Status: Needs review » Needs work

The last patch doesn't pass commit checks, could you make sure to run ./core/scripts/dev/commit-code-check.sh before uploading a patch to make sure there are no issues with code formatting. see https://www.drupal.org/docs/develop/development-tools/running-core-devel...

Thanks!

pradhumanjain2311’s picture

Status: Needs work » Needs review
StatusFileSize
new11.81 KB
new1.64 KB

Try to fix patch #84 CCF errors.
Taking reference from patch #82.

smustgrave’s picture

Status: Needs review » Needs work
Issue tags: +Needs Review Queue Initiative, +Needs change record

This issue is being reviewed by the kind folks in Slack, #needs-review-queue-initiative. We are working to keep the size of Needs Review queue [2700+ issues] to around 400 (1 month or less), following Review a patch or merge request as a guide.

CI failures in the last few patches.

Such a feature will need a change record.

Curious though if we are auto creating any kind of entity reference. What happens if it's a reference to, say articles, how is it auto creating articles?

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

narendraR made their first commit to this issue’s fork.

narendrar’s picture

Status: Needs work » Needs review
Issue tags: -Needs change record

Re #87: Fixed CI failures & added CR.

Curious though if we are auto creating any kind of entity reference. What happens if it's a reference to, say articles, how is it auto creating articles?

It will create an article with the title passed in input box.

narendrar’s picture

Issue summary: View changes
StatusFileSize
new161.86 KB

Update IS also.

smustgrave’s picture

Status: Needs review » Needs work

Cleaning up credits for bad rerolls

CR looks good.

Tested this out on a Umami Install, since that's what I had running
Created an Entity Ref view that searches for Tags title and filters by just Tags taxonomy vocabulary
updated Article content type to use new handler.
Created an Article and added "This is a test" to the tags field
It was created BUT it was added to the wrong vocabulary. Was added to Recipe category not tags

narendrar’s picture

Status: Needs work » Needs review

Hi @smustgrave, Thanks for the review.

Created an Article and added "This is a test" to the tags field
It was created BUT it was added to the wrong vocabulary. Was added to Recipe category not tags

This might be because Store new items in might be selected as Recipe on the created field. If this is not the case, can you please provide a screen recording so that I can reproduce the steps?

smustgrave’s picture

Status: Needs review » Reviewed & tested by the community

Retested on a fresh install and seems to be adding to the correct vocabulary now.

quietone’s picture

Issue summary: View changes
Status: Reviewed & tested by the community » Needs work
Issue tags: +Usability

I'm triaging RTBC issues.

I read the issue summary and then the comments. I then read the change record and scanned the patch. I have found some more things to do here which I will list below.

But first, thanks for working on this, it does look like a handy feature!

  1. This is adding to the UI, therefor adding 'usability' tag
  2. The proposed resolution has not been updated since this issue was created and there was a change to the approach in #54/#55. That should be checked.
  3. The points raised in #60 have not been addressed.
  4. #61 points out a change of behavior. I checked the change record and it is not discussed there. The change of behavior should be added there, perhaps in before/after sections. How disruptive is this change?
  5. Sadly, I don't see that there has been a code review since #60. There were a lot of rerolls after that but quite a few do not have interdiffs
  6. The term 'autocreation' is used throughout the MR but it is not an English word so should be changed. It is not identified because it appears in the core list of misspelled words in core. And there is an issue to correct all the spellings and remove that list.
  7. I think the change record needs a more informative title and that the CR itself can be made easier to understand. It should explicitly how/where to use this new feature. That is, that it when adding a reference field to an entity. The screenshot is helpful but I wasn't sure what is new about it. It is just the addition of the new option? Does selecting the option then offer more fields? I also am not sure what 'new referenced entities with title will be created" means. There is some help for this, Write a change record for a Drupal core issue.
quietone’s picture

I made a few tweaks to the MR but it still needs work.

I changed the MR to avoid spelling errors and sorted use statements in one file.

quietone’s picture

There is one test file changed here, \Drupal\Tests\field\Functional\EntityReference\Views\SelectionTest. It adds the test module, 'views_entity_test'. However, if the line is removed the test still passes.

And related to that, what is the purpose of the duplicate plugin in, \Drupal\views_entity_test\Plugin\EntityReferenceSelection\TestViewsWithAutoCreateSelection?

This all make me think the question raised in #58.5 about testing, and answered in #59.5, needs to be looked into again. And a fail test will be needed here as well. If I knew more about views testing I would offer a suggestion.

Adding tags I should have done earlier.

Utkarsh_33 made their first commit to this issue’s fork.

narendrar’s picture

Issue summary: View changes
Issue tags: -Needs issue summary update

tobiasb changed the visibility of the branch 2800875-autocreate-entity to hidden.

tobiasb changed the visibility of the branch 2800875-autocreate-for-entity-D8 to hidden.

tobiasb changed the visibility of the branch 11.x to hidden.

tobiasb changed the visibility of the branch 2800875-autocreate-for-entity to hidden.

tobiasb’s picture

Assigned: Unassigned » tobiasb
tobiasb’s picture

Assigned: tobiasb » Unassigned
Status: Needs work » Needs review
Issue tags: +Configuration schema, +Needs tests

I added a new constraint AutoCreateEntityBundleExists; but I have no idea how to test it on the drupal way. I know there are other constraints, but their looks easier.

needs-review-queue-bot’s picture

Status: Needs review » Needs work
StatusFileSize
new90 bytes

The Needs Review Queue Bot tested this issue. It no longer applies to Drupal core. Therefore, this issue status is now "Needs work".

This does not mean that the patch necessarily needs to be re-rolled or the MR rebased. Read the Issue Summary, the issue tags and the latest discussion here to determine what needs to be done.

Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.

lisagodare’s picture

Re-rolled the patch from #86 for 10.3.x - this is just a crutch for now, ultimately the merge request is the better option.

lisagodare’s picture

I'm just going to try that again, this time with the missing new files.

roman_l’s picture

Thank you @lisagodare !

Applied the patch #109 with core 10.3.1 and it solves this creation issue i had with a custom bundle, + entity reference & views selection.

vija’s picture

Patch was working with Drupal 10.3.*, but doesn't work with Drupal 10.4

urashima82’s picture

Hi @vija ! Here is an update of the patch for Drupal 10.4.

vija’s picture

@urashima82 thanks, man!

#112 is indeed working perfectly with Drupal 10.4.x :)

kopeboy’s picture

Patch #112 applied cleanly to Drupal 10.5 too but it doesn't work for creating Users.

Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null: INSERT INTO "users_field_data" ("uid", "langcode", "preferred_langcode", "preferred_admin_langcode", "name", "pass", "mail", "timezone", "status", "created", "changed", "access", "login", "init", "default_langcode") VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13, :db_insert_placeholder_14); Array ( [:db_insert_placeholder_0] => 7 [:db_insert_placeholder_1] => it [:db_insert_placeholder_2] => it [:db_insert_placeholder_3] => [:db_insert_placeholder_4] => [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => [:db_insert_placeholder_7] => Europe/Rome [:db_insert_placeholder_8] => 0 [:db_insert_placeholder_9] => 1751017446 [:db_insert_placeholder_10] => 1751017446 [:db_insert_placeholder_11] => 0 [:db_insert_placeholder_12] => 0 [:db_insert_placeholder_13] => [:db_insert_placeholder_14] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 817 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

EDIT: actually, that's the same error I get when using the default reference method (with autocomplete widget), so the patch should be fine!

sboden’s picture

I had the patch from #112 running on Drupal 10.4.5, it stopped working after upgrading to Drupal 11.2.3

I had Claude Code rework the patch, and after a couple of tries it came up with attached files. It works for me, but I need other people to test.
The patch is in 2 pieces, because there are also 2 problems. This should also minimize re-rolling.

To include with cweagons patching:

     "drupal/core": {
        "2800875: SelectionPluginManager uasort() TypeError": "https://www.drupal.org/files/issues/2025-08-21/2800875-115-a-selection_plugin_manager_drupal_11.patch",
        "2800875: Fix for error 'This entity cannot be referenced' when creating new contact information paragraph": "https://www.drupal.org/files/issues/2025-08-21/2800875-115-b-views_selection_autocreate_drupal_11.patch"
      }
neograph734’s picture

Thank you for the efforts. I took an attempt myself, but because there is so much going on I had some trouble with it.

I don't think that 2 patches is the Drupal way. Each patch should resolve a specific issue (2 patches for one issue cannot be automatically tested either).
Could you please explain where you believe the split is? Then we might need to split up this issue?

Update
Are these incremental patches bases on #112?
There should be a single patch including all the code.

sboden’s picture

It's 2 issues which cause the problem in this issue:

Purpose for patch a: Fixes the SelectionPluginManager to handle missing plugin groups gracefully

- Problem: The original code assumed $selection_handler_groups[$base_plugin_id] always exists and is an array
- Solution: Adds defensive checks with fallback logic:
a. Checks if the requested plugin group exists and is an array
b. If not, tries to find any available group as fallback
c. As last resort, constructs a default plugin ID pattern ($base_plugin_id . ':' . $target_type)

Impact: Prevents fatal errors when entity reference fields use selection handlers that don't have the expected plugin group structure.
You can find other issues on drupal.org with the uasort error but with without autocreation. e.g. https://www.drupal.org/project/drupal/issues/3509376

Purpose of patch b: Implements autocreate functionality for ViewsSelection handlers

1. Interface Implementation:
- Implements SelectionWithAutocreateInterface
2. createNewEntity():
- Creates new entities with proper label and bundle
- Sets entity ownership if the entity supports it (EntityOwnerInterface)
- Uses entity type manager to handle storage operations
3. validateReferenceableNewEntities():
- Validates that newly created entities match allowed target bundles
- Handles both array and string bundle configurations
- Returns filtered array of valid entities

Impact: Allows entity reference fields using Views-based selection to automatically create referenced entities when they don't exist, improving user experience during data entry.

Patch "a" you always need, patch "b" there are different options. Patch b is a different way from the patch in #112.

sboden’s picture

And here is the rerolled patch from #112 (as close as possible) for Drupal 11(.2.3).

The difference between #115 and #118 is that:
- #115 tries to fix the problem without looking at past solutions.
- #118 is a re-roll of #112.

This code is a PITA. If it's not in before Drupal 12, we will need to reroll it again.

To include in cweagans patching:

    "drupal/core": {
        "2800875: Autocreate for entity reference selection handlers": "https://www.drupal.org/files/issues/2025-08-22/2800875-118-Autocreate_for_entity_reference_selection_handlers_drupal11.patch"
    }

oily made their first commit to this issue’s fork.

neograph734’s picture

Status: Needs work » Needs review

Changing to needs review. The latest pull request appears to be working for me. (Had some issues with the update because the plugin name was changed and my field was still configured for the earlier version.)

I assume that the test of #106 still needs to be written?

smustgrave’s picture

Status: Needs review » Needs work

Correct and the pipeline now has issues

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.