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.
Issue fork drupal-2800875
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
Comment #2
jonathanshawComment #3
jonathanshawLet's see what testbot makes of my first core patch ...
Comment #5
jonathanshawComment #7
jonathanshawRevised views.entity_reference.schema.yml to fix test fails.
Comment #8
jonathanshawAdded screenshot.
Comment #9
jonathanshawLooks like we need an EntityReferenceAutocreateTestTrait to share logic between EntityReferenceAutocreateTest and views/SelectionTest, now that this patch adds autocreate to the views selection handler.
Comment #10
jonathanshawYched said in #2577963: Let entity_ref Selection handlers be in charge of the field validation IS:
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."
Comment #11
jonathanshawFixed screenshot link
Comment #12
amateescu commentedThe 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 thecreateNewEntity()andvalidateReferenceableNewEntities()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?
Comment #13
jonathanshawWhat 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.
Comment #14
amateescu commentedThat'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.
Comment #15
almaudoh commented+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_tagswidget 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', thenDefaultSelection::buildEntityQuery()fails because my entity has no bundles.I'm wondering if this could be pulled out into a separate bug-fix issue.
Why are we re-initializing
$entity_typeinside the if statement?The second
returnstatement will never run.Comment #16
jonathanshaw@amateescu #14
Agreed
@almaudoh #15
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.
Comment #17
jonathanshawCreated #2821352: EntityReferenceAutocompleteWidget::getAutocreateBundle() unnecessarily requires the 'target_bundles' setting, some guidance needed on whether/what tests are needed.
Comment #19
crizThis 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.
Comment #20
crizSorry, this is the right one.
Comment #21
mitsuroseba commentedAdd additional check for 'auto_create' settings.
Comment #22
welly commentedPatch at #7 wasn't applying to 8.3.x. Rerolled and tested - works great. Thanks all. Will need tests though.
Comment #23
welly commentedApologies to @mitsuroseba - hadn't refreshed my browser window while I was uploading my patch.
Comment #24
welly commentedMinor amend to the patch
Comment #26
mirsoft commentedPatch rerolled for 8.4.0 / 8.5.x-dev . Manually tested. Still needs automated tests.
Comment #27
mirsoft commentedComment #28
jonathanshaw@amteescu in #12 / #14 said:
As I interpret it this means the most helpful thing core could do for ViewsSelection handler is:
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.
Comment #29
amateescu commented@jonathanjfshaw, the first and the second points from #28 are spot on, but I don't agree with the third one.
createNewEntity()andvalidateReferenceableNewEntities()go hand in hand in regards to what fields need to be created bycreateNewEntity()so that the created entity is valid forvalidateReferenceableNewEntities().That would be the minimum, yes, but in reality
validateReferenceableNewEntities()has to implement the proper checks for the field values that were assigned increateNewEntity().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 :)
Comment #30
amateescu commentedI think we agree on the direction for this patch so NW is a better status.
Comment #33
naveenvalechaHere's straight reroll for 8.7.x
Next: Add tests and address the direction
Assigning to myself for it.
Comment #34
anavarreNaveen, are you still working on this?
Comment #35
anavarreUnassigning for now.
Comment #36
panchoPostponing this feature request on #2821352: EntityReferenceAutocompleteWidget::getAutocreateBundle() unnecessarily requires the 'target_bundles' setting for now.
Comment #38
Dirst commentedHello, this patch works with 8.7.2
Comment #39
geek-merlinPatch 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.
Comment #41
patrickfwestonI've rerolled the patch in #38 for Drupal 8.8 and have tested it on our site.
Comment #42
rob230 commentedFor some reason #37 and #39 do not apply to 8.7 for me. I've rerolled #39 so that it will apply.
Comment #44
rynebl commented#42 worked for 8.9.2, awesome stuff.
Comment #45
chr.fritschRerolled for Drupal 9. It still requires #2821352: EntityReferenceAutocompleteWidget::getAutocreateBundle() unnecessarily requires the 'target_bundles' setting
Comment #46
geek-merlinComment #47
jonathanshawComment #48
chr.fritschBlocker is in. We still need tests
Comment #49
jonathanshawThe whole approach needs reworking per #28 / #29
Comment #50
chr.fritschHere is the new approach.
Comment #51
jonathanshawYay! That's a huge step forward.
I don't understand why these changes are needed.
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?
Comment #52
chr.fritsch1. Without putting that code up front, in the test I never got the
auto_create_bundlevalue, because withouttarget_bundlesalways 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.
Comment #53
jonathanshawOK about #51.1, and for #51.2 let's see what the committer wants.
Comment #54
alexpottI 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.
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.
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.
Comment #55
chr.fritschAfter 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:
Comment #56
alexpottWe need some documentation of these methods.
Comment #57
chr.fritschAdded the missing docs.
Comment #58
jonathanshaw+1 to the direction.
Does checking for SelectionWithAutocreateInterface makes sense now that this method is only called explicitly on a handler that wants it.
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
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?
Comment #59
chr.fritschThank you @jonathanshaw
Regarding:
#58-1:
You are right. I removed the if clause
#58-2:
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?
Comment #60
jonathanshawnit: 'by' the bundle name.
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.
Comment #61
jonathanshawThis looks like it will change the behavior of autocreate on fields that reference deleted bundles. Probably for the better.
Comment #63
ashu1629 commentedThe patch mentioned in #59 is not working with drupal 9.1+ versions. Requesting a reroll for this patch.
Comment #64
ashu1629 commentedAdding rerolled patch which works with Drupal 9.1.7. Please review.
Comment #65
ashu1629 commentedComment #66
jonathanshawComment #67
suresh prabhu parkala commentedTried to fix custom commands failure. Please review.
Comment #69
imalabyaNeeded a Patch for 8.9.x.
Comment #70
vsujeetkumar commentedFixed fail tests because of "Undefined variable: selected_bundles", Please have a look and advise.
Comment #71
vsujeetkumar commentedComment #74
brentgRerolled the patch from #33 to be compatible with the 8.9.x version
Comment #75
benito25 commentedI had this problem with Inline Entity Form Complexe in Drupal 9.2.
I added patch 70 and it's work perfectly.
Thanks a lot.
Comment #76
damiengr commentedPatch #70 works perfectly with Drupal 9.2
Thank you !
Comment #77
ultrabob commentedI'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.
Comment #79
jnrfred commentedPatch in #70 works for me too on Drupal 9.2
Comment #80
pminfUsing 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?
Comment #81
quietone commentedThe 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.
Comment #82
immaculatexavier commentedRerolled patch against 10.0.x
Attached Reroll diff against #70
Comment #83
medha kumariRerolled patch #82 with 10.1.x.
Comment #84
pooja saraah commentedFixed failed commands on #83
Attached patch against Drupal 10.1.x
Comment #85
nod_The last patch doesn't pass commit checks, could you make sure to run
./core/scripts/dev/commit-code-check.shbefore 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!
Comment #86
pradhumanjain2311 commentedTry to fix patch #84 CCF errors.
Taking reference from patch #82.
Comment #87
smustgrave commentedThis 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?
Comment #91
narendrarRe #87: Fixed CI failures & added CR.
It will create an article with the title passed in input box.
Comment #92
narendrarUpdate IS also.
Comment #93
smustgrave commentedCleaning 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
Comment #94
narendrarHi @smustgrave, Thanks for the review.
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?
Comment #95
smustgrave commentedRetested on a fresh install and seems to be adding to the correct vocabulary now.
Comment #96
quietone commentedI'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!
Comment #97
quietone commentedI 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.
Comment #98
quietone commentedThere 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.
Comment #100
narendrarComment #105
tobiasbComment #106
tobiasbI 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.
Comment #107
needs-review-queue-bot commentedThe 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.
Comment #108
lisagodareRe-rolled the patch from #86 for 10.3.x - this is just a crutch for now, ultimately the merge request is the better option.
Comment #109
lisagodareI'm just going to try that again, this time with the missing new files.
Comment #110
roman_l commentedThank 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.
Comment #111
vija commentedPatch was working with Drupal 10.3.*, but doesn't work with Drupal 10.4
Comment #112
urashima82 commentedHi @vija ! Here is an update of the patch for Drupal 10.4.
Comment #113
vija commented@urashima82 thanks, man!
#112 is indeed working perfectly with Drupal 10.4.x :)
Comment #114
kopeboyPatch #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!
Comment #115
sboden commentedI 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:
Comment #116
neograph734Thank 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.
Comment #117
sboden commentedIt'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.
Comment #118
sboden commentedAnd 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:
Comment #120
neograph734Changing 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?
Comment #121
smustgrave commentedCorrect and the pipeline now has issues