Problem/Motivation

See part 2 at #3347343: Add Views EntityReference filter to support better UX for exposed filters

One major piece of functionality from the D7 Entity Reference module was left out entirely in #1801304: Add Entity reference field: the ability to render exposed views filters as a select list or autocomplete of available entities.

Proposed resolution

Create a new Views Entity Reference filter plugin to be available for all entity reference fields and migrate the existing taxonomy filters to be based on the new generic filter plugin.

How to use

  1. Add on an entity type / bundle an entity reference field, ex field_test_reference.
  2. Create a view displaying this entity type.
  3. Add a filter on the view for field_test_reference.
  4. Configure the entity selection mode and the widget display mode.
  5. Configure the filter behavior (ex: required, multiple, etc.)
  6. Finally use the filter field for filtering the results based on the selected entity from the autocomplete or select list.

Remaining tasks

  • ☑ support for content entity reference
  • ☑ support for configuration entity reference
  • ☑ support for content with and without bundles
  • ☑ taxonomy filter rebased on generic entity reference
  • ☑ settings forms to configure the filter
  • ☑ display widget in select or autocomplete
  • ☑ filter values based on reference view
  • ☑ filter values based on bundles
  • ☑ maximum filter values in select list for performance concerns
  • ☑ sort for filter values when in bundle selection handler mode
  • ☑ argument support for when view selection handler is used
  • ☑ views configuration schema update
  • ☐ existing configuration migration (no longer needed if we create a new filter only)
  • ☐ fix select option (#208, #215)
  • ☑ tests
  • ☐ get framework manager approval
  • ☐ write change record

Post tasks

  • ☐ follow-up task to have TaxonomyIndexTid use this entity reference plugin
  • ☐ conversion of the "authored by" filter to use the entity reference filter
  • ☐ extract selection handler form logic in separate plugins that will specialize for rendering and validating the filter selection config form
  • ☐ caching of the value form?
  • ☐ documentation updates
  • #3339738: Convert TaxonomyIndexTid to use new EntityReference filter

User interface

UI
UI

UI UI

Known issues

  • CANNOT REPRODUCE ATM sometimes when switching between widget it gets stuck on the previous selected one
  • FIXED when switching between the widget types the previous value is left in the exposed form and it's incompatible with the other widget type
  • FIXED triggering ajax requests on the extra options form right after adding the filter brings you back to the add handler form fixed

API changes

None.

CommentFileSizeAuthor
#547 2429699-546-10.4.x.patch3.37 KBngal
#545 2429699-546-10.3.x.patch50.69 KBbiancaradu27
#523 interdiff 521-2429699-entity-reference-views-filter-d101.txt11.16 KBgraber
#521 drupal-views-entity-reference-filter-2429699-521.patch2.67 KBmedha kumari
#519 interdiff_510-519.txt1.2 KBdaniel.rolls@flightcentre.com.au
#519 drupal-views-entity-reference-filter-2429699-519.patch66.51 KBdaniel.rolls@flightcentre.com.au
#510 interdiff_491-510.txt1.01 KBmuriqui
#510 drupal-views-entity-reference-filter-2429699-510.patch66.47 KBmuriqui
#502 interdiff_491-502.txt61.79 KBasad_ahmed
#502 2429699-502.patch2.67 KBasad_ahmed
#491 interdiff-2429699-488-491.txt1.85 KBscott_euser
#491 drupal-views-entity-reference-filter-2429699-491.patch66.22 KBscott_euser
#491 2022-07-25_20-22.png160.81 KBscott_euser
#488 interdiff-2429699-487-488.txt3.2 KBscott_euser
#488 drupal-views-entity-reference-filter-2429699-488.patch66.34 KBscott_euser
#487 interdiff-2429699-486-487.txt2.4 KBscott_euser
#487 drupal-views-entity-reference-filter-2429699-487.patch66.6 KBscott_euser
#486 drupal-views-entity-reference-filter-2429699-486.patch66.78 KBscott_euser
#486 interdiff-2429699-476-486.txt50.27 KBscott_euser
#483 drupal-views-entity-reference-filter-2429699-483.patch49.66 KBakalam
#476 interdiff-2429699-473-476.txt3 KBscott_euser
#476 drupal-views-entity-reference-filter-2429699-476.patch46.74 KBscott_euser
#473 interdiff-2429699-471-473.txt565 bytesscott_euser
#473 drupal-views-entity-reference-filter-2429699-473.patch47.1 KBscott_euser
#471 drupal-views-entity-reference-filter-2429699-471.patch47.88 KBscott_euser
#471 interdiff-2429699-470-471.txt741 bytesscott_euser
#470 update-hook-2429699-comment-470-onwards-add-to-your-own-module.txt1.61 KBscott_euser
#470 2022-04-07_07-54.png46.09 KBscott_euser
#470 interdiff-2429699-453-470.txt4.25 KBscott_euser
#470 drupal-views-entity-reference-filter-2429699-470.patch48.84 KBscott_euser
#453 2429699-453-9.3.x.patch49.1 KBseanb
#452 interdiff-2429699-439-446.txt14.28 KBmicnap
#446 2429699-446.patch54.79 KBcatch
#439 2429699-439.patch48.91 KBldavidsp
#436 2429699-436.patch2.96 KBldavidsp
#435 2429699-435.patch2.96 KBldavidsp
#429 interdiff-2429699-427-429.txt1.36 KByogeshmpawar
#429 2429699-429.patch54.79 KByogeshmpawar
#427 interdiff-2429699-424-427.txt1.9 KByogeshmpawar
#427 2429699-427.patch54.79 KByogeshmpawar
#424 reroll_diff_2429699_421-424.txt3.08 KBankithashetty
#424 2429699-424.patch50 KBankithashetty
#421 2429699-421.patch49.96 KBnickdickinsonwilde
#420 2429699-420.patch50.08 KBcatch
#419 2429699-419.patch49.71 KBcatch
#418 2429699-418-with-term-reference-fields.patch78.28 KBnixou
#414 2429699-414.patch49.71 KBklaasvw
#413 2429699-9.1-413.patch49.69 KBwillpeps
#409 2429699-9.1-409.patch49.69 KBjacobbell84
#404 interdiff.txt542 byteskapilv
#404 2429699-404.patch49.71 KBkapilv
#401 2429699-9.2-400.patch49.71 KBmr.york
#401 2429699-9.1-400.patch56.15 KBmr.york
#400 2429699-8.9.x-399.patch49.62 KBmr.york
#399 interdiff-393-399.txt974 bytesmr.york
#399 2429699-8.9.x-399.patch52.91 KBmr.york
#398 2429699-8.9.x-398.patch49.44 KBmr.york
#397 interdiff-393-397.txt974 bytesmr.york
#397 2429699-8.9.x-397.patch49.53 KBmr.york
#393 2429699-8.9.x-392.patch53.62 KBluksak
#392 2429699-8.9.x-392.patch0 bytesluksak
#391 Screenshot from 2021-04-07 16-06-02.png41.73 KByepa
#389 interdiff-387-389.txt542 bytessokru
#389 2429699-389.patch48.91 KBsokru
#387 interdiff-MR18-387.txt2.6 KBsokru
#387 2429699-387.patch48.91 KBsokru
#385 2429699-8.9.x-385.patch53.55 KBa.dmitriiev
#382 core-2429699-views_er_filter-382.patch48.76 KBczigor
#379 screenshot-drupal9.ddev_.site-2020.11.28-07_23_57.png114.71 KBscott_euser
#371 interdiff_369-371.txt1.4 KBklaasvw
#371 2429699-371--on-9_0_x.do-not-test.patch47.24 KBklaasvw
#371 drupal-views-entity-reference-filter-2429699-371.patch47.22 KBklaasvw
#369 drupal-views-entity-reference-filter-2429699-369.patch46.34 KBscott_euser
#369 interdiff-2429699-368-369.txt5.63 KBscott_euser
#368 interdiff-2429699-366-368.txt1.65 KBscott_euser
#368 drupal-views-entity-reference-filter-2429699-368.patch40.53 KBscott_euser
#367 interdiff-2429699-364-366.txt58.87 KBscott_euser
#367 interdiff-2429699-351-366.txt28.76 KBscott_euser
#367 drupal-views-entity-reference-filter-2429699-366.patch40.48 KBscott_euser
#364 interdiff_362_364.txt27.44 KBanmolgoyal74
#364 2429699-364.patch63.51 KBanmolgoyal74
#362 interdiff_361_362.txt53.92 KBkapilv
#362 2429699-362.patch36.35 KBkapilv
#361 drupal-generalize-taxonomyindextid-filter-2429699-301.patch77.87 KBnono95230
#354 2429699-354--on-8_9_x.do-not-test.patch45.02 KBmparker17
#354 2429699-354--on-9_0_x.do-not-test.patch45.02 KBmparker17
#354 2429699-354--on-9_1_x.patch45.05 KBmparker17
#354 interdiff--251-254.txt1.48 KBmparker17
#351 2429699-351--on-9_1_x.patch44.61 KBmparker17
#351 2429699-351--on-9_0_x.do-not-test.patch44.59 KBmparker17
#351 2429699-351--on-8_9_x.do-not-test.patch44.59 KBmparker17
#334 2429699-334.patch43.7 KBkrzysztof domański
#325 drupal-generalize-taxonomyindextid-filter-2429699-325.patch43.7 KBscott_euser
#325 interdiff-2429699-323-325.txt621 bytesscott_euser
#323 interdiff-2429699-311-323.txt6.9 KBscott_euser
#323 drupal-generalize-taxonomyindextid-filter-2429699-323.patch43.69 KBscott_euser
#311 interdiff-2429699-297-311.txt837 bytesmurz
#311 drupal-generalize-taxonomyindextid-filter-2429699-311.patch44.55 KBmurz
#297 interdiff-2429699-295-297.txt887 bytesscott_euser
#297 drupal-generalize-taxonomyindextid-filter-2429699-297.patch44.58 KBscott_euser
#295 interdiff-2429699-277-295.txt28.52 KBscott_euser
#295 drupal-generalize-taxonomyindextid-filter-2429699-295.patch45.7 KBscott_euser
#294 interdiff_267-277.txt301 bytesMokshit06
#293 interdiff_276-277.txt79.29 KBMokshit06
#292 filter-select-list-for-entity-reference-field.jpg14.45 KBscott_euser
#292 filter-text-field-for-entity-reference-field.jpg13.58 KBscott_euser
#292 verf-entity-reference-filter.png45.77 KBscott_euser
#292 selection-type.png4.28 KBscott_euser
#277 drupal-generalize-taxonomyindextid-filter-2429699-277.patch77.07 KBscott_euser
#277 interdiff-2429699-276-277.txt301 bytesscott_euser
#277 interdiff-2429699-271-277.txt879 bytesscott_euser
#276 interdiff-2429699-271-276.txt904 bytesmdolnik
#276 drupal-generalize-taxonomyindextid-filter-2429699-276.patch77.07 KBmdolnik
#272 interdiff-2429699-267-271.txt583 bytesscott_euser
#272 drupal-generalize-taxonomyindextid-filter-2429699-271.D8.patch76.92 KBscott_euser
#267 interdiff-2429699-263-267.txt17.39 KBscott_euser
#267 drupal-generalize-taxonomyindextid-filter-2429699-267.D8.patch76.93 KBscott_euser
#263 drupal-n2429699-263-88x.patch66.67 KBkasey_mk
#262 drupal-n2429699-262-88x.patch33.99 KBkasey_mk
#255 Screen Shot 2019-12-09 at 11.32.47 AM.png49.54 KBsuperfluousapostrophe
#253 2429699-253.patch72.98 KBheddn
#240 drupal-n2429699-232-87x.patch66.62 KB_Archy_
#232 drupal-n2429699-232-87x.patch66.62 KBdamienmckenna
#231 drupal-n2429699-214-225.interdiff.txt13.84 KBdamienmckenna
#225 generic_entityreference_filter_2429699-225.patch72.89 KB_Archy_
#225 interdiff-223-225.txt8.08 KB_Archy_
#223 generic_entityreference_filter_2429699-223.patch76.14 KB_Archy_
#223 interdiff-219-223.txt4.17 KB_Archy_
#219 generic_entityreference_filter_2429699-219.patch75.99 KB_Archy_
#219 interdiff-212-219.txt3.85 KB_Archy_
#214 drupal-n2429699-212-877.patch64.91 KBdamienmckenna
#212 drupal-n2429699-212.patch71.32 KBdamienmckenna
#206 generic_entityreference_filter_2429699-206-reroll-8.7.x.patch71.23 KBnuez
#204 generic_entityreference_filter_2429699-204-reroll-8.7.x.patch71.23 KBnuez
#199 2429699_196-199_interdiff.txt1.56 KBpancho
#199 generic_entityreference_filter_2429699-199.patch71.24 KBpancho
#196 2429699_194-196_interdiff.diff13.11 KBpancho
#196 generic_entityreference_filter_2429699-196.patch71.13 KBpancho
#194 2429699_191-194_interdiff.diff2.21 KBpancho
#194 generic_entityreference_filter_2429699-194.patch69.66 KBpancho
#191 2429699_190-191_interdiff.txt25.81 KBpancho
#191 generic_entityreference_filter_2429699-191.patch69.47 KBpancho
#190 2429699_186_190_interdiff.txt1.1 KBpancho
#190 generic_entityreference_filter_2429699_190.patch67.98 KBpancho
#187 generic_entityreference_filter_2429699-186.patch67.86 KB_Archy_
#187 2429699_184-186_interdiff.txt10.65 KB_Archy_
#184 generic_entityreference_filter_2429699-184.patch65.13 KB_Archy_
#184 2429699_182-184_interdiff.txt4.6 KB_Archy_
#184 screenshot-drupal-dev.lndo_.site-2019.06.13-15-16-44.png20.61 KB_Archy_
#184 screenshot-drupal-dev.lndo_.site-2019.06.13-15-17-40.png35.4 KB_Archy_
#184 screenshot-drupal-dev.lndo_.site-2019.06.13-15-19-23.png12.33 KB_Archy_
#184 screenshot-drupal-dev.lndo_.site-2019.06.13-15-14-22.png7.63 KB_Archy_
#182 2429699_181-182_interdiff.txt11.53 KB_Archy_
#182 generic_entityreference_filter_2429699-182.patch64.83 KB_Archy_
#181 2429699_180-181_interdiff.txt6.56 KBpancho
#181 generic_entityreference_filter_2429699-181.patch62.64 KBpancho
#180 2429699_179-180_interdiff.txt4.45 KBpancho
#180 generic_entityreference_filter_2429699-180.patch62.56 KBpancho
#179 2429699_178-179_interdiff.txt8.69 KBpancho
#179 generic_entityreference_filter_2429699-179.patch62.33 KBpancho
#178 2429699_177-178_interdiff.txt848 bytespancho
#178 generic_entityreference_filter_2429699-178.patch61.78 KBpancho
#177 generic_entityreference_filter_2429699-177.patch61.61 KBpancho
#167 22429699-148_162.interdiff.txt610 bytesdww
#162 generic_entityreference_filter_22429699-162.patch61.6 KBoriol_e9g
#159 generic_entityreference_filter_22429699-159.patch30.07 KBoriol_e9g
#148 generic_entityreference_filter_22429699-148.patch61.6 KBpancho
#148 22429699_147-148_interdiff.txt2.08 KBpancho
D7_entity_reference___Site-Install.png114.61 KBjhedstrom
Entity_reference_exposed_filter__Content____Site-Install.png162.37 KBjhedstrom
#2 entity-reference-exposed-filters-2429699-02.patch6.25 KBjhedstrom
#10 Content Content Site-Install.png31.24 KBberdir
#17 interdiff.txt18.82 KBjhedstrom
#17 entity-reference-exposed-filters-2429699-17.patch20.61 KBjhedstrom
#24 interdiff.txt1.09 KBjhedstrom
#24 entity-reference-exposed-filters-2429699-24.patch20.62 KBjhedstrom
#34 entity-reference-exposed-filters-2429699-34.patch18.67 KBtaran2l
#36 entity-reference-exposed-filters-2429699-36.patch19.98 KBtaran2l
#39 entity-reference-exposed-filters-2429699-36-39-interdiff.txt1.67 KBjsst
#39 entity-reference-exposed-filters-2429699-39.patch20.2 KBjsst
#45 interdiff-45-39.txt16.4 KB_Archy_
#45 entity_reference_view_filter-2429699-45.patch17.2 KB_Archy_
#47 entity_reference_view_filter-2429699-47.patch27.02 KB_Archy_
#50 interdiff-47-50.txt7.94 KB_Archy_
#50 entity_reference_view_filter-2429699-50.patch27.96 KB_Archy_
#52 interdiff-50-52.txt800 bytes_Archy_
#52 entity_reference_view_filter-2429699-52.patch28.22 KB_Archy_
#55 entity_reference_view_filter-2429699-55-D8-2.patch3.6 KB_Archy_
#56 entity_reference_view_filter-2429699-56-D8-2.patch28.01 KB_Archy_
#59 entity_reference_view_filter-2429699-59.patch27.27 KB_Archy_
#59 interdiff-56-59.txt17.6 KB_Archy_
#60 entity_reference_view_filter-2429699-60-D8-2-x.patch27.27 KB_Archy_
#63 interdiff-59-63.txt1.73 KB_Archy_
#63 entity_reference_view_filter-2429699-63.patch27.41 KB_Archy_
#63 entity_reference_view_filter-2429699-63-D8-2-x.patch27.41 KB_Archy_
#70 entity_reference_view_filter-2429699-70.patch27.45 KBdas-peter
#70 interdiff-2429699-63-70.diff814 bytesdas-peter
#74 2429699-74-content.png39.78 KBleksat
#74 2429699-74-view.png248.73 KBleksat
#81 interdiff-70-81.txt16.36 KB_Archy_
#81 entity_reference_view_filter-2429699-81.patch31.97 KB_Archy_
#87 entity_reference_view_filter-2429699-87.patch32.64 KBluksak
#87 interdiff.txt4.43 KBluksak
#92 2429699-92.patch32.67 KBseanb
#92 interdiff-87-92.txt717 bytesseanb
#99 views-entityreference-filter-2429699-99.patch32.62 KBckaotik
#99 interdiff-2429699-92-99.txt7.26 KBckaotik
#104 views-entityreference-filter-selection-2429699-104-interdiff.txt8.15 KBberdir
#104 Selection_277.png30.53 KBberdir
#107 2429699-107.patch35.94 KBrosk0
#107 2429699-interdiff-99-107.txt145 bytesrosk0
#107 2429699-interdiff-104-107.txt0 bytesrosk0
#108 2429699-interdiff-99-107.txt13.46 KBrosk0
#108 2429699-interdiff-104-107.txt10.66 KBrosk0
#111 2429699-111.patch38.03 KBrosk0
#111 2429699-107-111-interdiff.txt21.61 KBrosk0
#114 22429699-114.patch32.56 KBrlmumford
#114 interdiff.txt12.95 KBrlmumford
#119 22429699-114-119_interdiff.txt3.66 KBpancho
#119 generic_entityreference_filter_22429699-119.patch31.92 KBpancho
#121 22429699-114-121_interdiff.txt6.82 KBpancho
#121 22429699-119-121_interdiff.txt4.43 KBpancho
#121 generic_entityreference_filter_22429699-121.patch31.9 KBpancho
#123 22429699-114-123_interdiff.txt7.96 KBpancho
#123 22429699-121-123_interdiff.txt1.61 KBpancho
#123 generic_entityreference_filter_22429699-123.patch32.49 KBpancho
#124 filter groups.mkv247.84 KBpancho
#125 configure_filter.mkv194.05 KBpancho
#126 22429699-114-126_interdiff.patch8.79 KBpancho
#126 22429699-123-126_interdiff.patch854 bytespancho
#126 generic_entityreference_filter_22429699-126.patch33.49 KBpancho
#128 22429699-114-128_interdiff.txt9.33 KBpancho
#128 22429699-126-128_interdiff.txt2.95 KBpancho
#128 generic_entityreference_filter_22429699-128.patch33.8 KBpancho
#130 22429699-114-130_interdiff.txt9.65 KBpancho
#130 22429699-128-130_interdiff.txt633 bytespancho
#130 generic_entityreference_filter_22429699-130.patch33.8 KBpancho
#131 22429699-114-131_interdiff.txt25.6 KBpancho
#131 22429699-130-131_interdiff.txt16.22 KBpancho
#131 generic_entityreference_filter_22429699-131.patch49.78 KBpancho
#133 22429699-114-133_interdiff.txt27.16 KBpancho
#133 22429699-131-133_interdiff.txt3.16 KBpancho
#133 generic_entityreference_filter_22429699-133.patch50.54 KBpancho
#135 22429699-114-135_interdiff.txt38.16 KBpancho
#135 22429699-133-135_interdiff.txt13.52 KBpancho
#135 generic_entityreference_filter_22429699-135.patch56.9 KBpancho
#137 22429699-114-137_interdiff.txt38.12 KBpancho
#137 22429699-135-137_interdiff.txt609 bytespancho
#137 generic_entityreference_filter_22429699-137.patch56.9 KBpancho
#139 22429699-114-139_interdiff.txt38.78 KBpancho
#139 22429699-137-139_interdiff.txt2.7 KBpancho
#139 generic_entityreference_filter_22429699-139.patch57.73 KBpancho
#141 22429699-114-141_interdiff.txt42.76 KBpancho
#141 22429699-139-141_interdiff.txt4.86 KBpancho
#141 generic_entityreference_filter_22429699-141.patch61.63 KBpancho
#147 22429699_141-147_diff.txt2 KBpancho
#147 generic_entityreference_filter_22429699-147.patch61.67 KBpancho

Issue fork drupal-2429699

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

geertvd’s picture

Assigned: Unassigned » geertvd

I'll have a crack at this.

jhedstrom’s picture

Status: Active » Needs work
StatusFileSize
new6.25 KB

@geertvd here's a very rough start that will hopefully be of some use.

jhedstrom’s picture

+++ b/core/modules/entity_reference/src/ConfigurableEntityReferenceItem.php
@@ -39,6 +39,11 @@ public static function defaultStorageSettings() {
+      'views_select_list' => TRUE,

Oops, that was defaulted to TRUE for debugging...should be FALSE.

geertvd’s picture

Assigned: geertvd » Unassigned

I'm a bit lost with this one but maybe these comments are useful.

+++ b/core/modules/entity_reference/src/Plugin/views/filter/EntityReference.php
@@ -0,0 +1,82 @@
+    // @todo How to get a FieldDefinitionInterface (required by
+    // getSelectionHandler) without a bundle? `$configuration` contains
+    // `entity_type` and `field_name` parameters.

I thought we could use FieldAPIHandlerTrait for that which has a method getFieldDefinition but it seems this object is not complete enough to get the selectionHandler.

I also wonder how this should behave. in D7 "target bundles" is a field setting but now it seems this it's a field instance setting.

jhedstrom’s picture

Oh cool, I didn't know about FieldAPIHandlerTrait, that looks promising. However, as you note, the fact that target bundles now reside at the field setting level is going to be problematic here.

xjm’s picture

This seems like a feature request to me, not a bug? It's okay not to have feature parity with D7 contrib modules. Views doesn't either.

berdir’s picture

The point is that you can do that with taxonomy term references*. And we want to replace them with ER, so we lose that feature, and I think this is important.

We also had criticals around the regression that it was not possible to expose list fields as exposed filter, nobody there said that's not a regression because views was contrib in 7.x :)

* Not in the same way, instead, the filter plugin asks you if you want autocomplete or a select. That seems actually like the preferred option to me?

berdir’s picture

Issue summary: View changes
StatusFileSize
new31.24 KB

This is what I was talking about:

Shouldn't we just port this behavior to the entity reference filter plugin, no need to make it configurable per field type?

xjm’s picture

Version: 8.0.x-dev » 8.1.x-dev
Category: Bug report » Feature request
Status: Needs work » Postponed

So see #1847596-223: Remove Taxonomy term reference field in favor of Entity reference from @berdir. For taxonomy, there will be no change. I think it's acceptable for core to ship without this feature of D7 entity reference, and so I think that makes this issue a feature request (and therefore targeted for 8.1.x or later if we do decide to add it to core). If there are other regressions please add more detail here. Thanks!

jhedstrom’s picture

If core ships with this as is, even contrib will not be able to replace the functionality without swapping out the entity reference field type. As long as bundle settings live with the field config, rather than the storage settings, views can't narrow the items down below entity type (eg, all nodes).

As far as this being a feature request, I think this will be seen as a major regression when folks have been told entity reference has been moved to core.

berdir’s picture

I'm confused, what does that have to do with this issue?

jhedstrom’s picture

Followed up with Berdir in IRC to clarify:

since the bundle settings live with the field, rather than the storage, the Views filter plugin has no way to get at those, so it can only expose a list of all entities, rather than just a list of a selected bundle

yched’s picture

The 'target_bundle' setting is a red herring, it is not used by anything anymore - see #2064191-4: Fix the 'target_bundle' field setting - 'target_bundles' are not validated when entity_reference is enabled

jhedstrom’s picture

Looking into how the current taxonomy reference handles this, the bundle (vid) setting is actually on the Views filter, so contrib could actually mimic this functionality until this goes into core.

The tests for this functionality reside in TaxonomyIndexTidUiTest.

jhedstrom’s picture

Status: Postponed » Needs review
Issue tags: -VDC
StatusFileSize
new18.82 KB
new20.61 KB

This gets everything working as expected. I had to use the handler settings from field config on the view filter settings, but this actually worked out quite well.

Setting to needs review so tests can run.

Also removing the VDC tag since this really has nothing to do with that.

Status: Needs review » Needs work

The last submitted patch, 17: entity-reference-exposed-filters-2429699-17.patch, failed testing.

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 17: entity-reference-exposed-filters-2429699-17.patch, failed testing.

jhedstrom’s picture

Version: 8.1.x-dev » 8.0.x-dev
Status: Needs work » Needs review

Aaah. Version temporarily back to 8.0.x to get testbot happy.

Status: Needs review » Needs work

The last submitted patch, 17: entity-reference-exposed-filters-2429699-17.patch, failed testing.

jhedstrom’s picture

Status: Needs work » Needs review
StatusFileSize
new1.09 KB
new20.62 KB

Fixes schema error in test view.

jhedstrom’s picture

Version: 8.0.x-dev » 8.1.x-dev

Back to 8.1.

jhedstrom’s picture

Title: Entity Reference field missing 'Render Views filters as select list' option » Generalize TaxonomyIndexTid filter to be available for all entity reference fields
Version: 8.1.x-dev » 8.0.x-dev
Category: Feature request » Task
Issue summary: View changes
Status: Needs review » Needs work

Since #1847596: Remove Taxonomy term reference field in favor of Entity reference landed, I think this can safely be re-categorized as a task, rather than a feature request?

Version: 8.0.x-dev » 8.1.x-dev

Drupal 8.0.6 was released on April 6 and is the final bugfix release for the Drupal 8.0.x series. Drupal 8.0.x will not receive any further development aside from security fixes. Drupal 8.1.0-rc1 is now available and sites should prepare to update to 8.1.0.

Bug reports should be targeted against the 8.1.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.2.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

jlbellido’s picture

Version: 8.1.x-dev » 8.2.x-dev

Since it's a task, not a bug, it think this should be done at 8.2.x-dev.

jlbellido’s picture

I'll try to reroll #24 for being applied to 8.2.x-dev

colan’s picture

There's a contrib module over at Entity Reference Exposed Filters. I haven't looked at the code so I'm not sure if it would help with what we're trying to do here.

There's also a blog post over at Entity reference filter with Drupal 8.

howards’s picture

I hope the "render views filter as select list" feature gets looked at again and will do my best to help provide any information and even potentially patches if I can find the time. Initially I tried patching the Drupal code base with the patch in #24 but it no longer applies due to changes in core. Hoping to reference the related changes in an effort to coalesce the related changes and make it easier both for myself and others to take a stab at a patch.

Two files referenced in the patch were removed via #2429191-189: Deprecate entity_reference.module and move its functionality to core and the committed patch might provide some insight into integration areas.

Edit: the commit is 97823b5a

howards’s picture

It appears the original issue title appears more correct, as it seems to be purely a views exposed filter issue, not necessarily a TaxonomyIndexTid filter. That said, it also appears the TaxonomyIndexTid filter does provide somewhat of a roadmap to get there through entity reference and views configurations.

Similarly, as I was looking to re-roll the patch in #24 to D8.2.x, information in the entity_reference module is deprecated in 8.x. I can reroll a patch that recreates a similar structure, but I don't think that's the correct path to go down in terms of down the road given the deprecation notice. It seems like a short-term, non-commitable fix. (Am I wrong? Is it something that will just need a forward-port in a couple of years?)

Would the right way to go be adding a pluggable module in core/modules/views/src/Plugin/views/filter, or even adding code to an existing plugin, as most views filters are placed? There is also other code that exists to provide appropriate exposed taxa filters, but seem to be generally contained within the core/modules/taxonomy module. Many parts of the taxonomy module are deprecated as well, along with removal in D9.x.

I am not a particularly adept coder, although I can read it understand it; reproducing it is a different story. (I can try, but it is open to all sorts of scrutiny; I welcome the scrutiny because it will help me to get better.)

I am lost as to what to do or where to focus, or how best to approach it. Any guidance would be appreciated.

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

Drupal 8.2.0-beta1 was released on August 3, 2016, which means new developments and disruptive changes should now be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

taran2l’s picture

Status: Needs work » Needs review
StatusFileSize
new18.67 KB

Re-roll against 8.2.x

Status: Needs review » Needs work

The last submitted patch, 34: entity-reference-exposed-filters-2429699-34.patch, failed testing.

taran2l’s picture

Status: Needs work » Needs review
StatusFileSize
new19.98 KB

Fixed incorrect schema

Status: Needs review » Needs work

The last submitted patch, 36: entity-reference-exposed-filters-2429699-36.patch, failed testing.

i.bajrai’s picture

I have patched Drupal using #36.

Go to the field you want to update and under field setting is the familiar checkbox.

Flush the caches.

Then update the exposed filter in your view.

Pretty sure this can RBTC?

jsst’s picture

I've attached a new patch based on #39 (see interdiff) to support references between entities of different types (#39 used entity_type where I believe target_type was intended).

I've also changed getValueOptions to support not having any bundles selected (my entities don't have bundles!). I'm not sure about that should that be supported? I have to override getSelectionHandlerOptions() to make the filter work without bundles:

  /**
   * Helper method to get selection handler options.
   *
   * @return array
   *   Array of options matching SelectionBase options.
   */
  protected function getSelectionHandlerOptions() {
    $options = ['target_type' => $this->configuration['target_type']];

    // Don't filter on bundles.
    $options['handler_settings']['target_bundles'] = NULL;

    $options['handler_settings']['sort'] = $this->options['sort'];
    return $options;
  }

Note that target_bundles needs to be NULL, not [], in order to show all entities instead of no entities (that's how Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection works).

berdir’s picture

Not sure why we're not actually doing the same as TaxonomyIndexTid as suggested in #9/#10. The current behavior of having an exposed field for the ID never makes sense.. why not add the autocomplet-or-list setting that TaxononomyIndexTid uses too? We have generic entity autocomplete..

jibran’s picture

Status: Needs work » Needs review
Issue tags: +DER issue

Tagging.

jibran’s picture

Issue tags: +VDC

Status: Needs review » Needs work

The last submitted patch, 39: entity-reference-exposed-filters-2429699-39.patch, failed testing.

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.

_Archy_’s picture

As Berdir said so did I. Brought big part of the functionality from the TaxonomyIndexTid. Removed the possibility to select the target bundle types, seems to me weird, but it can be readded if you think it can be useful. Now it detects from the displayed entities the possible target bundles. Also removed from the entity reference field the setting to allow for views filtering, so now it's by default enabled. Coding standard fixes.

With this patch the filter can be select or autocomplete. This seems to work with nodes, but a lot of work is still left. Also this patch needs cleanup: config schemas.

About the problem with too many entities: I think we shouldn't disallow the filter, but rather alert the user about possible problems. As I see, it can only have problem with the select type, but the user should decide whether he wants select or autocomplete as he will know how many target entities will be possible.

_Archy_’s picture

Status: Needs work » Needs review
_Archy_’s picture

StatusFileSize
new27.02 KB

Did not create the patch properly. Also I did not update the tests so this will break.

The last submitted patch, 45: entity_reference_view_filter-2429699-45.patch, failed testing.

Status: Needs review » Needs work

The last submitted patch, 47: entity_reference_view_filter-2429699-47.patch, failed testing.

_Archy_’s picture

Status: Needs work » Needs review
StatusFileSize
new7.94 KB
new27.96 KB

Fixed referenced entity type always node and added support for entities that don't support bundles. Other minor improvements.

It works for nodes and users. I don't quite understand why for files the core_field_views_data is not called. Can someone enlighten me. How are they special. I notice that for file and image reference fields in the views filter list they don't display independently, but rather all their fields.

I need some guidance and feedback to continue work on this.

Status: Needs review » Needs work

The last submitted patch, 50: entity_reference_view_filter-2429699-50.patch, failed testing.

_Archy_’s picture

StatusFileSize
new800 bytes
new28.22 KB

Since target bundles are not options anymore, at least for now.

berdir’s picture

Status: Needs work » Needs review
berdir’s picture

Status: Needs review » Needs work

Thanks, this is a good start, great to see progress on this. I'll try to look into that file problem you mentioned.

For now, reviewed the patch.

  1. +++ b/core/config/schema/core.data_types.schema.yml
    @@ -582,6 +582,13 @@ field.storage_settings.entity_reference:
           label: 'Type of item to reference'
    +    additional_behaviors:
    +      type: mapping
    +      label: 'Additional behaviors'
    +      mapping:
    +        views_select_list:
    +          type: boolean
    +          label: 'Render Views filters as select list'
     
     field.field_settings.entity_reference:
    

    I think this is no longer needed as we no longer need that setting? Also for file and image.

  2. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +
    +  /**
    +   * In memory cache of the possible referenced bundles for the entity type.
    +   *
    +   * In case the entity type does not support entity bundles this will be an
    +   * empty array.
    +   *
    +   * @var array
    +   */
    +  protected $referencedPossibleBundles;
    

    why do we need an in memory cache of this information?

    \Drupal\Core\Entity\EntityTypeBundleInfo::getBundleInfo() is already statically cached, if we use that, then we don't neeed this IMHO

  3. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +  /**
    +   * In-memory cache for the entity type ID of the referenced entity.
    +   *
    +   * @var string
    +   */
    +  protected $referencedEntityTypeId;
    

    this also seems not necessary, we just save two methods calls, a method can be useful for this but a static cache seems overkill.

  4. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +  /**
    +   * Validated exposed input that will be set as value in case.
    +   *
    +   * @var array
    +   */
    +  protected $validatedExposedInput;
    

    not sure what's special about this filter that it needs a property for this, I guess this was taken over from the public property of the other class (which I suppose also means it would be hard to deprecae the code there and extend from this. But we could still deprecate it eventually)

  5. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +    $entities = $this->selectionPluginManager->getInstance($this->getSelectionHandlerOptions())->getReferenceableEntities();
    

    this is only needed for the else case, we should not need to load all entities for autocomplete?

  6. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +    $targetType = $this->getReferencedEntityTypeId();
    

    we don't (yet) use camelCase for local variables I think.

  7. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +      if ($this->value && !$this->value['all']) {
    +        $entityArray = $entityStorage->loadMultiple($this->value);
    +      }
    +      else {
    +        $entityArray = [];
    +      }
    

    and we usually don't put the type in variables, this could just be $entities when the code above moves to the else. or $default_entities or something like that.

  8. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +        '#title' => $this->t('Select %entity_typess', ['%entity_types' => $targetType]),
    

    entity types actually have a plural label, check the entity type definition object.

  9. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +
    +      // Show help text if not exposed to end users.
    +      $form['value']['#description'] = t('Leave blank for all. Otherwise, the first selected entity will be the default instead of "Any".');
    +    }
    

    there is a lowercase method for the entity type label, but that's flawed and doesn't really work in many languages.

    You could use a neutral label like "item", we often talk about "content items" or so in the UI.

  10. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +    if ($this->options['type'] != 'auto-complete') {
    

    we use those magic strings a lot, can we make them constants on the class?

  11. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +  protected function getSelectionHandlerOptions() {
    +    $options = ['target_type' => $this->getReferencedEntityTypeId()];
    +    $options['handler_settings']['target_bundles'] = $this->getReferencedBundles();
    +    $options['handler_settings']['sort'] = $this->options['sort'];
    +    return $options;
    

    this needs the same check as the auto-complete above for having bundles? also, can't we re-use this for the selection settings, then we need this logic only once?

  12. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,413 @@
    +    // First gather all the entity bundles that can be displayed in this view.
    +    if (array_key_exists('type', $this->view->filter)) {
    +      $displayedBundles = array_keys($this->view->filter['type']->value);
    +    }
    +    else {
    +      $allBundles = $this->entityBundleInfo->getBundleInfo($this->getReferencedEntityTypeId());
    +      $displayedBundles = array_keys($allBundles);
    +    }
    

    this is not an assumption that we can make. This could be a filter on a list of terms, the bundle condition is something else there, or the condition could be based on a relationship or so.

    What I would do is just look for all fields of our field storage definition, you can't use \Drupal\field\Entity\FieldStorageConfig::getBundles(), but as you can see there, that's just a wrapper for the field map, we can use that.

    Then loop over those. In 99% of the cases, all fields are going to have the same allowed reference. But we could just show them in the extra settings like the taxonomy filter does.

_Archy_’s picture

Status: Needs work » Needs review
StatusFileSize
new3.6 KB

Thanks @Berdir for the feedback. I will try to work more on this when I have time.
This is only for 8.2.x, it was not applying cleanly. No changes made.

_Archy_’s picture

StatusFileSize
new28.01 KB

Well creating patches is not my strongest point :D. Did not include new files..

The last submitted patch, 55: entity_reference_view_filter-2429699-55-D8-2.patch, failed testing.

Status: Needs review » Needs work

The last submitted patch, 56: entity_reference_view_filter-2429699-56-D8-2.patch, failed testing.

_Archy_’s picture

Status: Needs work » Needs review
StatusFileSize
new27.27 KB
new17.6 KB

Did some work. Changed the way getReferencedBundles() works, readded the option of selecting the bundles in the extra config and fixed most of the notes in #54. Now it works with taxonomy (to test comment taxonomy.views.inc:67).

_Archy_’s picture

StatusFileSize
new27.27 KB

Adding for 8.2.x.

The last submitted patch, 59: entity_reference_view_filter-2429699-59.patch, failed testing.

Status: Needs review » Needs work

The last submitted patch, 60: entity_reference_view_filter-2429699-60-D8-2-x.patch, failed testing.

_Archy_’s picture

Status: Needs work » Needs review
StatusFileSize
new1.73 KB
new27.41 KB
new27.41 KB

Added check to see if target bundles is a setting on the field to prevent notices.

Status: Needs review » Needs work

The last submitted patch, 63: entity_reference_view_filter-2429699-63-D8-2-x.patch, failed testing.

jastraat’s picture

The patch in #63 successfully allows displaying an exposed entity reference field as a select or autocomplete in a view.

However - it would be a really nice feature to have the ability to order by something other than node ID. For example... node title?

akozma’s picture

Assigned: Unassigned » akozma
Issue tags: +DCTransylvania
jastraat’s picture

The last patch appears to still work with 8.3.x.

akozma’s picture

In order to not block this issue, I added a new task for the sorting feature (patch included).
See Entity reference view filter, ability to order values by selected field

akozma’s picture

Assigned: akozma » Unassigned
das-peter’s picture

Status: Needs work » Needs review
StatusFileSize
new27.45 KB
new814 bytes

The patch in #63 messes up the reverse relationship handler because it re-assigns the variable $field_name.
The foreach that ensures the filter id is set to entity_reference should use another variable name.
Re-rolled a patch against 8.3.x, should work with 8.4.x too.

The last submitted patch, 70: entity_reference_view_filter-2429699-70.patch, failed testing.

adrian83’s picture

I'm excited to see progress on this issue. As more builders use entity reference instead of taxonomy for expressing relationships, we will be bumping into the entity reference limitations more. I like the implementation in #10.

aaron.r.carlton’s picture

The patch in #63 is breaking for me in a total unrelated condition. I have a view of taxonomy_terms and am adding an entity reference display. When I add a relationship to the view which uses a taxonomy term entity reference field, the module incorrectly builds the query adding a 'target_id' to the reference field of the query, resulting in a SQL error looking for *_target_id_target_id. This was on Drupal 8.2.x.

I recently upgraded my DEV site to Drupal 8.3.x and build the entity referernce view display just fine, without the patch installed. When I re-applied the patch (successfully) to 8.3.x, loading a page with my view, or the view itself results in the following error page below.

Would like to provide more testing and information, but don't have time ATM.

Exception: No entity type for field type on view commodities in Drupal\views\Plugin\views\HandlerBase->getEntityType() (line 697 of core/modules/views/src/Plugin/views/HandlerBase.php).
Drupal\views\Plugin\views\filter\Bundle->init(Object, Object, Array) (Line: 888)
Drupal\views\Plugin\views\display\DisplayPluginBase->getHandlers('filter') (Line: 1029)
Drupal\views\ViewExecutable->_initHandler('filter', Array) (Line: 887)
Drupal\views\ViewExecutable->initHandlers() (Line: 2245)
Drupal\views\Plugin\views\display\DisplayPluginBase->preExecute() (Line: 1678)
Drupal\views\ViewExecutable->preExecute(Array) (Line: 1613)
Drupal\views\ViewExecutable->executeDisplay('entity_reference_1', Array) (Line: 220)
Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection->getReferenceableEntities() (Line: 561)
Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem->getSettableOptions(Object) (Line: 116)
Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase->getOptions(Object) (Line: 34)
Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsSelectWidget->formElement(Object, 0, Array, Array, Object) (Line: 322)
Drupal\Core\Field\WidgetBase->formSingleElement(Object, 0, Array, Array, Object) (Line: 85)
Drupal\Core\Field\WidgetBase->form(Object, Array, Object) (Line: 168)
Drupal\Core\Entity\Entity\EntityFormDisplay->buildForm(Object, Array, Object) (Line: 122)
Drupal\Core\Entity\ContentEntityForm->form(Array, Object) (Line: 98)
Drupal\node\NodeForm->form(Array, Object) (Line: 115)
Drupal\Core\Entity\EntityForm->buildForm(Array, Object)
call_user_func_array(Array, Array) (Line: 514)
Drupal\Core\Form\FormBuilder->retrieveForm('node_pickup_form', Object) (Line: 271)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 48)
Drupal\Core\Entity\EntityFormBuilder->getForm(Object) (Line: 113)
Drupal\node\Controller\NodeController->add(Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 656)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

leksat’s picture

StatusFileSize
new39.78 KB
new248.73 KB

Hi there,

There is an issue with ManyToOne discovered in #2559961: ManyToOneHelper ignores group configuration for some cases:

ManyToOneHelper forces INNER JOINs

Here is an example of a buggy behavior (with the fix-group-condition patch applied).
Content:

Result:

It's currently not decided how to fix the INNER JOIN issue nor whether it needs to be fixed.

As the taxonomy reference field is currently the only field that uses ManyToOne, I was going to create "Stop using TaxonomyIndexTid for taxonomy reference fields" issue. But then I found this issue and I don't really know what to do. So, I just inform you about the bug.

acidaniel’s picture

What about to make it working when the field is included on a search index and those values you want them into a dropdown or autocomplete?

dawehner’s picture

  1. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,449 @@
    +    if ($bundleType = $this->getReferencedEntityType()->getBundleEntityType()) {
    +      /** @var \Drupal\Core\Entity\EntityInterface[] $bundles */
    +      $bundles = $this->entityTypeManger->getStorage($bundleType)->loadMultiple();
    +
    +      $bundle_options = [];
    +      foreach ($this->getReferencedBundles() as $bundle) {
    +        $bundle_options[$bundle] = $bundles[$bundle]->label();
    +      }
    +
    

    One could argue that it would be better to use the bundle info service, given that those labels might come from something else.

  2. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,449 @@
    +      $form_state->setError($form['target_bundles'], 'You must choose at least one target bundle.');
    

    This message should be translatable.

  3. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,449 @@
    +      /** @var \Drupal\node\NodeStorageInterface $entity_storage */
    

    Nitpick: Let's use EntityStorageInterface

  4. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,449 @@
    +        '#default_value' => EntityAutocomplete::getEntityLabels($entities),
    

    Its nice to have this helper method available

  5. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,449 @@
    +      $entities = $this->selectionPluginManager->getInstance($this->getHandlerOptions())->getReferenceableEntities();
    +      $options = [];
    +      foreach ($entities as $bundle) {
    +        foreach ($bundle as $id => $entityLabel) {
    +          $options[$id] = $entityLabel;
    +        }
    +      }
    

    We could use the tricky to flatten the array in one line: call_user_func_array('array_merge', $entities), but I believe writing it out is actually easier to read.

  6. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,449 @@
    +
    +      if ($exposed = $form_state->get('exposed')) {
    +        $identifier = $this->options['expose']['identifier'];
    +
    +        if (!empty($this->options['expose']['reduce'])) {
    +          $options = $this->reduceValueOptions($options);
    +
    +          if (!empty($this->options['expose']['multiple']) && empty($this->options['expose']['required'])) {
    +            $default_value = [];
    +          }
    +        }
    +
    +        if (empty($this->options['expose']['multiple'])) {
    +          if (empty($this->options['expose']['required']) && (empty($default_value) || !empty($this->options['expose']['reduce']))) {
    +            $default_value = 'All';
    +          }
    +          elseif (empty($default_value)) {
    +            $keys = array_keys($options);
    +            $default_value = array_shift($keys);
    +          }
    +          // Due to https://www.drupal.org/node/1464174 there is a chance that
    +          // [''] was saved in the admin ui. Let's choose a safe default value.
    +          elseif ($default_value == ['']) {
    +            $default_value = 'All';
    +          }
    +          else {
    +            $copy = $default_value;
    +            $default_value = array_shift($copy);
    +          }
    +        }
    +      }
    

    Not your fault, but all this code is just quite sad ...

  7. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,449 @@
    +    $ids = array();
    

    Let's ensure to have short array syntax

  8. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,449 @@
    +  protected function getReferencedBundles() {
    

    This method name doesn't really communicate that these are all referencable bundles.

  9. +++ b/core/modules/views/views.views.inc
    @@ -720,6 +720,13 @@ function core_field_views_data(FieldStorageConfigInterface $field_storage) {
     
    +    // Render filters as select lists.
    +    foreach ($table_data as $table_field_name => $table_field_data) {
    +      if (isset($table_field_data['filter']) && $table_field_name != 'delta') {
    +        $data[$table_name][$table_field_name]['filter']['id'] = 'entity_reference';
    +      }
    +    }
    

    Don't we need some update path for that?

drunken monkey’s picture

Status: Needs review » Needs work

I guess you meant to set this back to NW?

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.

luksak’s picture

I am using this patch on a field that references users on 8.3.4.

I keep getting those warnings:

Warning: array_keys() expects parameter 1 to be array, null given in Drupal\views\Plugin\views\filter\EntityReference->getReferencedBundles() (line 440 of core/modules/views/src/Plugin/views/filter/EntityReference.php).
Warning: array_merge(): Argument #2 is not an array in Drupal\views\Plugin\views\filter\EntityReference->getReferencedBundles() (line 441 of core/modules/views/src/Plugin/views/filter/EntityReference.php).  
_Archy_’s picture

Assigned: Unassigned » _Archy_

Well I am back to this feature. I've just encountered the case where I need the handler to work with fields that use view selection handling.

Have taught about it and it seems too difficult to handle that case in the best generic way. For example if two bundles implementing the same field are displayed in the view and both these fields have view selection handling, how would you provide the available values for the filter? The ideal way would be merging the two views results for the filter values. To make things more complicated add the possibility for an additional bundle with same field that references directly bundles. Then the two views results would have to be combined with all the entities of that bundle. Which makes this even more complicated, how do you handle all this with the autocomplete field? We would need a new selection handler.

I've will implement this in an easier, limited way for the moment: in the settings form you will have to select whether you want to add bundles for filter possibilities or ONE view selection handler if any exists.

_Archy_’s picture

Status: Needs work » Needs review
StatusFileSize
new16.36 KB
new31.97 KB

Added support for view selections, described in #80. Also addressed most of the comments in #76. Point 9 I didn't understand the request.

Status: Needs review » Needs work

The last submitted patch, 81: entity_reference_view_filter-2429699-81.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

_Archy_’s picture

Assigned: _Archy_ » Unassigned
Issue tags: +Needs tests

Seems to work with my manual tests.

luksak’s picture

In "Possible selection values from" the only option is "View result". The "View selection" is empty. Do I have to create a specific view before I can choose it?

_Archy_’s picture

@Lukas von Blarer you have to have the "reference method" setting as "Views: Filter by an entity reference view" and NOT "default" (for at least one content-field) on the reference field for which you are adding the filter.

luksak’s picture

Ah ok. I'll try that. Thank you!

luksak’s picture

StatusFileSize
new32.64 KB
new4.43 KB

I think it would be better if the user could choose to use a differnt view or display for the selection. It gives the possibility to restrict the exposed filters in a flexible way. As an example: I am using it to only display options that yield results.

I did a rough implementation of that. It is missing a few things:

  • The possibility to provide arguments.
  • A method to get the supported views. There is duplicated code in buildExtraOptionsForm() and collectFieldsReferenceHandlers().
  • The ability to use the default behavior not to use a view.
Christophe Bourgois’s picture

Subscribe ++ (ttt)

manuga’s picture

The first fail in the test:
Schema key views.view.test_filter_entity_reference:display.default.display_options.filters.status.value failed with: variable type is boolean but applied schema class is Drupal\Core\TypedData\Plugin\DataType\StringData
looks like to be in
+++ b/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_filter_entity_reference.yml
where it says:

+filters:
+        status:
+          value: true

must say:

+filters:
+        status:
+          value: '1'

But i haven't tested it.

flabel’s picture

Subscribe+

_Archy_’s picture

seanb’s picture

Status: Needs work » Needs review
StatusFileSize
new32.67 KB
new717 bytes

Fixed #89

Status: Needs review » Needs work

The last submitted patch, 92: 2429699-92.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

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.

avogler’s picture

I tested #92 manually. Works as expected but one thing I noticed: If there is more than one field referencing the same entity but only one is set to use a reference type of "Views: filter by an entity reference view" and the other uses "Standard" you'll get a warning:

Notice: Undefined index: user_admin_people:entity_reference_1 in Drupal\views\Plugin\views\filter\EntityReference->getHandlerOptions() (line 501 of core/modules/views/src/Plugin/views/filter/EntityReference.php). 
ckaotik’s picture

Some additional comments after just trying to make this usable with search_api:

  1. Style: This and other non-class variables should use snake_case instead of camelCase:

    + $entityType = $this->getReferencedEntityType();
    + if ($bundleType = $entityType->getBundleEntityType()) {
  2. collectFieldsReferenceHandlers expects there to be bundles to filter by, we should check this first.

        // For entity types that do not offer bundles, don't try to look them up.
        $entity_type = $this->getReferencedEntityType();
        if ($bundle_type = $entity_type->getBundleEntityType()) {
          $field_definitions = $this->getBundleFieldDefinitions();
    
          // For each entity bundle check if this field is set and if yes collect
          // the configured target entity bundles.
          foreach ($field_definitions as $field) {
            /* ... */
          }
        }
    
  3. Why do we only check entity reference displays if there are bundles in collectFieldsReferenceHandlers? Shouldn't the Views select options always be available, like when there are no bundles (think: user entities), and offer all possible view/display options, not just if configured in the field's settings?
  4. The $view->get('base_table') check makes this unusable with differently named source tables, we could ask the ViewExecutable for its entity type instead of the View configuration entity:

    if (($executable = Views::getView($view_id)) && $executable->getBaseEntityType() == $entity_type) {

With these changes, collectFieldsReferenceHandlers could look like this:

  protected function collectFieldsReferenceHandlers() {
    $referenced_bundles = [];
    $view_selection_handlers = [];

    // For entity types that do not offer bundles, don't try to look them up.
    $entity_type = $this->getReferencedEntityType();
    if ($bundle_type = $entity_type->getBundleEntityType()) {
      $field_definitions = $this->getBundleFieldDefinitions();

      // For each entity bundle check if this field is set and if yes collect
      // the configured target entity bundles.
      foreach ($field_definitions as $field) {
        $handler_settings = $field->getSetting('handler_settings');

        // Get the configured reference-able bundles.
        if (isset($handler_settings['target_bundles']) && is_array($handler_settings['target_bundles'])) {
          $target_bundles = array_keys($handler_settings['target_bundles']);
          $referenced_bundles = array_merge($referenced_bundles, $target_bundles);
        }
      }
    }

    // Check any entity_reference View that might be relevant.
    $view_selection_options = [];
    $displays = Views::getApplicableViews('entity_reference_display');
    foreach ($displays as $data) {
      list($view_id, $display_id) = $data;
      if (($executable = Views::getView($view_id)) && $executable->getBaseEntityType() == $entity_type) {
        $view_settings = [
          'view_name' => $view_id,
          'display_name' => $display_id,
          'arguments' => []
        ];

        $id = implode(':', [$view_settings['view_name'], $view_settings['display_name']]);
        $view_selection_handlers[$id] = $view_settings;
      }
    }

    return [
      // Remove duplicates and reset the array keying.
      'bundles' => array_values(array_unique($referenced_bundles)),
      'views' => $view_selection_handlers,
    ];
  }
didebru’s picture

Could we make this work with config entities? That would be awesome.

ckaotik’s picture

I've just run into a situation where target entities without bundles (in this case: selecting a commerce shop) cause the view to break when using the patch. It seems, my suggestions from #96 are not only useful for search_api, but actually required in general.

@Insasse, do you have an example use case for selecting config entities? Have you tried the new handler (possibly with the changes to collectFieldsReferenceHandlers), or is it not compatible at all?

ckaotik’s picture

Status: Needs work » Needs review
StatusFileSize
new32.62 KB
new7.26 KB

I've updated the patch for my remarks in #96. Marking as needs review for the testbot.

We still need to address #95 and possibly think about #97.

Edit: There are also some coding standards to fix, just went over EntityReference.php.

Also noticed that if (in_array($view->get('base_table'), [$entityType->getBaseTable(), $entityType->getDataTable()])) { is duplicated, so the second instance of that should also be updated according to #96. Maybe even put the logic into a reusable method.

Status: Needs review » Needs work

The last submitted patch, 99: views-entityreference-filter-2429699-99.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

didebru’s picture

Yes in our project we have 2 config entities that are used to control the output for our content, we want to filter our nodes by that.
I tried the patch but it is not working for me in this case.

adrian83’s picture

RKopacz’s picture

This is a prosaic question, in the current state, right now, if I have a view of Articles, and I would like to filter it by a reference field that references a Basic Page, for example, what value do I put in the "Value" field in order to get the field to work? I don't mind putting a value in there but it is not clear what value to put in there. I've tried the node ID of the referenced basic page, the URL, and a text string of the Node Title, and nothing works, Is that filter not working at all in its current state?

I've created a relationship to the reference field on Article etc. But I can't get the list to filter by the value in the reference field.

If someone could point me to some documentation on that, I'd appreciate it. I've looked all over but I guess I'm using the wrong key word phrases.

EDIT: posted a support request here: https://www.drupal.org/project/drupal/issues/2955011

berdir’s picture

I think it is unfortunate that we are hardcoding all those extra settings and then require all that mapping between selection plugins and hardcoded views settings.

I started looking into re-using the plugins to allow them all and to expose their own settings forms, so we don't have to reinvent things. That is quite a lot of work, but I did manage to make the extra fields show up at least. Just posting an interdiff with my current progress as I need to switch to something else for now.

Some of the exposed settings might be a bit bogus (like the one about auto-creating entities) but I think that's not a big deal.

Not actually less code yet, as I just added a bunch of early returns, but I hope to get there eventually.

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.

rosk0’s picture

Assigned: Unassigned » rosk0

Trying to continue from where @Berdir finished.

rosk0’s picture

Assigned: rosk0 » Unassigned
Status: Needs work » Needs review
StatusFileSize
new35.94 KB
new145 bytes
new0 bytes

Made some progress. Views are now selectable and everything is actually works. Feedback appreciated.

I think we need to convert test from Drupal\views_ui\Tests\UITestBase to \Drupal\Tests\views_ui\Functional\UITestBase. Don't have time for it at the moment.

Status: Needs review » Needs work

The last submitted patch, 107: 2429699-107.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

rosk0’s picture

Assigned: Unassigned » rosk0

Still on it, found issues with filter schema and test view.

rosk0’s picture

Assigned: rosk0 » Unassigned
Status: Needs work » Needs review
StatusFileSize
new38.03 KB
new21.61 KB

Removed copy paste element validate property, disabled auto create option, fixed formatting, fixed sorting handling for default handler, removed unused variable, fixed filter schema, fixed test view, converted test to functional.

Test should go green, at least its green locally.

Chris Charlton’s picture

Tests are green! :)

rlmumford’s picture

Assigned: Unassigned » rlmumford
Status: Needs review » Needs work

The configuration form doesn't work if the field is a user a reference. If you select 'User role' under 'Filter By' the role selector does not appear. Investigating...

rlmumford’s picture

Assigned: rlmumford » Unassigned
Status: Needs work » Needs review
StatusFileSize
new32.56 KB
new12.95 KB

Went through and made sure the handler settings configuration worked. Removed all of the duplicated hard coded references to target bundles and let the Selection plugins massage the configuration. Tested with user entity reference fields (limiting by roles).

Still needed the hack for the AJAXified Selection plugin configuration forms.

finex’s picture

Hi, is this patch "safe" to use on production or is still under development? Thanks :-)

Currently I'm using on a test website and it works for me :-)

pancho’s picture

Very nice. I'm using this one in my beta production environment now, and while I hit a fairly minor UI bug with views preview (#3027858: Exposed filter widget change triggers 'illegal choice' resp. 'no matching entity') it has been taken over from TaxonomyIndexTid. Actually I also hit a second bug taken over from TaxonomyIndexTid, but have failed to reproduce. Using a generic filter plugin for all kinds of referenced items is a good thing - it will get the code more exposure, so bugs will evaporate over time.

ckaotik’s picture

The patch in #114 produces an error when trying to change the filter value, because the entity_autocomplete element requires full entity objects (or NULL), not the names. We should change getDefaultSelectedEntityLabels to getDefaultSelectedEntities. In case of large amounts of entities, can we just set the value to NULL, instead of loading all of them? The autocomplete input has a length limit iirc ...

/**
   * {@inheritdoc}
   */
  protected function valueForm(&$form, FormStateInterface $form_state) {
    $referenced_type = $this->getReferencedEntityType();

    if ($this->options['type'] == self::AUTO_COMPLETE_TYPE) {
      $form['value'] = [
        '#title' => $this->t('Select %entity_types', ['%entity_types' => $referenced_type->getPluralLabel()]),
        '#type' => 'entity_autocomplete',
        '#default_value' => $this->getDefaultSelectedEntities(),
        '#tags' => TRUE,
        // <snip>
  /**
   * Gets the default value for auto-complete field.
   *
   * @return \Drupal\Core\Entity\EntityInterface[]|null
   *   The auto-complete value.
   */
  protected function getDefaultSelectedEntities() {
    $referenced_type_id = $this->getReferencedEntityType()->id();
    /** @var \Drupal\Core\Entity\EntityStorageInterface $entity_storage */
    $entity_storage = $this->entityTypeManger->getStorage($referenced_type_id);

    if ($this->value && !isset($this->value['all'])) {
      return $entity_storage->loadMultiple($this->value);
    }
  }
ckaotik’s picture

To make life easier for site builders, we should probably also improve the admin summary of the filter. Maybe add the selected entities to the value options and rely on the parent class?

  public function getValueOptions() {
    if (!isset($this->valueOptions)) {
      $this->valueOptions = [];
    }

    if (empty($this->valueOptions) && $this->options['type'] === static::SELECT_LIST_TYPE) {
      $this->valueOptions = $this->buildReferenceEntityOptions();
    }
    if (empty($this->valueOptions) && $this->options['type'] === static::AUTO_COMPLETE_TYPE) {
      if (empty($this->value) || isset($this->value['all'])) {
        $this->valueOptions['all'] = $this->t('All');
      }
      else {
        // @todo Better yet: map entity id => entity label.
        $this->valueOptions = array_combine($this->value, $this->value);
      }
    }

    return $this->valueOptions;
  }

Displaying the entity id is easiest, but the entity label should be better still. Unfortunately, EntityAutocomplete::getEntityLabels($entities) returns a string instead of an array - and exploding on , would need to consider escaping etc.

pancho’s picture

  • Fixed the bug described in #117. '#process_default_value' => FALSE did the job. Note that this is also the additional bug I mentioned in #116, so another box checked.
  • Fixed the admin summary, per #118.
  • Removed some unused leftover code
  • Renamed a misspelled property and two camel-cased local variables.

Hopefully still green, so no new bugs introduced. Two or three more glitches to be fixed, and then we should be relatively close.

Status: Needs review » Needs work

The last submitted patch, 119: generic_entityreference_filter_22429699-119.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new31.9 KB
new4.43 KB
new6.82 KB

Fixed coding standards + another instance of a camelCased local variable

pancho’s picture

1) Note that when the filter is not exposed, operator is either of (one/all/none of) and no default is chosen I'm now getting a validation error:

No valid values found on filter: name_of_filter

There's no validation error when using the TaxonomyIndexTid filter in the same configuration, but I guess it's correct that the warning is there now, so it's another previously existing, now fixed bug rather than a new bug, if I'm right. We might want to catch the validation error earlier though by marking the default value field required in this case.

2) In any case, if the operator is unary (one of empty / not empty), we need to hide the value field, both for the default value and in the exposed filter. StringFilter, NumericFilter and others get it right, TaxonomyIndexTid doesn't. I'm preparing another patch that fixes this.

pancho’s picture

StatusFileSize
new32.49 KB
new7.96 KB
new1.61 KB

I looked at both the code and the UI of all implementations, and the code is horrible and (at least if I got it right) not even a single filter class gets it right:

  • Normally, the default value field is only shown, if the operation is binary (i.e. not one of the unary "empty" and "not empty" ops).
  • However, if both the filter AND the operation are exposed AND the operation has a proper identifier, we ẃant the default value field always to be shown. Even if the default operation is unary, the end user may choose another op, and for that case we might want to have a default filter value.

Enclosed patch puts that logic into code, and from what I know, it works correctly and is much cleaner codewise.

However, the actual result looks a bit weird, as the "expose operator" checkbox may show/hide the filter value field above. In the end, I have no idea why the "expose operator" checkbox along with its identifier field is located in the right column under the filter value and not in the left column right under the operator it belongs to. Changing this, however, is beyond the scope of this issue.

I'm happy to accept if someone convinces me that I missed something and got it wrong. But if the logic is approved here, it should be rolled out to the rest of the filter subsystem anyway.

pancho’s picture

StatusFileSize
new247.84 KB

Forgot to post a small screencast showing how my new logic looks like.
Ignore this one please.

pancho’s picture

StatusFileSize
new194.05 KB

Oops, this is the right video. Sorry for the noise.

pancho’s picture

StatusFileSize
new33.49 KB
new854 bytes
new8.79 KB

However, the actual result looks a bit weird, as the "expose operator" checkbox may show/hide the filter value field above. In the end, I have no idea why the "expose operator" checkbox along with its identifier field is located in the right column under the filter value and not in the left column right under the operator it belongs to. Changing this, however, is beyond the scope of this issue.

We can actually decide later if fixing the twig template is out of scope or not. I'm enclosing another patch that provisionally fixes the two-column floatbox design. Further layout changes should in any case be covered in a followup.

Status: Needs review » Needs work

The last submitted patch, 126: 22429699-114-126_interdiff.patch, failed testing. View results

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new33.8 KB
new2.95 KB
new9.33 KB

Fixed field visibility for the actual exposed filter, too. Reorganized the code a bit to avoid any unnecessary HTML if the operator is not exposed, while avoiding redundant code as well. Manually tested, should be fine now. Sorry for the noise.

Status: Needs review » Needs work

The last submitted patch, 128: generic_entityreference_filter_22429699-128.patch, failed testing. View results

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new33.8 KB
new633 bytes
new9.65 KB

Forgot one instance of the internal variable $exposed I renamed to $is_exposed to be a bit more verbose. Hope it is green now.

Test coverage needs to be further expanded.

pancho’s picture

StatusFileSize
new49.78 KB
new16.22 KB
new25.6 KB

Next step: I'm rebasing TaxonomyIndexTid on the new generic EntityReference filter.

Unfortunately I need a minor patch to the TermSelection handler to make hierarchy prefixes optional. This currently isn't configurable in the EntityReference selector, and my patch doesn't add any UI to entity references, though it might be easily done in a followup, if desired.

Also, I'm hiding the 'auto_create_bundle' handler setting which doesn't apply to views.

Surprisingly everything works well, including the otherwise unchanged TaxonomyIndexTidDepth filter that is now based on the new TaxonomyIndexTid. We might want to figure out, if and how we can reintegrate the depth option into the main TaxonomyIndexTid filter, but that's definitely out of scope here.

Let's see if the tests agree, and if they do, that's something. Finally, our test coverage should be considerably better now, because of prexisting tests against TaxonomyIndexTid. If everything stays green, we should be veery close.

Status: Needs review » Needs work

The last submitted patch, 131: generic_entityreference_filter_22429699-131.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new50.54 KB
new3.16 KB
new27.16 KB

Config is one of the remaining problems.
Added the dependencies that the taxonomy tests are expecting:

  • Entity bundles chosen at handler-level, exported by TaxonomyIndexTid (actually the handler's job, unsure about this)
  • DefaultSelectedEntities, right at the EntityReference filter

However, if we stick with the current config structure (bundles in handler_settings), then this will not be compatible with preexisting views and we need an upgrade path. We however need an upgrade path anyway, as the old TaxonomyIndexTid had the (single allowed) bundle under the key 'vid', and we certainly want this to be consistent across all entity types.

I also refactored EntityReference::getDefaultSelectedEntityLabels into getDefaultSelectedEntities as previously proposed by @ckaotik. The previous method was far too specific to be reused anywhere except for autocomplete default values.

Let's see if the tests go green, in which case I would be done for now. We still need a decision on how to proceed with the bundle config as well as the upgrade path for TaxonomyIndexTid. Input on this and more generally a thorough code review would be welcome!

Status: Needs review » Needs work

The last submitted patch, 133: generic_entityreference_filter_22429699-133.patch, failed testing. View results

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new56.9 KB
new13.52 KB
new38.16 KB

Renamed the 'type' setting to 'widget' both to be clearer (there are so many "types") and more accurate (select or autocomplete aren't different "types" of filters, they are widgets).

Also renamed the values 'select-list' to 'select' and 'auto-complete' to 'autocomplete' to be more in line with how we call it elsewhere.

Config is tricky, and on my local testbed I continue to get 3 errors, but at least it should be a bit closer to green now, and I'm definitely running out of time for today. Input welcome.

Status: Needs review » Needs work

The last submitted patch, 135: generic_entityreference_filter_22429699-135.patch, failed testing. View results

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new56.9 KB
new609 bytes
new38.12 KB

Fixed one of the three failures. Minor glitch introduced by myself, should be okay now.

The two remaining ones:

  • The wizard test, yes: It has to be adapted to the new config schema.
  • The other one (TaxonomyIndexTidUiTest) I don't know.

    views.view.test_filter_taxonomy_index_tid:display.default.display_options.filters.tid.type missing schema

    Yes, it's missing schema, but it shouldn't be there in the first place after being renamed to 'widget'.

Feel free to step in as I've run completely out of time now.

Apart from that some input is needed what this weird 'error_message' setting in the old TaxonomyTermTid filter was meant to accomplish. Apart from the setting, I didn't find any code related to it, so almost certain it was useless and can be fully removed.

Status: Needs review » Needs work

The last submitted patch, 137: generic_entityreference_filter_22429699-137.patch, failed testing. View results

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new57.73 KB
new2.7 KB
new38.78 KB

Fixed the two failing tests in TaxonomyIndexTidUiTest. For one, it manually tries to change the filter 'type', now officially 'widget'. Also, 'target_bundles' may not just be empty but not set at all, courtesy of the handler, so we need to check its existence.

The only test that should still fail is the wizard. I'd need some more time to figure it out.
But in the end, I think we need a maintainer to decide if we want to go ahead with this handler architecture at all or not.

Status: Needs review » Needs work

The last submitted patch, 139: generic_entityreference_filter_22429699-139.patch, failed testing. View results

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new61.63 KB
new4.86 KB
new42.76 KB

Think (or better: hope) I finally got it right: the ConfigSchemaChecker kept throwing exceptions. This may only have started with patch #133 when I introduced the dependency calculations. Obviously only those triggered the ConfigSchemaChecker, because until #131 there were only some foreseeable test failures.

Now I fixed the Node view wizard (which now allows as many tags fields and as many bundles as desired). The ConfigSchemaChecker kept complaining, but the schema should be correct now. Config-inspector says OK, too.

[edit: There is at least one more preexisting issue with AJAX in the handler setting, at least until the view is saved. Manual testing suggests it is related to the "AJAX hack" mentioned in #114. If someone can reproduce it, they might get an idea what's wrong there. We probably need test coverage for that dialog, too.

Otherwise, the tests have gone green and we may proceed to a thorough code review. I'm unassigning for now.]

scott_euser’s picture

I have not looked at the code, but have tested this out in terms of functionality and was able to:

  1. Convert existing entity reference fields to use select dropdowns
  2. Add new entity reference fields as exposed filters using select dropdowns
  3. Combine this with Better Exposed Filters to render the select dropdowns as radio buttons (single) and checkboxes (multiple)

Thank you for all of the effort that has been put into this thus far.

jhedstrom’s picture

Issue tags: -Needs tests

I'm removing the 'Needs tests' tag. This is still tagged as needing an IS update, perhaps a picture of the new UI change this provides could replace the old one from D7--I'm not sure if any other IS updates are needed.

skylord’s picture

Hm. After applying patch from #141 views edit window stopped working - server memory limit (about 512Mb) and maximum execution time allowed were not enough for it. Maybe because of potentional long select list of referenced entities (about 2k)....

grathbone’s picture

@scott_euser Related to your comment in #142, I'm actually running into an issue with Better Exposed Filters returning the error Notice: Undefined index: type in /var/www/docroot/modules/contrib/better_exposed_filters/src/Plugin/views/exposed_form/BetterExposedFilters.php on line 325

It seems to be looking for 'type' instead of 'widget' on taxonomy terms. I know it's related to Better Exposed Filters, but wanted to note since I saw your comment about it working.

I opened an issue and related it back to this issue, as well as added a patch.

But this makes me wonder if changing the 'type' to widget could potentially cause problems with other modules.

Status: Needs review » Needs work

The last submitted patch, 141: generic_entityreference_filter_22429699-141.patch, failed testing. View results

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new61.67 KB
new2 KB

Just a straight reroll of #141 against current dev.
Interdiff didn't work in this case, added a plain diff instead.

pancho’s picture

Just some minor tidbits.

@scott_euser: Thanks! Yes I think it's working quite flawlessly. I've been using it in production for a week or two now, and it turned out very nice. There's however still the AJAX issue in the handler setting until the view is saved once (as described in #141). If someone can figure that out, that'd be awesome. I probably won't have time for that in the next two weeks.

@skylord: Yes, a select list with 2k entities will bring it down. We could set a limit of max. 100 select options, otherwise switching to autocomplete. Finally, a select list with 2k entities isn't usable either.

@grathbone: Thanks for filing BEF issue #3032467: Issue with upcoming change to Entity Reference/Taxonomy filters in Core. Indeed, $options['type'] is now $options['widget']. We might however do some BC on Core side.

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.

eglaw’s picture

I have a commerce2 project.
I have this patch installed #141, which applies on Drupal 8.6.10.
This patch works on Commerce product fields on entity_references.
I have plenty of Custom Content Entities (let's say A,B,C,D,E,F....)
They have entity_reference between them ... lets say B has a *a_ref* which references A.

In a view that shows B entities (whatever display let's say table) - the exposed filter of field *a_ref* CAN'T be chosen as Select.

What am i missing ?

Anonymous’s picture

Thanks for all the hard work.
Patch cannot be applied to the current 8.6.15 version.

pancho’s picture

Patch #148 still applies against 8.8 and 8.7, which is where new features/tasks are landing.

The last one still applying against 8.6 is #141.

Anonymous’s picture

Thanks @Pancho.
The patch #141 applies perfectly.
It seems there is no option to alter existing entity reference view filters, right?
It would be nice if there was a setting to use autocomplete, my view hangs up since there a lot of nodes that could be referenced.

glass.dimly’s picture

The patch from #141 applied cleanly against 8.6.14, and works great.

c.e.a’s picture

Patch #141 applied cleanly on 8.6.15 with no errors.

Patch working as expected and used with Better Exposed filters module as well...

Thank you everybody for your hard work!

oriol_e9g’s picture

I will review the patch in depth tomorrow but, can we address the new two coding standards warnings added?

+          'target_bundles' => $target_bundles,
+          'sort' => [
+            'field' => 'name',
+            'direction' => 'asc'
+          ],
+          'auto_create' => FALSE,
+          'auto_create_bundle' => ''
+        ],

Missing coma after 'direction' => 'asc' and 'auto_create_bundle' => ''.

c.e.a’s picture

I found a small problem with both patches (#141 for 8.6.x) and (#148 for 8.7.x)

When add a new entity reference field within the filter section of a view, the settings page made available due to patch #141 will automatically open...

Now, try to change the option of Reference Method select list field from Default to Views: Filter by an entity reference view and you will notice that: the "settings" page will auto-close and the "Add Filter" page will re-open again.

Expected Behavior:
The settings page must remain open/active in order to continue the configuration of the filter field.

c.e.a’s picture

Patch #148 applied cleanly to core release 8.7.0

Note: for anybody else encountered an issue of making patch #148 works on 8.7.0 release, make sure you are applying the right patch for the right core release from this issue #2174633: View output is not used for entityreference options (currently the patch #273 is working great on 8.7.0)

oriol_e9g’s picture

Only addresing the two CS warnings related in #156

Status: Needs review » Needs work

The last submitted patch, 159: generic_entityreference_filter_22429699-159.patch, failed testing. View results

oriol_e9g’s picture

1. When we get the entities we can limit the requested entities. EntityReferenceAutocompleteWidget has a hard limit to 10, and there is an issue to add a new setting #2863188: Hardcoded result size limit in the entity reference autocomplete widget.. Maybe we can add const for a hard limit and open a followup for a new setting.

const MAX_REFERENCED_ENTITIES = 100;
...
$entities = $this->selectionPluginManager->getInstance($handler_settings)->getReferenceableEntities(NULL, 'CONTAINS', MAX_REFERENCED_ENTITIES);

2. If we change $options['type'] to $options['widget'] maybe a CR will be suficient?

oriol_e9g’s picture

StatusFileSize
new61.6 KB

Sorry for the noise, this is the correct patch.

scott_euser’s picture

Thanks for the continued updates to this! #148 works for me as before but now in 8.7.

Retested the following:

  • Convert existing entity reference fields to use select dropdowns
  • Add new entity reference fields as exposed filters using select dropdowns
  • Combine this with Better Exposed Filters to render the select dropdowns as radio buttons (single) and checkboxes (multiple)

The patch in #162 unfortunately had errors for me with missing 'vid' in exposed filter settings for existing filters.

aaronbauman’s picture

Status: Needs work » Needs review
brooke_heaton’s picture

This patch now fails on 8.7.1 since the core module is now at schema version 8701.

c.e.a’s picture

@brooke_heaton I am running Drupal 8.7.1 with the applied patch #148

the patch is applied cleanly and working as expected with no errors.

dww’s picture

@brooke_heaton re: #165: I don't see anything in patches #148 nor #162 that include any schema updates at all. Not sure why you think it matters that the core module's schema version is now 8701. Was your comment perhaps for a different issue where there are DB updates involved?

Meanwhile, since I was curious and it hasn't been posted, here's the interdiff between #148 and #162. As advertised, it's only the 2 minor code style fixes. Folks should use #162 as the basis of any future work going forward, and should focus reviews and testing there.

I don't have time now for a thorough review, but I'm definitely interested in this issue and hope to be able to put some energy into it in the coming days.

Finally, I'm hiding a bunch of older, stale patches and interdiffs. I'm leaving #141 as the last patch that applies to 8.6.x. #162 is for 8.7.x and 8.8.x.

Thanks,
-Derek

dddbbb’s picture

Just tried D8.7.1 with the patch from #162. Seems to work but I did notice 2 oddities:

1. Existing filters on the view I tried to add entity ref exposed filters to were reset. E.g. a term ref field filter was no longer associated with a vocabulary. Manually updating the filter and saving worked around issue.

2. Adding an entity reference based filter to a view exhibited strange behaviour: after adding the new filter, attempting to configure the filter (even just selecting a content type to reference) triggered an AJAX load and I was dumped back into the "Add filter criteria" modal. Fortunately, my filter had still been added but I had to exit the modal and click the filter's "Settings" link to then configure it.

Minor WTFs with manual workarounds but I'd be shocked to find this shipped in core. Thanks for all the hard work so far! :)

c.e.a’s picture

@danbohea same as I explained in my above comment #157

aaronbauman’s picture

nit pick: if we get another re-roll, can the next patcher please remove the extraneous "2" from the patch name, so that it matches the node id of this thread?

22429699-162.patch

dddbbb’s picture

Status: Needs review » Needs work

@C.E.A I missed that but yes, your comment sounds like the same behaviour that I mentioned in my second point :)

brooke_heaton’s picture

@dww - hm, my bad! Yes, this must have been for another patch. My apologies! Carry on! :/

c7bamford’s picture

The selection group plugin is being obtained incorrectly in \Drupal\views\Plugin\views\filter\EntityReference::buildExtraOptionsForm() on lin 98. $this->selectionPluginManager->getPluginId($entity_type->id(), $selection_group_id) should be used instead of concatenation. The current method does not allow selection plugins to be overridden.

joachim’s picture

+/**
+ * Filter handler which allows to search on multiple fields.
+ *
+ * @ingroup views_filter_handlers
+ *
+ * @ViewsFilter("entity_reference")
+ */
+class EntityReference extends ManyToOne {

The class docs are wrong.

Also, I can't get this to work, so the issue summary needs updating with instructions on how to test.

I did this:

1. created an entity reference field on a node that points to a custom entity,
2. created a view of nodes
3. added a filter on the field I'd made

I see the same old textfield for the filter.

_Archy_’s picture

Assigned: Unassigned » _Archy_
_Archy_’s picture

Issue tags: +DevDaysTransylvania

So I have been looking into this some more to see what has been done and to maybe continue the work on it as of DrupalDevDays in Cluj. I have found a serious issue with the submission of extra options form, which seems to be related to the fact that for some reason even if there are errors on the form state in the ViewsFormBase in the getForm method it is skipping an important if and subsequently closing the modal without actually saving (in case the below clause would evaluate it would function correctly):

    // If the form has not been submitted, or was not set for rerendering, stop.
    if (!$form_state->isSubmitted() || $form_state->get('rerender')) {
      return $response;
    }

I have not yet figured out why this is happening. I will continue debugging this in the next few days.

pancho’s picture

Thanks for looking into the remaining bugs!
In the meantime, here's a plain reroll against current dev.

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new61.78 KB
new848 bytes

I have found a serious issue with the submission of extra options form, which seems to be related to the fact that for some reason even if there are errors on the form state in the ViewsFormBase in the getForm method it is skipping an important if and subsequently closing the modal without actually saving

That may be the case, so we should follow that underlying issue, too, whether here or in a separate issue.

However, the more obvious thing here is that in \Drupal\views\Plugin\views\filter\EntityReference::buildExtraOptionsForm(), while we're disabling the auto-create functionality:

    $form['handler']['handler_settings']['auto_create']['#access'] = FALSE;
    $form['handler']['handler_settings']['auto_create_bundle']['#access'] = FALSE;

we were not disabling the AJAX callback (resp. the non-JS replacement button) that updates 'auto_create' depending on what is configured as 'target_bundles'. Not a big surprise that this would cause problems.

So by simply adding:

    $form['handler']['handler_settings']['target_bundles']['#ajax'] = FALSE;
    $form['handler']['handler_settings']['target_bundles_update']['#access'] = FALSE;

the bug is gone. :D

Is it the only/last one? I guess not. But it's probably been the most obvious and stubborn one.

pancho’s picture

Status: Needs review » Needs work
StatusFileSize
new62.33 KB
new8.69 KB

While #178 is an improvement, it unfortunately doesn't solve the whole issue with the extra settings form, as the bug will still appear when switching the handler before the filter has been saved.

However, we could simply lock the handler and defer the remaining issue to a followup. Finally TaxonomyIndexTid didn't support entity reference views either. Given we are at 179 comments, this might be the best way forward.

Regardless of this, I refactored Drupal\views\Plugin\views\filter\EntityReference quite a bit, simplifying the form element #parents logic and some other things, fixing some misnomers, reordering helper methods, and fixing some comments. There shouldn't be any change in functionality vs. patch #178.

pancho’s picture

Use SubformState when propagating $form_state to the selection plugin's buildConfigurationForm() and validateConfigurationForm() methods.

Some more refactoring, particularly in validateExtraOptionsForm. The plugin only needs 'handler_settings'. Also see #3061180: Don't allow all bundles if no target bundle is configured, after which there won't be much code left in DefaultSelection::validateConfigurationForm(). Not sure we should bother with it at all.

pancho’s picture

Would be nice if this passes all tests.

I'm now using InOperator::getValueOptions() to populate $this->valueOptions, providing an 'options callback' instead of doing everything ourselves in buildReferenceEntityOptions(). Also reordering related methods.

@todo: Find a better way to enrich $handler_settings in TaxonomyIndexTid::init(), so we don't have to override the parent class. Maybe use HandlerBase::defineExtraOptions().

_Archy_’s picture

Status: Needs work » Needs review
StatusFileSize
new64.83 KB
new11.53 KB

I have fixed the issue with the validation not saving the extra options form. Also I have introduced a maximum elements settings for the select widget. Defaulted to 30, debatable. Also added a warning log in case there are more than the set maxiumum when the widget is in select, also this is debatable to how we should do it, a problem with it is that currently it will generate many warning logs in that case. But I think it is still important to notify the site administrators.

Also I have tested manually many flows and did not find any minor to major issues.
I will do an issue summary update later.

Status: Needs review » Needs work

The last submitted patch, 182: generic_entityreference_filter_2429699-182.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

_Archy_’s picture

Fixed coding standards issues. A little bit more of refactoring. Also added dependencies from selection handlers to the calculate dependencies.

Updated the issues summary to my best knowledge. I added that there are no API changes but I need confirmation on this. I've added a list of things that has been done and what still needs to be done. I did not check tests since there is only a single webtest that after my estimates only covers like 10% of the functionality. So I think we should add some more tests, maybe unit as well. I have also put question marks for todos that I am not sure about, so I need some opinions about those. What we should tackle in a different issue I've added to Post tasks. Feel free to complete this if you think it's missing things or they are incorrect.

Why are the filter configuration schema set to not translatable?

_Archy_’s picture

Issue tags: +DevDaysCluj

Status: Needs review » Needs work

The last submitted patch, 184: generic_entityreference_filter_2429699-184.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

_Archy_’s picture

Issue summary: View changes
StatusFileSize
new10.65 KB
new67.86 KB

Coding standards fixes. Some further code improvements. Added more test cases in the UI test and transformed the configuration modifications to drupalPostForms so that it know has better coverage of the functionality. There are still lots of cases that are not covered, but the most important are there. With this I guess we can set the tests checked.

_Archy_’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 187: generic_entityreference_filter_2429699-186.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

pancho’s picture

Status: Needs work » Needs review
StatusFileSize
new67.98 KB
new1.1 KB

Fixed the two little issues causing test failures. Should test green now.

pancho’s picture

1.

I have fixed the issue with the validation not saving the extra options form.

Yay! We're getting closer...

Validation works now, however for some reason, the submit button goes from "Apply and continue" simply to "Apply". It still does continue, so this seems a minor glitch, even though something may be wrong with the stack.

I moved these lines:

-    // This is required for proper validation rendering on AJAX.
-    if ($form_state->getErrors()) {
-      $form_state->set('rerender', TRUE);
-    }

to ConfigHandlerExtra though. This is where @dawehner put them in #2784233-5: Allow multiple vocabularies in the taxonomy filter, parallelling ConfigHandler, and indeed I think this should be handled generically.

2.
However, we still have the problem that switching either the handler or the sort key while adding a new filter will cause the dialog to return to the previous form in the stack rather than rebuild the current one. I managed to fix it for the non-JS case, but not yet for the Ajax case. This remains another @todo.

3.

Also I have introduced a maximum elements settings for the select widget. Defaulted to 30, debatable. Also added a warning log in case there are more than the set maximum when the widget is in select, also this is debatable to how we should do it, a problem with it is that currently it will generate many warning logs in that case. But I think it is still important to notify the site administrators.

We have to do something, given that quite some commenters noticed memory issues with hundreds or thousands of entities. However, I don't think this is a viable approach. If we want to cut the list off at the threshold, at least we'd have to pick a sensible sort order, but even then it will be defunct in many cases. That's why you're logging warnings.

I'd propose a totally different approach: whenever the (still configurable) threshold is crossed, we should automatically fall back to the autocomplete widget. This way we don't even have to log any warning, as relying on this is a safe, sensible and legitimate option for the sitebuilder.

So removed the new, yet superfluous getReferencableEntities() helper, rolling some lines back into getValueOptionsCallback() and valueForm(), the latter of which was broken up into the two new helpers addValueAutocomplete() and addValueSelect(). We might want to further refactor them.

4.
+ protected function getSelectionHandler(): SelectionInterface {
Yay! Indeed we're no longer supporting PHP 5.6, so may declare return types for improved type safety and clarity. Added them to all functions in our new EntityReference handler and the two child handlers we're refactoring.

5.
Another problem is with switching widgets on exposed filters. Our very complicated logic doesn't seem to be 100% correct. We should take a stab at inheriting at least some of this, so this should need some more work, too.

All in all, the patch should be usable more than ever, but not quite ready for Core.

6.
Think we should rename the class to EntityReferenceFilter, so it conveys a bit more of what it is, thereby avoiding confusion with all the other homonymous classes. Yes, display, row and style plugins are named EntityReference, but per https://www.drupal.org/node/608152#naming we should be avoiding ambiguous class names, at least when adding a new class. Awaiting some feedback before going ahead with this, though.

Status: Needs review » Needs work

The last submitted patch, 191: generic_entityreference_filter_2429699-191.patch, failed testing. View results

_Archy_’s picture

Status: Needs work » Needs review

I have started debugging the issues number 2. and I have found that it is caused by the fact that when first adding the filter the AddHandler forms controller path is rendered in the
tag, but the form_id input still has the ConfigHandlerExtra form id inserted into it. This in turn in the FormBuilder causes an if to not throw the FormAjaxException which would normally render the same form.

Now my problems is that I don't quite understand what is the expected behaviour here? Should the form_id be the one from the AddHandler or the path should be changed to be from the ConfigHandlerExtra since we are submitting that form. I will attempt to go with the first solution by changing the ID to the right one and see what happens.

Also @pancho thanks for your indepth review. Also I agree with the switch to autocomplete solution on the list_max, it actually is less of a problem than possible millions of warning logs.

pancho’s picture

Now my problems is that I don't quite understand what is the expected behaviour here?

I will look into it later.

Here's a patch adapting the test that failed in #191 to our new fallback to autocomplete.

_Archy_’s picture

Somebody has found the issue already, linking it here. I think we need to figure out how to change the route callback to go to getForm on ConfigHandlerExtra as oposed to AddHandler.

pancho’s picture

Somebody has found the issue already, linking it here. I think we need to figure out how to change the route callback to go to getForm on ConfigHandlerExtra as oposed to AddHandler.

Technically, this means we have to postpone this issue on #2991982: Ajax in a Views filter handler extra settings form jumps back... :/

Yay! Indeed we're no longer supporting PHP 5.6, so may declare return types for improved type safety and clarity. Added them to all functions in our new EntityReference handler and the two child handlers we're refactoring.

However, we're currently only enforcing PHP 7.0.8, so at least void return types would have to wait, see patch #194 failing on PHP 7.0.

Also, while PHP 7.2 will bring parameter type widening (contravariance), not even PHP 7.3 there is parameter type narrowing (covariance). The moment we're requiring PHP 7.2 is when we may add proper parameter types to base classes without BC concerns. Only then we may add proper parameter types to extending sub-classes. We may however add them for our own (helper) methods.

Also adding/fixing a number of docblocks.

_Archy_’s picture

Assigned: _Archy_ » Unassigned

I've kept debugging to understand better what is happening with the issue, but could not get to it's end. The bug seems to be highly complicated, also I won't have time to continue so unassigning myself. But here are some leads from where others can continue:

  • i've found that the forms when you add a filter are rendered with the proper from id input value but their action will still point to the previous form, so the extra options form to the add handler form, and the options form to the extra options form
  • taught that the above was causing the issue, but I have found that the options form has ajax as well and it works well there (on the expose checkbox), so that above is not the real issue
  • the main issue is the fact that in ViewsFormBase when the ajax callback is made the wrong form class is loaded, for our case instead of ConfigHandlerExtra it is AddHandler, this is why it trows back to the previous modal
  • the above happens because the ajax call from frontend is made to the route of the AddHandler form rather then the ConfigHandlerExtra form; this works well for the other options form, it makes ajax calls to the route of the ConfigHandler form
  • I was unable to find why the ajax calls are made to the incorrect path, but I was searching why the other handler form works good and found some dubious code on the ajax callback that might be related in FilterPluginBase::buildGroupForm
  • attempted to apply that same code in our callback, but I have found that the EntityRerference::settingsAjax is not called when adding the filter handler first time
rosinegrean’s picture

Issue tags: -DevDaysCluj
pancho’s picture

Thanks for your very helpful leads, @_Archy_!

I found the solution in EntityField. Yay!
Indeed, AJAX paths were the problem, and with the proper path being set, the callback gets called as well.

andypost’s picture

+++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
@@ -311,17 +311,18 @@
         'callback' => [get_called_class(), 'settingsAjax'],
+        'url' => views_ui_build_form_url($form_state),
         'wrapper' => $main_form['#id'],

it sounds like wrong to use views_ui module's function in views as I see the same inside \Drupal\views\Plugin\views\field\EntityField so probably it is fine for "only working in UI" methods

pancho’s picture

Well, actually you're totally right that this seems more like a workaround, both here and in \Drupal\views\Plugin\views\field\EntityField, and I noted in #2991982: Ajax in a Views filter handler extra settings form jumps back that this should probably be solved in a generic way.

When constructing a form afresh, ViewsFormBase->getForm() already calls views_ui_build_form_url() and sets $form_state->url accordingly to be picked up by ajaxFormWrapper.

However, the $form_key received by ViewsFormBase->getForm() isn't 'handler-extra'. It is 'add-handler', so this may not work.

There's also this inconsistently commented code:

    // If the form has not been submitted, or was not set for rerendering, stop.
    if (!$form_state->isSubmitted() || $form_state->get('rerender')) {
      return $response;
    }

Either the comment is wrong ("not set for rerendering") or the code is. The opposite however isn't correct, either. I'm a bit confused by the whole code, and while I know #199 works, I unfortunately don't have any idea how to solve this more properly. Everything else I tried, didn't work.

michelle’s picture

The latest patch doesn't apply against 8.7.6. I realize core development goes against the bleeding edge but this patch is a major usability improvement and I would be so grateful if someone who has their head in this would be willing to make one against 8.7.6. :) There's only 1 failing hunk so I'm hoping it wouldn't be hard to do for someone already familiar with the patch. If not, I may try to tackle this on my own but I'm not very familiar with the inner workings of Views. Thanks!

_Archy_’s picture

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

Maybe we can get some maintainer reviews so that additional work can be introduced with the next patch and thus we would get closer to it being introduced in core.

nuez’s picture

Reroll against 8.7.x

murz’s picture

@nuez, seems there are a typo in generic_entityreference_filter_2429699-204-reroll-8.7.x.patch:

-  protected function defineOptions() {
+  protected function defineOptions(): arrayt   {

- arrayt must be array?
Without this I got the fatal error on views edit pages:
Fatal error: Declaration of Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid::defineOptions(): Drupal\taxonomy\Plugin\views\filter\arrayt must be compatible with Drupal\views\Plugin\views\filter\EntityReference::defineOptions(): array in web/core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndexTid.php on line 17

nuez’s picture

Don't know where that came from. Here's another. I'll run the testbot. In any case, the patch from #199 is up for revision, which applies to the 8.8.x branch.

michelle’s picture

Thanks for that, nuez! I'll test it out this weekend.

Edit: Tested it and it applies against 8.7 with no issues and works great. Thanks again!

caspervoogt’s picture

I tested #206 on 8.7. I selected "dropdown" for the exposed filter, but it only renders as an autocomplete field. The dropdown/select UI option seems to be getting ignored. I saved my view, cleared caches, and edited again, but it remains the same.

_Archy_’s picture

If you have a lot of entities it wont allow for rendering as dropdown since it would cause memory and other issues. If there is not already a warning for this we should include one maybe under the field.

caspervoogt’s picture

@ _Archy_ I have 79 published entities that I was trying to get into the dropdown. 83 total if I include unpublished ones. The UI appeared to suggest it cuts off after 30 entities, but I would have expected it to still render, but simply render the first 30 only.

damienmckenna’s picture

Status: Needs review » Needs work
Issue tags: +Needs reroll

This needs a reroll.

damienmckenna’s picture

Status: Needs work » Needs review
Issue tags: -Needs reroll
StatusFileSize
new71.32 KB

Rerolled.

damienmckenna’s picture

FYI with the patch in #212 I'm seeing this error when I open a view which had an exposed ER field from before the patch was applied:

The operator is invalid on filter: [field label]
damienmckenna’s picture

StatusFileSize
new64.91 KB

This is the patch in #212 rerolled for 8.7.7.

damienmckenna’s picture

Status: Needs review » Needs work

I can also confirm that saving the settings dialog after selecting "selector" instead of "autocomplete" does not appear to save, it always shows the autocomplete field on the page and when reopening the settings form it goes back to showing "autocomplete" is selected. So basically Drupal\views\Plugin\views\filter\EntityReference::buildExtraOptionsForm() isn't saving correctly.

damienmckenna’s picture

This is what the exposed field looks like when it's exported:

        field_thing_target_id:
          id: field_thing_target_id
          table: eck_data__field_thing
          field: field_thing_target_id
          relationship: none
          group_type: group
          admin_label: ''
          operator: '='
          value:
            min: ''
            max: ''
            value: ''
          group: 1
          exposed: true
          expose:
            operator_id: field_thing_target_id_op
            label: Thing
            description: ''
            use_operator: false
            operator: field_thing_target_id_op
            identifier: thing
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
              anonymous: '0'
              administrator: '0'
              editor: '0'
            placeholder: ''
            min_placeholder: ''
            max_placeholder: ''
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: numeric
damienmckenna’s picture

Issue summary: View changes

Given that there are two reports (#208, #215) of the select option not working, does the test coverage need to be expanded?

I've added another task for fixing this option, do we need to uncheck the "tests" task too?

caspervoogt’s picture

Thanks for the 8.7.7 patch in #212. This does provide a select/autocomplete filter option for entityref fields that reference taxonomy or nodes (the only entities I tested) AND my choice of 'select' or 'autocomplete' selection type (for the exposed filter) is saved.

However, it still only renders as an autocomplete field, regardless of whether I choose 'select' or 'autocomplete'.

"Given that there are two reports (#208, #215) of the select option not working, does the test coverage need to be expanded?"
I suppose so. Also, FWIW, patch #212 applied cleanly. I see it failed testing but for me it applied cleanly. And when I was testing I watched my logs and saw no errors or warnings.

_Archy_’s picture

I tested and the select widget works. I've added a warning about the entity limit for the select widget since it seems to me that UI was not clear enough about the limit, also added description about it in the settings form. The patch was not applying to 8.8.x I hope I fixed the conflicts accordingly, let's see the tests.

_Archy_’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 219: generic_entityreference_filter_2429699-219.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

c.e.a’s picture

Patch #219 applied successfully on Drupal 8.7.7 with no errors and the added limit & description really make sense !

Thank you

_Archy_’s picture

Issue summary: View changes
Status: Needs work » Needs review
StatusFileSize
new4.17 KB
new76.14 KB

Fixed the tests. Let`em pass pls. Also fixed the issue with the switching between the widgets and previous value not being compatible. This should be really ready for core, we just need some more reviews.

Status: Needs review » Needs work

The last submitted patch, 223: generic_entityreference_filter_2429699-223.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

_Archy_’s picture

Status: Needs work » Needs review
StatusFileSize
new8.08 KB
new72.89 KB

PhpStorm doesn't like copy diff, somehow one of the test view config yamls disappeared.

anybody’s picture

Whao _Archy_ thank you so much, great improvements, works completely fine for me on 8.7.7. RTBC +1
This is a really important feature for 8.8!

caspervoogt’s picture

Wow, _Archy_, that's a massive patch. Thank you for the work!

I just tested the patch from #225 on 8.7.7; it didn't apply cleanly using Composer but when I applied it from the command line it was OK; I just had to tell it which files to patch because it couldn't seem to find some of the files to patch. I tested it with a Views exposed filter but didn't get far; I got this on a brand-new view when I tried to add an exposed filter on an entity reference field (after having cleared caches a few times to make sure);

Configure filter criterion: Broken/missing handler
Appears in: event, news, sector, contract, resource.
The handler for this item is broken or missing. The following details are available:

Enabling the appropriate module may solve this issue. Otherwise, check to see if there is a module update available.

Not sure what I'm missing since it did apply cleanly and it worked for Anybody. Just not for me ;)

neograph734’s picture

Forgive me for not having read through all 200+ posts here and many thanks for all the effort. I believe this is a great start, but I am missing the entity references provided by core.

For instance the Node entity uses entity references to link to a user for the 'Authored by' field (provided by the EntityOwnerTrait). I was more or less hoping (expecting) that the 'Authored by' field would now be available for a select drop down, but it was not. It does work when I add a custom entity reference field (referencing users) to the entity.

On a final note, the order of dialogs in views filters is confusing me. First I have to select that I want to render an autocomplete field or a select box and second I get to choose whether or not I want to expose the filter. I believe it makes more sense if the order of dialogs is flipped (and ideally if the filter is not an exposed filter, do not ask for the widget; I won't be rendered any way).

I'd say that this is not yet ready for production.

_Archy_’s picture

@caspervoogt The patch in 225 is meant for 8.8.x someone should do a reroll for 8.7.x

@Neograph734 Support for the authored by filter is noted in the issue description that a followup task should introduce it. And for the second argument with the configuration ordering I agree but this patch and issue has grown quite large. I think we should focus on testing it, reviewing it and getting it in 8.8.x; the ability to have this types of filters is more important than UX for the admins.

neograph734’s picture

Support for the authored by filter is noted in the issue description that a followup task should introduce it

My bad, I was not aware that Views had a special filter for the user name. I thought it was a general issue for all references defined in entity definitions. I cannot test anymore today, but I'll take your for word for it that those will work.

I think we should focus on testing it, reviewing it and getting it in 8.8.x; the ability to have this types of filters is more important than UX for the admins.

I can imagine and would like to see it too. Thanks again :)

damienmckenna’s picture

StatusFileSize
new13.84 KB

For anyone who needs it, this is a diff between 214 212 and 225.

damienmckenna’s picture

StatusFileSize
new66.62 KB

This is a combination of #214 and #225 for 8.7.x.

damienmckenna’s picture

Note: I'm not sure the #232 diff has all the test files, so the tests might fail. OOps. The files that failed were exported Views defaults, so they might need some manual work to fully reroll the changes in #225.

That said, the patch works for me - the filter settings saves correctly, the "limit" option works correctly, and fields with an item count under the "limit" value are indeed displayed as selectors. Yay!

(of course now we're seeing that some of these views needed to be Search API queries with facets, but that's another story)

So a big +1 from me!

caspervoogt’s picture

tested the patch from #232 on 8.7.7 and it works great. RTBC from me.

marcoscano’s picture

Just posting here my experience with patch #232, which applied cleanly to 8.7.7 for us.

It does allow me to create a new view with an exposed filter on an entity reference field using a select element, by referenced content's title.

It did introduce a negative side effect though. In an unrelated view, a taxonomy exposed filter stopped working, is that expected? Since no DB updates are introduced, I would expect that existing views would be unaltered by this patch.

Here's my existing filter configuration that stopped working after applying this patch:

        field_document_type_target_id:
          id: field_document_type_target_id
          table: media__field_document_type
          field: field_document_type_target_id
          relationship: none
          group_type: group
          admin_label: ''
          operator: or
          value: {  }
          group: 1
          exposed: true
          expose:
            operator_id: field_document_type_target_id_op
            label: Type
            description: ''
            use_operator: false
            operator: field_document_type_target_id_op
            identifier: field_document_type_target_id
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
              anonymous: '0'
              administrator: '0'
            reduce: false
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          reduce_duplicates: true
          type: select
          limit: true
          vid: document_type
          hierarchy: false
          error_message: true
          plugin_id: taxonomy_index_tid

When visiting this view now, it displays an input text element, instead of the select dropdown that the field is configured to use.

Not setting it to NW since I don't know if that's expected, and I also haven't tried to reproduce on a vanilla install.

rgpublic’s picture

@marcosano: AFAIK the configuration is a bit different now (i.e. after the patch). The taxonomy term is now just one case among other others and not "special" anymore. So, you now have to define "widget: select", "handler: default: taxonomy_term" and handler_settings with target_bundles, for example. You can find that if you create a new view after the patch, export the configuration of that one and compare how the taxo field is defined. What I don't know is whether there should be database updates. Probably yes, I'd say, because existing views break otherwise. Perhaps someone more knowledgable can tell why this doesn't seem to be implemented yet.

damienmckenna’s picture

Status: Needs review » Needs work

Sounds we either need an update script or the configuration needs to be adjusted to be backwards compatible.

marcoscano’s picture

(Cross-posted, thanks @DamienMcKenna and @rgpublic!)

OK, just confirmed that by changing:

-          type: select
-          limit: true
-          vid: [my-vocab-name]
+          handler: 'default:taxonomy_term'
+          handler_settings:
+            target_bundles:
+              [my-vocab-name]: [my-vocab-name]
+            sort:
+              field: name
+              direction: asc
+            auto_create: false
+            auto_create_bundle: ''
+          widget: select

in the pre-existing view, the filter is back to what it was, so we definitely need an upgrade path here. (Also a quick search for "upgrade path" on this page shows that @Pancho on #133 had apparently raised this point already :P )

_Archy_’s picture

Issue summary: View changes

Good catch. When I was modifying the issues description I've added a point for existing config migration with question mark since I was not sure we needed one, but now its for sure.

_Archy_’s picture

StatusFileSize
new66.62 KB

Reuploading patch to trigger tests since it was added for wrong version.

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.

lefale’s picture

This patch is wonderful and thank you all for your hard work. Here is an issue that I encountered (using Drupal 8.7.X).

When using a View (along with the select widget) to populate the list of options, the entity label is used for the option label. Is this the normal behaviour? I was expecting the label to be the output of the view (as rendered by the Row Renderer plugin) since my view display uses a field of the referenced entity instead of the entity title.

It is worth mentioning that the list of options is populated correctly in the node edit form, so I guess both lists should look identical.

dww’s picture

@lefale re: #242: That's at #2174633: View output is not used for entityreference options.

In addition to the 2 failing tests, this also introduces the following code standards violations:

/var/lib/drupalci/workspace/jenkins-drupal_patches-11408/source/core/modules/taxonomy/src/Plugin/views/filter/TaxonomyIndexTid.php
line 2	Whitespace found at end of line
/var/lib/drupalci/workspace/jenkins-drupal_patches-11408/source/core/modules/views/src/Plugin/views/filter/EntityReference.php
86	Multi-line function declarations must define one parameter per line
401	Data types in @param tags need to be fully namespaced
410	TRUE, FALSE and NULL must be uppercase; expected "NULL" but found "null"
434	Avoid backslash escaping in translatable strings when possible, use "" quotes instead

I need this on a project I'm currently working on, and hope to have time for a more thorough review, testing, and possible re-roll next week. If I start working on the patch itself, I'll assign to myself. Otherwise, if anyone else wants to work on the failing tests (which on quick skim seem like legitimate failures) and the code style bugs, please do. :)

Cheers,
-Derek

m.lebedev’s picture

Hi! I think that the option "Maximum entities in select list" should not be required. Limiting up to 100 items will affect the expected result of existing sites.

_Archy_’s picture

It has to be required for two important reasons. firstly if there are too many entites we can get out of memory errors or the view can get super slow till the point of unusability. second is that if you have more than 100 entities in a select list that is in no way ux friendly and you really need to reconsider the way the filter works.

m.lebedev’s picture

I agree. However, there are requirements when needing to ignore limits. It would be great if the settings had the option to turn off the limit. The developer consciously makes a choice by disabling limits.

andypost’s picture

Related issue landed in 8.8 so limit could be used from the field settings

gbirch’s picture

Patch #240 applies cleanly to 8.7.9, but when added to a view on a user reference field (that uses entityreference view as a source), I get: The handler for this item is broken or missing. The following details are available: with no further information.

The patch applied successfully, but put some files above the document root. With that fixed by hand, it Is now working fine. Sorry to bother you!

damienmckenna’s picture

@gbirch: did you clear/rebuild the site's caches after applying the patch?

gbirch’s picture

@DamienMcKenna - overlapping edits. See above. Thanks!

damienmckenna’s picture

No worries, the composer patches process gets a bit wonky sometimes.

kasey_mk’s picture

I agree that "Maximum entities in select list" should not be required. A warning in the description will allow developers to use their own best judgement for their own circumstances.

UX can be made more friendly with tools like the Chosen module.

heddn’s picture

Status: Needs work » Needs review
StatusFileSize
new72.98 KB

Let's move the latest patch as the latest upload... Here's the patch from #225.

Status: Needs review » Needs work

The last submitted patch, 253: 2429699-253.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

superfluousapostrophe’s picture

StatusFileSize
new49.54 KB

I am having an issue with the #225 patch - I'm not 100% clear on how to explain it (or even if it's directly related to the patch), so here goes:

I have a view which shows a table of Orders to a user, restricted to the vendor or vendors that the user has access to. I am trying to create an exposed filter on that Order view which uses an Entity Reference View to display the vendors available to the user in a select box.

Whenever I go to add the filter, I get the following error in the ajax response:

TypeError: Argument 2 passed to Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection::getDisplayExecutionResults() must be of the type string, null given, 
called in /app/web/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php on line 243 in 
Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection-&gt;getDisplayExecutionResults() 
(line 266 of /app/web/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php).

dialog

I am running 8.8.0. I'd appreciate any help on this.

jastraat’s picture

#225 worked for our purposes against Drupal core 8.8.0. (It did not apply cleanly however.) #253 did NOT work for us.

wstocker’s picture

Confirmed #225 applied against Drupal core 8.8.0, but we are getting the same error mentioned in #255.

c.e.a’s picture

#225 did applied against Drupal core 8.8.0, but we are getting the same error mentioned in #255

So basically the patch is not working and there is no working patch for Drupal Core 8.8.x.

Any help please ?

Drutech’s picture

Any help please on this issue !

Not a single patch available here is applied and working on my 8.8.0 site.

can someone with enough experience fix this issue ?

@_Archy_

heddn’s picture

When patch is used in combo with better exposed filters, you can no longer rewrite the options. Basically, there are BC concerns with what is going on here. It is BC around expected form structure, which form structure is explicitly called out as a internal. So it can be done, its just that the CR should discuss that edge case and that views will need to be adjusted if they are using BEF and rewriting options.

c.e.a’s picture

@heddn I affraid the Better Exposed Filter module does not have any conflict while used with this patch as because the patch #225 or #253 both are generating the below error even while the Exposed form style for filters is set to Basic with in the view.

Note: I am running Core version 8.8.0

Error:

TypeError: Argument 2 passed to Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection::getDisplayExecutionResults() must be of the type string, null given, called in /home/####/public_html/####.com/web/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php on line 243 in Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection->getDisplayExecutionResults() (line 266 of /home/####/public_html/####.com/web/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php) #0...

kasey_mk’s picture

StatusFileSize
new33.99 KB

EDIT: Sorry, I realized I made a mistake and this patch only includes new files, not edited ones. And of course I've thrown away my workspace since then. :(

#232 had been working for us before updating to Drupal 8.8.... but for the life of me I can't figure out why/where we were using it. Everything I touched on the branch where I added the patch from #232 seems fine without it.

But before I figured that out, I re-implemented that patch against 8.8. So here that is in case anyone finds it useful.

kasey_mk’s picture

StatusFileSize
new66.67 KB

For real this time, a re-roll of patch #232 against 8.8.x. With limits set to 1000 instead of 100, because when I needed this patch, 100 was too low.

c.e.a’s picture

@Kasey_MK I have applied your patch #263 which applied cleanly but yet the same error mentioned in #261 persists.

Patch not working for me ! Thank you

gbirch’s picture

The error in #263 is caused by the code at line 597 of views\Plugin\views\EntityReference.php, in the new function getValueOptionsCallback().

Specifically, it appears that

$entities = $selection_handler->getReferenceableEntities(NULL, NULL, $list_max + 1);

should be

$entities = $selection_handler->getReferenceableEntities(NULL, 'CONTAINS', $list_max + 1);

This is because getReferencableEntities passes the NULL on to getDisplayExecutionResults(), which itself requires that argument to be a string, for reasons that are not entirely silly.

@Kasey_MK, do you agree, and would you be willing to re-roll the patch?

scott_euser’s picture

Assigned: Unassigned » scott_euser

Working on this now

scott_euser’s picture

Assigned: scott_euser » Unassigned
Status: Needs work » Needs review
StatusFileSize
new76.93 KB
new17.39 KB

Updated patch.

  • Updated some coding standards and missing docblock info.
  • Updated non-required limit so that default limit of 30 is not applied if no limit is set (so its actually unlimited).
  • Added to the limit description to make the warning clearer.
  • Updated Taxonomy Term select so limit is applied even if hierarchical (and hierarchy is not lost).
  • Added in the file containing the viewconfig from #225 that was missing preventing FilterEntityReferenceWebTest tests from running

I do have a slight concern we are perhaps doing too much here? Should the whole limit thing be a follow-up / separate issue? It seems to be expanding the scope of just generalizing the TaxonomyIndexTid class. Feel free to disagree of course!

c.e.a’s picture

@scott_euser thank you for your kind help !

Finally there is a patch working with no errors for Drupal Core 8.8.x

Patch #267 is working as expected

scott_euser’s picture

No problem, but I think that the tests are failing though. It seems to be because the tests are now running against 8.9.x instead of 8.8.x and don't seem to do with the actual patch https://dispatcher.drupalci.org/job/drupal_patches/22994/consoleFull

Will see if just triggering it to re-run the tests helps.

On local they pass:

Drupal test run
---------------

Tests to be run:
  - Drupal\Tests\views_ui\Functional\FilterEntityReferenceWebTest

Test run started:
  Saturday, December 21, 2019 - 10:14

Test summary
------------

Drupal\Tests\views_ui\Functional\FilterEntityReferenceWebTes   1 passes                                      

Test run duration: 23 sec
Drupal test run
---------------

Tests to be run:
  - Drupal\Tests\taxonomy\Functional\Views\TaxonomyIndexTidUiTest

Test run started:
  Saturday, December 21, 2019 - 10:17

Test summary
------------

Drupal\Tests\taxonomy\Functional\Views\TaxonomyIndexTidUiTes   2 passes                                      

Test run duration: 51 sec
scott_euser’s picture

Triggered a run of #267 against 8.8.x now (though I tested locally against 8.9.x so not sure if that will work)

c.e.a’s picture

After further testing, Patch #267 is working for some views and generating an error on some other views.

Error Description:

TypeError: Argument 3 passed to Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection::getDisplayExecutionResults() must be of the type integer, string given, called in /home/####/public_html/my.valetop.com/web/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php on line 243 in Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection->getDisplayExecutionResults() (line 266 of /home/####/public_html/my.valetop.com/web/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php)

Any idea on what it is going on ?

scott_euser’s picture

Updated should pass tests against 8.8.x. Seems there is a rogue config not part of schema in one of the test view configs (core/modules/views/tests/modules/views_test_config/test_views/views.view.test_filter_entity_reference.yml), though not sure it is related to this issue or whether it should be in a separate issue scope.

scott_euser’s picture

Re #271 error:
TypeError: Argument 3 passed to Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection::getDisplayExecutionResults() must be of the type integer, string give
Is it possible that you have something left over from an old patch. If you resave your extra settings for wherever you have set a max number of entities, it should save them as integers. That error indicates something is saved as a string, but I don't see anything in the code that could lead to `list_max` being a string.

scott_euser’s picture

Okay tests now passing. Needs review I think before we work on last task 'existing configuration migration'?

mdolnik’s picture

I am getting the same error with patch #272

TypeError: Argument 3 passed to Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection::getDisplayExecutionResults() must be of the type integer, string given, called in var/www/html/public_html/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php on line 243 in Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection->getDisplayExecutionResults() (line 266 of core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php).

This can occur on existing exposed filters created using old patches and newly added exposed filters. Steps to reproduce:

  1. Add an exposed filter for an entity reference field
  2. Edit the settings
  3. Set the Reference Method to Views: Filter by an entity reference view
  4. Select a View used to select the entities
  5. Choose Select list in Selection type
  6. Leave Maximum entities in select list blank
  7. Apply the settings

An exception is thrown.

This is because $list_max = $this->options['list_max'] ?? -1 in \Drupal\views\Plugin\views\filter\EntityReference::getValueOptionsCallback() will not transform the list_max value to -1 if it is an empty string since the null coalescing operator ?? will only work on NULL/unset values and not empty strings.

This exception will not occur on the regular "Default" selection handler because DefaultSelection::getReferenceableEntities() and other methods it calls do not have strict parameter types, but ViewsSelection::getReferenceableEntities() calls ViewsSelection::getDisplayExecutionResults() which has strict parameters which is what throws the exception on the string passed in int $limit parameter.

mdolnik’s picture

Added fix regarding comment #275

scott_euser’s picture

Thanks, good spot! It seems your patch contains quite a few more changes than your interdiff shows (looks like an auto format on save). I applied your change to #271 and attached an interdiff from both that and from your #276. This patch fixing the missing closing } of the class which was causing the linter fail / fatal error so tests can now rerun.

Status: Needs review » Needs work

The last submitted patch, 277: drupal-generalize-taxonomyindextid-filter-2429699-277.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

scott_euser’s picture

Looks like a completely unrelated failure related to some change to media library.

dww’s picture

Re: #279 -- yeah, I think that's at #3066447: [random test failure] Random failures building media library form after uploading image (WidgetUploadTest). Re-queued #277 for testing. Let's see if it passes this time...

scott_euser’s picture

Status: Needs work » Needs review

Nice, thanks! Tests passing.

scott_euser’s picture

Still eventually needs config update but general functionality needs review before doing that I think.

wstocker’s picture

Confirming that #277 was applied against Drupal core 8.8.0 and this resolved the error we saw in #255.

superfluousapostrophe’s picture

The patch in #277 applies cleanly via composer in 8.8.1 and seems to solve the problems I was having. Thank you!

damienmckenna’s picture

Some details of my testing of #277 on a new site that didn't have the patch applied previously..

  • This site has two views with exposed entity reference fields.
  • The first view continued to work fine as-is on the front-end after the patch was applied.
  • I edited the first view, clicked on the existing exposed field to open its dialog, didn't change anything, clicked the "save" button and it gave the "An illegal choice has been detected. Please contact the site administrator." error message; this also happened when I clicked the "cancel" button, I ultimately had to click the close button on the dialog to make it close.
  • I then edited the "settings" on the exposed field, changed it to a select field, clicked save, then went back to the field dialog and again it wouldn't save without the error message; looking more closely I realized that the existing "operator" selection was no longer valid, which is why it was failing.
  • I then opened the edit for on the second view, and noticed that the preview had this message: The operator is invalid on filter: [name of exposed field]. This resulted in not being able to save the view until I edited the exposed field to correct the operator.
  • Exporting the site's configuration after applying the patch doesn't change anything, you have to first fix the exposed operator and save the view to see the changes.

I think the problem is that the exposed filter's options change like so:

-          operator: '='
-          value:
-            min: ''
-            max: ''
-            value: ''
+          operator: or
+          value: {  }

I would suggest the backwards compatibility needs to be improved to avoid this problem.

scott_euser’s picture

That sounds like the 'existing configuration migration' remaining task from the issue description, but as per my comments above shouldn't we first get review of the general approach before we spend time on the upgrade path?

kasey_mk’s picture

Thanks so much for everyone's work on this. After coming back from a holiday and re-discovering the use case I had for this patch, I am relieved to find that #277 has been made and works for me.

costellofax’s picture

In case anyone else runs into this--for us, #277 applied cleanly on 8.8.1 but, when used with search_api 8.x-1.15 and search_api_solr 8.x-3.8, it caused taxonomy term reference exposed filters on indexed content views to throw:
Notice: Undefined index: entity_type in Drupal\views\Plugin\views\filter\EntityReference->getFieldStorageDefinition() (line 62 of .../core/modules/views/src/FieldAPIHandlerTrait.php)
and
Error: Drupal\Component\Plugin\Exception\PluginNotFoundException: The "" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 150 of .../core/lib/Drupal/Core/Entity/EntityTypeManager.php).

colan’s picture

Status: Needs review » Reviewed & tested by the community

#286: Let's set to RTBC to get a review from the core committers before proceeding with the migration work. They can set it back to NW with feedback.

gambry’s picture

I believe asking an initial review is understandable, but probably we should also flag this currently requires both an upgrade path and a change record. Besides as it is affecting at least 3 subsystems (node, taxonomy, views) and may affect quite few drupal instances probably a framework manager approval would be beneficial too.

I'm not sure RTBC is the right status, as we all now this needs still work, but because general consensus is to use this status to gather attention then ...It's better to ask forgiveness than permission. :p

gambry’s picture

Issue summary: View changes

Adding approval and change-record requirements to the IS tasks.

scott_euser’s picture

Status: Reviewed & tested by the community » Needs review
StatusFileSize
new4.28 KB
new45.77 KB
new13.58 KB
new14.45 KB

It's better to ask forgiveness than permission. :p

Love this! I think 'Needs review' is probably already stretching it enough since, as you say, we all know it needs further work.

I think we maybe need to consider the functionality in general a bit more as a group though anyway. While this does provide the ability to for instance have nodes in a select list on a view (which is why I assume most people would like this feature):
Image of entity reference exposed filter as select list

I cannot see how we provide an upgrade path from a text field (which is probably not very useful, but that is beside the point):
Image of entity reference exposed filter as text field

With only these options available with the patch applied:
List of possible input types for entity reference after applying patch

Should we not continue to allow that status quo and let site builders consciously decide to make use of this as a new feature? When I look at https://www.drupal.org/project/verf I see their approach was to create it as a separate option in the list of possible filters to add:
List of filters to add with VERF module enabled.

Mokshit06’s picture

StatusFileSize
new79.29 KB

Sorry this is an incorrect interdiff file.

Mokshit06’s picture

StatusFileSize
new301 bytes

This is the correct interdiff file for comment 267 and 277

scott_euser’s picture

Title: Generalize TaxonomyIndexTid filter to be available for all entity reference fields » Add Views EntityReference filter to be available for all entity reference fields
Issue summary: View changes
StatusFileSize
new45.7 KB
new28.52 KB

After discussion on slack in the #contribute channel, lets reduce the scope of this to adding the EntityReference views filter only to avoid the breaking changes and challenges outlined above with migrating existing usage of the TaxonomyIndexTid filter.

The attached patch essentially removes the bits of the preceding patches that change TaxonomyIndexTid, yet still allows you to use entity references as views filters with the select, autocomplete, max limits (and potentially as checkboxes / radio lists for instance in combination with better exposed filters module).

I have tried to avoid any changes to the patches thus far and just reverting the bits that are beyond just the Entity Reference views filter.

I have updated a fair bit of the description and the title to reflect this - please have a look at the changes there too.

Status: Needs review » Needs work
scott_euser’s picture

Status: Needs work » Needs review
StatusFileSize
new44.58 KB
new887 bytes

Whoops, missed one artefact relating to TaxonomyIndexTid conversion

scott_euser’s picture

Issue tags: -Needs upgrade path

No longer needs upgrade path

ckaotik’s picture

Great work everyone! Love that this has gotten so much attention. I'm wondering when using the autocomplete widget, can we keep the query parameters to stay as id-only, instead of the current &my_field=some+long+entity+title+(42)? It makes urls quite long and in case the widget is changed to select later on, makes existing urls invalid.

stopopol’s picture

Just applied the patch smoothly on 8.8.2 and it nicely changed the text field into an autocomplete widget in my view filter. I played around with the select options and couldn't find any bugs so far. Everything works smoothly.

I think this can be commited.

ibullock’s picture

Patch in #297 appears to break entity reference fields in use on Webforms. Entity reference fields on Webforms always report the referenced entity does not exist. Rolling back the patch causes them to work once more. This could be a webform issue, but worth noting for anyone looking to implement this.

Never mind, issue seems to be something in node access.

capysara’s picture

Worked for me! I applied the patch to a fresh install of 8.8.2 and to an existing site on 8.8.1 (updating an earlier version of the patch).

scott_euser’s picture

Great to hear its working. If one or two people in the community have a chance to review it would be great to get this to RTBC for maintainer review.

I think we can also remove these two bullet's from the issue description?
☐ get framework manager approval
☐ write change record
Since its no longer a change, I believe it now only needs release notes (+ the follow-up tasks listed like documentation).

nord102’s picture

Noting that I'm currently using the patch from #297 and it applies cleanly and is working as expected.

I noticed some strange behaviour when using the patch from #297 in combination with changing the Reference method to Views: Filter by an entity reference view and specifying an Entity Reference view.

The view does work as expected on the front-end, but once that setting is set to the above, the view from the admin side is unreachable / results in a timeout error when attempting to navigate to the edit view page.

Wondering if anyone else has run into this or can reproduce this issue with the same steps as above.

gbirch’s picture

Folks, this patch needs to incorporate the work done in https://www.drupal.org/project/drupal/issues/2957376, which has already been committed to core, but which is not used here. Otherwise you can get views that can't be saved, WSOD, etc.

scott_euser’s picture

@gbirch Can you please elaborate and provide steps to reproduce? It would be good if it is directly related to the addition of this new filter. Things related to other filters would probably best reside in a different (new) issue to keep this scope limited to its goal.

gbirch’s picture

Under some circumstances, triggered by I know not what, other than that it has happened to me, a filter on a view will point to a vocabulary that does not exist, or is not loaded when needed. This causes fatal errors. The patch merely checks for the existence of the vocabulary object before attempting to call a function on it. You may wish to read the original issue. The patch applies cleanly over this patch, and it stopped the errors I was experiencing and returned the erring view to functionality.

I can't give you steps to reproduce, because the view in question is an elaborate beast that applies to a content type with more than 100 fields. Do with this as you like, but the patch is short, simple, easy to understand, and seems to work. It would be interesting to know if it solves @nord102's issue.

stopopol’s picture

After applying the patch, the view worked fine for a while, but after an update using composer (i think this is when it started) I get this error message:

Drupal\Component\Plugin\Exception\PluginException: Plugin (entity_reference) instance class "Drupal\paragraphs\Plugin\views\filter\EntityReference" does not exist. in Drupal\Component\Plugin\Factory\DefaultFactory::getPluginClass() (line 97 of /var/www/drupal/web/core/lib/Drupal/Component/Plugin/Factory/DefaultFactory.php).

When I have a look at web/core/modules/views/src/Plugin/views/filter/EntityReference.php everything's there.

This causes the view to return a WSOD and I can't even edit the view anymore.
Also when I try to add a new view and recreate this, I get this error message as soon as I try to add the filter.
This might be the issue described in #305 or it might mean that the patch doesn't work for core 8.8.3. I can't narrow it down.

Any ideas on how to fix this?

brandonratz’s picture

I am having the exact issue @stopopol mentioned. Also the patch #297 had been applied for some time and now when upgrading to 8.8.3 the view is now failing.

Drupal\views\Plugin\views\query\Sql->execute() (line 1543 of /app/web/core/modules/views/src/Plugin/views/query/Sql.php).

Currently, the only way to edit a view which uses this exposed entity reference source is to DISABLE the view being referenced.

EDIT:

The error appears to be from NOT setting "Maximum entities in select list". When I added a value here, the errors went away.

murz’s picture

The error appears to be from NOT setting "Maximum entities in select list". When I added a value here, the errors went away.

I got same problem when NOT setting "Maximum entities in select list", the source of failing is wrong LIMIT in SQL query:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-1 OFFSET 0' at line 4:
... ORDER BY nested_set_field_parent_node_left_pos ASC LIMIT -1 OFFSET 0
murz’s picture

I fix problem when NOT setting "Maximum entities in select list" via setting 0 instead of -1 in $list_max value, patch is attached. With this fix - MySQL error LIMIT -1 OFFSET 0 is disappear. @brandonratz, can you retest your issue with my patch?

vasike’s picture

quick check on #311 - it doesn't work for "Required" option

No valid values found on filter:

+ It doesn't filter properly - as i got no results

Entity reference node to node ...


Updates: So direct reference it seems it "works as designed"

The issues are for Entity reference field with "Relationship".

Updates2: please Forget about `Relationship` issue (my fault - i was missing something).

Other issue is for "Required" and no "Selected content items" ... i think it could from what it founds.
Anyway if there are too many then i don't think the required option is selected ... and also it's not selectable from "1802" options ...

shabana.navas’s picture

I am wondering how we get the autocomplete to display for a custom entity which has references to other entities. My custom entity has a reference to a Commerce Product Variation and Commerce Product. Right now, it doesn't give me an autocomplete or select list option for these references. Do we have to do anything programmatically to enable this feature for custom entities?

This is a must needed patch. Thanks for all the hard work.

vasike’s picture

So tested more #311 and it seems it works as "designed"

I also updated my previous comment #312 - so the only thing it's "Required" for All References ... which for sure it's another issue ... but good to know

johnwebdev’s picture

Code review. Here's a start.

  1. +++ b/core/modules/views/config/schema/views.filter.schema.yml
    @@ -128,6 +128,29 @@ views.filter.many_to_one:
    +      nullable: false
    ...
    +      nullable: false
    ...
    +      nullable: false
    

    Can be removed.

  2. +++ b/core/modules/views/config/schema/views.filter.schema.yml
    @@ -128,6 +128,29 @@ views.filter.many_to_one:
    +      translatable: false
    ...
    +      translatable: false
    ...
    +      translatable: false
    

    Can be removed.

  3. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,746 @@
    +   * Type for the auto complete filter format.
    

    auto complete => autocomplete

  4. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,746 @@
    +  protected function getSelectionHandler(): SelectionInterface {
    ...
    +  protected function defineOptions(): array {
    ...
    +  public function hasExtraOptions(): bool {
    

    Not sure we can use return type declarations? I know there is a issue on this somewhere though.

  5. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,746 @@
    +    $options['list_max'] = ['default' => ''];
    

    According to our schema this should be a integer and cannot be null.

  6. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,746 @@
    +        $handlers_options[$selection_group_id] = Html::escape($selection_plugins[$selection_group_id][$selection_group_id]['label']);
    ...
    +        $handlers_options[$selection_group_plugin] = Html::escape($selection_plugins[$selection_group_id][$selection_group_plugin]['base_plugin_label']);
    

    Why do we need Html::escape here?

  7. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,746 @@
    +      '#process' => [[get_class($this), 'fixSubmitParents']],
    ...
    +   * Render API callback.
    ...
    +  public static function fixSubmitParents(array $form, FormStateInterface $form_state): array {
    ...
    +  public static function fixSubmitParentsElement(array &$element, $key) {
    

    Can we add further documentation to explain what's going on here?

  8. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,746 @@
    +    // There is no need in polluting filter config form.
    +    $form['reference']['handler_settings']['target_bundles']['#ajax'] = FALSE;
    +    $form['reference']['handler_settings']['target_bundles_update']['#access'] = FALSE;
    

    Is this a typo (#ajax = FALSE) or intended? Can we clarify with a comment what we're doing here.

jantoine’s picture

Status: Needs review » Needs work

The latest patch in #311 has a performance issue that is most likely attributing to those experiencing the WSOD. I ran into this issue when trying to update a view that was using the previous patch from #71, but was also able to reproduce when deleting the filter completely and re-adding it to the view.

The issue occurs when a filter is being added for entity reference fields where a large number of entities already exist for the referenced entity type. To reproduce, create 10,000+ entities of a given entity type and then attempt to add an entity reference filter to a view for a field referencing that entity type.

The cause of the issue is not having a reasonable default value for the 'list_max' option. Using a default of 10 adds the filter quickly returning the configuration form where the 'list_max' value can then be altered.

sagesolutions’s picture

I am also having performance issues with patch #311.

What is strange for me is that other views that do not include any entity reference filters are also periodically seeing a WSOD and memory usage errors.

I'm wondering if this patch is effecting all views, not just views that use the filter.

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes) in /var/www/html/drupal/web/core/lib/Drupal/Core/Cache/DatabaseBackend.php on line 167

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes) in /var/www/html/drupal/web/core/lib/Drupal/Core/Session/SessionHandler.php on line 76

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes) in /var/www/html/drupal/web/core/includes/errors.inc on line 26
sagesolutions’s picture

Update:

So it turns out my one of my blocks in an view has a filter on a multi-valued field which is checking if that field is not null (empty). Removing this filter also removes the WSOD.

This is most likely unrelated to the entity reference filter, but it did start happening at approx. the same time as I added the #311 patch.

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.

rockaholiciam’s picture

The patch in 297 does not seem to work for entity references that are predefined in code as part of custom entities and not created via interface.

rockaholiciam’s picture

Infact, it seems any special handling of views filters for fields that are defined as part of entity in code is being ignored. Tried to add one for daterange and it too doesnt work for the field defined in code but does work if I add another via interface? Anyones got any idea why this is so?

berdir’s picture

scott_euser’s picture

Status: Needs work » Needs review
StatusFileSize
new43.69 KB
new6.9 KB

Thanks for the code review @johnwebdev

1. Removing nullables from config schema
Removed as suggested

2. Removing translatables from config schema
Removed as suggested

3. Auto complete should be autocomplete in comment
Comment fixed

4. Return type declarations
From what I can see, since minimum required version is php 7.0.8, this is available, though it is being discussed here. Not sure if its safer to remove for now or leave in as it has no ill effect?

5. list_max schema is integer so should not be ''
Good spot - updated to be '0' which matches now the default for SelectionInterface. I have updated the field description accordingly

6. Use of Html::escape()
I have removed though I am not fully confident about it; could it be because a Label could potentially cause an issue as an array key if it has special characters?

7. fixSubmitParents and fixSubmitParentsElement documentation
I have added back in the comments from the original addition of that to the code. Full disclosure, I did not attempt to get my head around what the issue was when it was added.

8. #ajax false mixed in with #access false
Actually this appeared to be required. The handler list of entity bundles to allow does not show up without it. I have separated it from the display changes (#access) and added a comment.

Additionally:

I have set the default list_max back to 100. It appears not having this has caused user's of the patch a bit of grief. I think better to have user's consciously decide to remove the limit. This avoids the risk of a WSOD immediately within the views preview if the user does not make a choice.

Status: Needs review » Needs work
scott_euser’s picture

Status: Needs work » Needs review
StatusFileSize
new621 bytes
new43.7 KB

Added return typehint to test for D10 compatibility

honyik’s picture

Hello, how does one actually use this? I've been using this module: https://www.drupal.org/project/entity_reference_exposed_filters but the update to core from 8.8.4 to 8.8.6 has broken it. I suppose that changes made in this thread made it to the core code? If so, how do I implement this? I've applied the 325 patch and I've search for the filter field "Content: content" as per the description of this issue and I can't find anything, can anybody advise please? I don't need anything too fancy, just an exposed filter containing titles of the nodes referenced by the displayed nodes. Thanks a lot

scott_euser’s picture

If you installed with composer, you can apply a patch using this https://github.com/cweagans/composer-patches/blob/master/README.md (you could find tutorials by searching for "composer patches drupal" for instance). You could alternatively use
https://www.drupal.org/project/verf which may serve your purpose.

Via this patch, if you for instance have a field_organisations, which is an entity reference for an Organisation node bundle, you would add the filter for field_organsations to the View and, in additional to the option of displaying as an auto complete input field, with this patch you can also choose to make it a select box (or with Better Exposed Filters module a series of checkboxes or radio inputs depending on single or multi-select).

honyik’s picture

I knew how to apply the patch, but didn't know how to set up the view, I do now, thank you very much :)

aswathyajish’s picture

#297 worked for me. Thanks.

ivanaldavert’s picture

Hello folks,

I got

"Could not apply patch! Skipping. The error was: Cannot apply patch https://www.drupal.org/files/issues/2020-02-08/drupal-generalize-taxonom..."

on 9.0.1,

any clue?

Thanks!!

krzysztof domański’s picture

@ivanaldavert You are using an older patch #297. In the meantime, something has been commited so the old patch is not applying in the new version of Drupal 9. Try applying one of the recently added patches. I have not tested them and there is no guarantee that they will work as expected. It may still require additional work. Read previous comments.

Good luck!

scott_euser’s picture

Can use #325 latest, it's effectively the same but updated code to match drupal 9 and addresses a few minor tweaks from code reviews. Functionality is the same and structure is the same so no upgrade needed from 297 to 325, just replace the patch.

ivanaldavert’s picture

Hey Krzysztof,

- Installing drupal/core (9.0.1): Downloading (100%)
- Applying patches for drupal/core
https://www.drupal.org/files/issues/2020-05-23/drupal-generalize-taxonom... (Add Views EntityReference filter to be available for all entity reference fields)
Could not apply patch! Skipping. The error was: Cannot apply patch https://www.drupal.org/files/issues/2020-05-23/drupal-generalize-taxonom...

It happens the same with the last patch...

krzysztof domański’s picture

StatusFileSize
new43.7 KB

Re-rolled.

patching file core/modules/views/config/schema/views.filter.schema.yml
patching file core/modules/views/src/Plugin/views/filter/EntityReference.php
patching file core/modules/views/tests/modules/views_test_config/test_views/views.view.test_filter_entity_reference.yml
patching file core/modules/views/views.views.inc
Hunk #1 succeeded at 809 (offset 1 line).
patching file core/modules/views_ui/src/Form/Ajax/ConfigHandlerExtra.php
patching file core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php

#2824935: Fix Squiz.ControlStructures.SwitchDeclaration coding standard was commited and core/modules/views/views.views.inc has been changed. The same file has been modified in the last patch but re-roll was not necessary. The automatic test fails if the patch cannot be applied but has passed successfully.

@ivanaldavert It looks like you have a conflict with patches. Probably another patch also modifies the same file. Check other patches that modify the views or views_ui modules.

ivanaldavert’s picture

Hi,

 "patches": {
      "drupal/core": {
        "Add Views EntityReference filter to be available for all entity reference fields": "https://www.drupal.org/files/issues/2020-06-21/2429699-334.patch"
      }
    }

I just have one patch, I just tried with the last one but still not working... should I reinstall something?

Thanks!

krzysztof domański’s picture

@ivanaldavert Delete the core/ directory and reinstall it. It looks like the previous patch was not fully applied or something.

ivanaldavert’s picture

Deleted the core but still not working with the latest patch... any idea?

cilefen’s picture

https://www.drupal.org/files/issues/2020-06-21/2429699-334.patch applies to all versions of Drupal 9.

If you are on a system with the right utilities, output of the following would be interesting to see:

curl https://www.drupal.org/files/issues/2020-06-21/2429699-334.patch | patch -p1 --verbose
ivanaldavert’s picture

This is the output:

% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
9 44744 9 4104 0 0 77433 0 --:--:-- --:--:-- --:--:-- 77433
curl: (23) Failed writing body (1363 != 1371)

am I missing something there?

cilefen’s picture

@ivanaldavert

I am sorry to hear you are still having issues. It seems the patch utility may not be installed on that system. It could be https://github.com/cweagans/composer-patches/issues/316, assuming you are using cweagans/composer-patches.

But a general inability to patch is out of scope for this issue and this conversation is noise for the > 200 people following it. If you continue to have problems patching it will be better if you work that issue at https://github.com/cweagans/composer-patches.

ivanaldavert’s picture

It looks that my sistem had an error and the patched was not applied. Now works perfectly, thanks guys!

stopopol’s picture

I just cleanly applied the patch in #334.
So far I haven't found any issues with it.

EDIT: As far as I can tell, the patch also applies to Core #8.9.2

c7bamford’s picture

EntityReference->getValueOptionsCallback defaults to loading every entity. This seems incorrect. Also, it breaks views_ui on my site. I have tens or hundreds of thousands of entities. Perhaps countReferenceableEntities should be used instead of getReferenceableEntities, then if the count is over the limit, switch to an autocomplete.

stopopol’s picture

The patch in #334 doesn't apply to 8.9.3 anymore.

c.e.a’s picture

Patch #297 applied cleanly on Drupal Core 8.9.3

stopopol’s picture

The patch in #334 cleanly applies to 8.9.4, 8.9.5 and 8.9.6

david.qdoscc’s picture

Patch #334 is also working for me on 8.9.6 along with Selective Better Exposed Filters to only show titles that appear in the result set :) Nice!

heddn’s picture

Status: Needs review » Needs work

I feel bad about this, but I'm getting schema validation issues on a site with this patch applied. I think (hope) it should be a quickfix to update the config schema.

Unexpected error during import with operation create for views.view.accessories: Schema errors for views.view.accessories with the following errors: views.view.accessories:display.default.display_options.filters.field_bike_models_target_id.value variable type is NULL but applied schema class is Drupal\Core\Config\Schema\Sequence, views.view.accessories:display.default.display_options.filters.field_bikes_target_id.expose.reduce missing schema, views.view.accessories:display.default.display_options.filters.field_bikes_target_id.reduce_duplicates missing schema, views.view.accessories:display.default.display_options.filters.field_bikes_target_id.handler missing schema, views.view.accessories:display.default.display_options.filters.field_bikes_target_id.handler_settings missing schema, views.view.accessories:display.default.display_options.filters.field_bikes_target_id.widget missing schema, views.view.accessories:display.default.display_options.filters.field_bikes_target_id.list_max missing schema, views.view.accessories:display.default.display_options.filters.field_bikes_target_id.handler_submit missing schema'
berdir’s picture

@heddn: I assume that's existing views that had those entity reference fields already as filters? That's not easy to fix, because with this, the old structure becomes invalid.

heddn’s picture

Status: Needs work » Needs review

@Berdir, it sure was cruft. I guess that should be fodder for any CR that gets added. Backs to NR.

mparker17’s picture

StatusFileSize
new44.59 KB
new44.59 KB
new44.61 KB

I noticed that the patch in #334 no longer applies to 9.1.x, so I've re-rolled it (and tried my best to fix the merge conflict). Since this is a re-roll, generating an interdiff is not useful (and somewhat difficult), so I'm not including one.

For your convenience, I re-rolled #334 on the latest 8.9.x and 9.0.x too, and I'm including them as .do-not-test.patches so Testbot doesn't get too angry.

OthmanEmad’s picture

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

Patch #351 for the 8.9.x version worked perfectly on 8.9.6.
Great work!

avpaderno’s picture

Version: 8.9.x-dev » 9.1.x-dev
mparker17’s picture

StatusFileSize
new1.48 KB
new45.05 KB
new45.02 KB
new45.02 KB

As @heddn noticed in #348 even newly-created views seem to be writing handler_settings and handler_submit keys to the config.

It shouldn't be writing handler_submit (we don't need to store the nojs submit button text as configuration!), and handler_settings should have a schema.

Here's an updated patch to fix those issues.

heddn’s picture

It seems to be like we need better test coverage then, if we have config schema errors that aren't getting caught.

playful’s picture

#354 is not working with Chosen, which works fine on entity reference select lists outside of Views exposed filters.

colan’s picture

#356: Please create a follow-up issue for that (unless there's one already) as this issue has dragged on long enough. We can't keep expanding the scope.

dww’s picture

Status: Needs review » Needs work

Thanks to everyone who worked on this so far! It's really coming along, and looks close to being ready. It's definitely going to be a big win for Views! Excited to try to help get this in.

First deep dive of the patch, and I found a bunch of mostly cosmetic issues with comments and code style.

Probably the biggest question of substance is if we want/need the list_max setting (and all the related complications) at all. Due to how it works, if you're over the limit, you already had to pay the RAM + query price. So while it saves you from an unwieldy UI and a huge select in the page output, it doesn't help you much on the back end. I'd be in favor of a the simple toggle between select + autocomplete. If a site builder uses 'select' and the list is too big, that's their problem, not ours. If so, we could remove a lot of complication and code in this patch.

Anyway, here's the full dreditor review...

  1. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * Validated exposed input that will be set as value in case.
    

    "in case" what? ;)

  2. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * The messenger service for setting messages.
    

    "for setting messages" isn't needed.

  3. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +  /**
    +   * {@inheritdoc}
    +   */
    +  public function __construct(
    

    If we could inherit the _construct() docs from our parent, we wouldn't need this function at all. ;) The parent only takes 3 args. So we need a real docblock here to document the additional params.

  4. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    

    Can we define the return type as void? Or not, since it doesn't have it in the parent?

  5. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * Get the used entity reference selection handler.
    

    a) Should start with 'Gets'

    b) "the used" is a little awkward.

    Maybe:
    "Gets the entity reference selection handler in use." ?

  6. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +      // entity type specific plugins (e.g. 'default:node', 'default:user',
    +      // ...).
    

    maybe just leave out the '...' here and end this comment on the 1st line?

  7. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +    // @todo When changing selection handler Ajax request doesn't get processed
    +    // correctly so need to add this hack.
    

    This is a little worrisome. ;) Is there a more elegant way to fix it? Can we open a follow-up to track this? It's not obvious what "doesn't get processed correctly" means, so it's not clear what this hack is working around, etc. If not a link to a follow-up issue, can we give this comment more detail?

    Also, in comments, AJAX should be all caps as an acronym.

  8. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +    // https://www.drupal.org/project/drupal/issues/2854166 landed.
    

    Reading #2854166: Add #group handling to Select form/render element, it looks like #2190333: Make #group FAPI / render feature work on all form/render #types out of the box is probably going to be the real solution here. Probably better to use 2190333 for this link.

  9. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +      '#attributes' => ['class' => ['entity_reference-settings']],
    

    Note to self: why do we need this?

  10. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +    // Remove ajax to load handler target bundles immediately.
    ...
    +   * Ajax callback for the handler settings form.
    

    In comments, s/ajax/AJAX/

  11. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * Render API callback.
    

    This isn't very helpful as a 1-line summary. I think I'd remove this entirely and use the 'Processes the ...' thing as the summary.

  12. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * Processes the field settings form and allows access to the form state.
    

    Not sure what 'and allows access to the form state.' is talking about. Looking at this function and what it calls, I don't see anything about form state at all...

  13. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * Process element callback.
    ...
    +   * Render API callback.
    ...
    +   * Process element callback.
    

    More of the same. I'd remove the generic summaries and use the more specific descriptions for each of these.

  14. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * Adds entity_reference specific properties to AJAX form elements from the
    +   * field settings form.
    

    That doesn't look like what this function really does. ;) More like 'Changes the parent of submit buttons on the field settings form because X...', right?

  15. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * Processes the extra options form and allows access to the form state.
    

    Again, what's "form state" have to do with it?

  16. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +        $options = $this->getValueOptions();
    +        if ($list_max <= 0 || count($options) <= $list_max) {
    +          $this->valueFormAddSelect($form, $form_state);
    +        }
    

    So if we have a huge # of options, we still have to query/load them all, only to count them and decide if that'd be too expensive and we want autocomplete, instead?

    Is all this list_max setting and functionality even worth the complication? Maybe we just have the widget setting and let site admins shoot themselves in the foot if they try using 'select' on something huge?

  17. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * ValueForm helper adding an autocomplete element to the form.
    

    'Adds an autocomplete...'

  18. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +  protected function valueFormAddAutocomplete(array &$form, FormStateInterface $form_state) {
    ...
    +  protected function valueFormAddSelect(array &$form, FormStateInterface $form_state) {
    

    Can declare : void return type.

  19. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +    $referenced_type = $this->getReferencedEntityType();
    ...
    +      '#title' => $this->t('Select %entity_types', ['%entity_types' => $referenced_type->getPluralLabel()]),
    ...
    +      '#target_type' => $this->getReferencedEntityType()->id(),
    

    Either we don't need the local var and we call getReferencedEntityType() twice, or we use the local var for both. The current mix is weird.

  20. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +      '#validate_reference' => FALSE,
    

    Maybe worth a comment here. Curious: why not validate the reference?

  21. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * ValueForm helper adding a select element to the form.
    

    s/ValueForm helper adding/Adds/

  22. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +        else {
    +          $copy = $default_value;
    +          $default_value = array_shift($copy);
    +        }
    

    Not required, but I'd love a comment about what's happening here.

  23. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +      '#size' => min(9, count($options)),
    

    Why do we force this min #size? Probably worth a comment.

  24. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +    $user_input = $form_state->getUserInput();
    +    if ($is_exposed && isset($identifier) && !isset($user_input[$identifier])) {
    +      $user_input[$identifier] = $default_value;
    +      $form_state->setUserInput($user_input);
    +    }
    

    Not obvious why this is needed at all. Can we rip it out? If not, can we add a comment about it?

  25. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * Value options callback.
    

    Maybe: "Returns the value options for a select widget." or something? 'Value options callback' doesn't follow standards and isn't very descriptive.

  26. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +  protected function valueValidate($form, FormStateInterface $form_state) {
    

    This doesn't appear to validate anything, and it used only to copy values from target_id into something else. Maybe worth a comment?

  27. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +      if ($values = $form_state->getValue(['options', 'value'])) {
    +        foreach ($values as $value) {
    +          $ids[] = $value['target_id'];
    +        }
    +      }
    

    You don't technically need the outer if(). If $values is an empty array, foreach() becomes a no-op and $ids remains empty.

  28. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +    $rc = parent::acceptExposedInput($input);
    +    if ($rc) {
    ...
    +    return $rc;
    

    Not sure what $rc stands for. "Return code"? Maybe $result would be more self-documenting?

  29. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +    // We only validate if they've chosen the select field style.
    

    Not clear why. Don't we want/need to validate autocomplete values, too? Does anything stop end users from putting bogus entity IDs in this filter?

  30. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +        $this->validatedExposedInput = (array) $form_state->getValue($identifier);
    

    getValue() isn't really validating anything, either. ;) I confess this function isn't making much sense (but I'm also sleep deprived, so maybe I'm just being dense).

  31. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +    // Prevent array_filter from messing up our arrays in parent submit.
    

    Huh? Is this saying we don't call the parent to avoid an array_filter()?

    Maybe add @see pointing to the parent valueSubmit() we're worried about?

    So this valueSubmit() is a total no-op? Isn't that a problem? ;)

    Also, it's convention to include () after function names in comments: array_filter()...

  32. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   * Gets the target entity type ID referenced by this field.
    

    It's not just the ID, it's the fully loaded EntityType object.

  33. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,765 @@
    +   *   Entity type.
    

    Sadly, our doc standards basically want us to duplicate the summary here. ;) But "Entity type" isn't much help on its own.

  34. +++ b/core/modules/views/views.views.inc
    @@ -811,6 +811,13 @@ function core_field_views_data(FieldStorageConfigInterface $field_storage) {
    +      // Render filters as select lists.
    

    A) Not necessarily 'select'. Maybe "Use the entity_reference filter for this field." or something...

    B) Looking at this hunk in context, it's weird that it's between the relationship and reverse relationship cases. Seems cleaner to either put it near the top of the loop (right after we test for instanceof ContentEntityTypeInterface), or at the very bottom.

    C) Given this change, we should consider updating the comment for the function to mention it's mucking with filters, not just relationships.

  35. +++ b/core/modules/views_ui/src/Form/Ajax/ConfigHandlerExtra.php
    @@ -95,6 +95,10 @@ public function buildForm(array $form, FormStateInterface $form_state) {
    +
    +    if ($form_state->getErrors()) {
    +      $form_state->set('rerender', TRUE);
    +    }
    

    Not clear why we need this. If we do, why didn't we need it before? ;) If we don't, what's it doing here? Seems this wants to be removed, or it wants a comment to justify itself.

Stopping here and saving review so far. I'll come back for reviewing the test coverage ASAP. I'll also try running it locally, and seeing 1st hand how it behaves.

Thanks again!
-Derek

dww’s picture

Component: entity_reference.module » views.module
  1. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    + * Test the entity reference filter UI.
    

    s/Test/Tests/

  2. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +   * Entity type and referenceable type.
    

    Can remove 'referenceable' from here -- that gets its own comment. I'd rather know what entity type we're talking about here. The "host" entity type that the view is of?

  3. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +   * @var \Drupal\node\NodeTypeInterface
    

    Kinda weird the type is hinted as NodeTypeInterface. If we're hard-coding node, why bother with the protected member at all?

  4. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +   * @var \Drupal\node\NodeTypeInterface
    

    Also here.

  5. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +   * Referenceable content.
    ...
    +  protected $nodes;
    ...
    +   * Content containing fields as reference.
    ...
    +  protected $containingNodes;
    

    All this terminology and the variable names are a little confusing. Maybe $hostNodes vs. $targetNodes would be more clear?

    Or parentNodes vs. referencedNodes or something?

  6. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +          // Note, this has no impact on Views at this time.
    

    That's interesting. ;) So why is it in this test?

  7. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +  public function testFilterUi() {
    

    Could declare return type : void

  8. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +    $found_all = TRUE;
    ...
    +      $found_all = $found_all && $label == $node->label() && $nid == $option['nid'];
    ...
    +    $this->assertTrue($found_all, 'All referenceable nodes were available as a select list properly ordered.');
    ...
    +    $found_all = TRUE;
    ...
    +      $found_all = $found_all && $label == $node->label() && $nid == $option['nid'];
    ...
    +    $this->assertTrue($found_all, 'All referenceable nodes were available as a select list properly ordered.');
    

    This is a bit weird. Seems better to directly assert the nids (like we do for the labels) and let PHPUnit blow up if we're missing something or we didn't find them in the right order...

  9. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +    $this->drupalPostForm('admin/structure/views/nojs/handler-extra/test_filter_entity_reference/default/filter/field_test_target_id', $edit, t('Apply'));
    ...
    +    $this->drupalPostForm('admin/structure/views/nojs/handler-extra/test_filter_entity_reference/default/filter/field_test_target_id', $edit, t('Apply'));
    ...
    +    $this->drupalPostForm('admin/structure/views/nojs/handler-extra/test_filter_entity_reference/default/filter/field_test_target_id', $edit, t('Apply'));
    

    A) See https://www.drupal.org/node/3168858 -- we don't want drupalPostForm() anymore.

    B) See #3133726: [meta] Remove usage of t() in tests not testing translation -- we don't want t() here.

  10. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +    foreach ($this->containingNodes + $this->nodes as $nid => $node) {
    

    This seems a bit fragile to depend on the ordering from adding these two arrays together...

  11. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +   *   Array of keyed arrays containing `nid` and `label` of each option.
    

    Maybe we should, but I don't remember us using ` for comments like this...

  12. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +  protected function getUiOptions() {
    

    Could declare return type : array

  13. +++ b/core/modules/views_ui/tests/src/Functional/FilterEntityReferenceWebTest.php
    @@ -0,0 +1,219 @@
    +        'label' => (string) $this->getSession()->getDriver()->getText($option->getXpath()),
    

    Why can't we call $option->getText()? This seems more complex than needed.

Cool. That's a start for test coverage of the views_ui parts of this patch. But there seem to be a lot of code paths (even in the admin UI parts) of EntityReference.php that we're not covering here. Additional test coverage we could use:

A) I wonder if we'd be better suited with a FunctionalJavascript test so we could actually see the AJAX stuff in action (since there are a fair bit of comments and code in the patch specifically for the AJAX cases within the admin UI itself).

B) This patch would be more RTBC-able if it also included a new test in core/modules/views/tests/src/Kernel/Handler to actually verify that the filter itself works for end users using a view.

C) For extra credit, we could also add something in core/modules/views/tests/src/FunctionalJavascript/Plugin/views/Handler to see the autocomplete exposed filter actually working, too.

Thanks again!
-Derek

p.s. Moving the component to Views, since the "Entity Reference" module as such is going away...

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.

nono95230’s picture

I add to this question the same patch, compatible with version 8.9.7 of the drupal core, and compatible with version 7.0 of PHP.

kapilv’s picture

Status: Needs work » Needs review
StatusFileSize
new36.35 KB
new53.92 KB

patch doesn't apply. hear a updated patch.

Status: Needs review » Needs work

The last submitted patch, 362: 2429699-362.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

anmolgoyal74’s picture

Status: Needs work » Needs review
StatusFileSize
new63.51 KB
new27.44 KB

Handled few points from #358.
Added Entityrefernce.php file.

scott_euser’s picture

Assigned: Unassigned » scott_euser

From what I can see #361, #362, and #364 are not moving the issue ahead, but are so that people can use the old patch on older versions of Drupal/PHP. I'm going to work on #358.

playful’s picture

I just noticed that #354 has broken some of my existing views filters causing a "The operator is invalid on filter" error. On Drupal 8.9.

scott_euser’s picture

Assigned: scott_euser » Unassigned
StatusFileSize
new40.48 KB
new28.76 KB
new58.87 KB

Okay here is an updated patch addressing comments from #358 and #359 (thanks very much for the detailed review and helping move this forward!). I can see that in #364 you have written 'Handled few points from #358.' so I put an interdiff, but I still based this on #351 as #364 re-introduces changes to the views wizard and taxonomytermtid classes and I believe we've already addressed that we need to keep this scope limited to have a realistic chance of getting it done. Would suggest any extending of EntityReference by TaxonomyTermTid and changes to the wizard be a follow-ups. Apologies if I've gotten this wrong!

I have gone with the suggestion of removing the list max option. Theoretically the same issue of memory can occur with any reference including taxonomy terms (existing) when switching from autocomplete to a full list. As @dww pointed out, we are anyways loading the entities to determine if the max has been hit (though I suppose we could load max+1 rather than all entities). In any case, it might be more suitable to have that in VERF or other contrib module to avoid slowing progress down on this issue.

Where the comment was clear, I've updated, but here are my notes on things that might be more contentious in the change:

Addressing review from #358 (functionality):

  • 4. Wasn't sure about this. If we do add void, I guess we cannot inheritdoc any more, but other than that fine?
  • 7. This no longer seems to be an issue as far as I can tell. I don't see the background on it well enough, but its discussed in #141. Everything appears to work correctly for me before and after save.
  • 9. I also can't see any use of this class; however, it appears in several other places in core.
  • 14. I've based this on the description in EntityReferenceItem::formProcessMergeParent
  • 20. I believe the validation is covered by validateExposed, I've attached a screenshot of a manual test here: I can see that invalid input in the autocomplete is still validated
  • 22. We similarly do this in /admin/reports/dblog for the DB Log filters (DblogFilterForm). I've set this to match that now. There the min() is not used, I assume to have the two filters match each other's height. Here if there are less options, we can make it smaller so the subsequent inputs are moved up.
  • 24. This appears to have been introduced into https://www.drupal.org/project/drupal/issues/2318087 for TaxonomyIndexTid. This class has some level of duplication. There appears to be some discussion as to whether to add it, but the discussion doesn't see to cover the 'why'.
  • 27. Isn't it possible for this not to return an array, and if so, won't we get `Invalid argument supplied for foreach()`
  • 29. I didn't quite get this comment (the original from the code) Target_ids from the Entity Reference Autocomplete are in fact added to validatedExposedInput slightly further on in this method. The validation is definitely happening as validation messages are being shown. This matches how the the Drupal\user\Plugin\views\filter\Name class is handling an autocomplete in validateExposed. I have updated the comment here.
  • 30. Validation is actually happening, I'm just not 100% sure where. If I change a select value in devtools and try to save, I correctly get the 'An illegal choice has been detected. Please contact the site administrator.' validation message.
  • 31. This actually comes from TaxonomyIndexTid as well as duplicate code. I appreciate that being in core already doesn't excuse the comment, so I have tried to make it better here at least.
  • 35. I don't think we need it. If this is handling the no-JS case like the comment says, isn't a rerender implied? I tested by disabling javascript and playing with the various settings, switching between autocomplete and select and then updating the preview without issue. This was likely related to the list_max.

Addressing review from #359 (tests):

  • 5. I've renamed all to the suggested target/host entities and entity types and tried to make the comments more readable and useful.
  • 6. I think the idea here was that if there is only 1 bundle, selecting nothing or selecting the bundle won't make a difference. That said, we have page and article, so this does feel necessary. I've removed the comment.
  • 10. Would you suggest not caring about the order in this case and just checking the options exist?
  • Additional tests ABC: Needs further work
scott_euser’s picture

Fixes for coding standards warnings, otherwise no change from #367.

scott_euser’s picture

Updated patch now including a Kernal test.

Next steps I believe if someone else would like to continue:

  1. Expand on the Kernal tests if needed
  2. Convert Functional test to FunctionalJavascript test to also test ajax as per #359
  3. Add FunctionalJavascript to test autocomplete handler of this EntityReference plugin as well as per #359
aaronmchale’s picture

Queued #369 for testing against 9.2.x.

klaasvw’s picture

First of all, thanks everyone involved for pushing this forward! This is a much needed feature that is frequently requested, so having this in core would be great.

As already mentioned in #321, entity_reference base fields are not supported here. As #322 explained this is mainly a higher order issue, but until that issue is fixed we can still make sure base fields can also use this filter. Note that this is already the case for other views integrations, e.g. in core/modules/views/src/Plugin/views/field/EntityField.php:167, where $this->definition['entity field'] is converted to $this->definition['field_name'], so base field definitions are also supported as views fields.

Updated the patch from #369 with support for base field definitions and also included a 9.0.x backport for those who need it.

The last submitted patch, 371: drupal-views-entity-reference-filter-2429699-371.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

avpaderno’s picture

Status: Needs review » Needs work

(I wonder why the status is not automatically changed when a patch fails to apply or tests fail, as it usually happens.)

dww’s picture

Thanks for all the effort here since #359!

@all: I signed this issue up for forks, and created an initial branch here:

https://git.drupalcode.org/issue/drupal-2429699/-/tree/2429699-add-views...

We could keep the mainline effort in this issue in that branch, but create other branches for the backport patches. Ideally that will keep everything more clear, and make it easier to share our work. It's the way the future is going for core contribution, and we can now try it here and provide feedback on how it works if we run into anything. Sound good?

Would @scott_euser be willing to populate the above branch (and maybe put #371 as an additional commit)?

Would @Nono95230 and others working on the 8.9.x backport be willing to create a new branch, then populate it?

I'll look more closely at the new patches in the meanwhile.

Thanks!
-Derek

scott_euser’s picture

Status: Needs work » Needs review

Thanks for setting that up @dww! I done the following:

  1. Set initial commit to #369
  2. Added the patch from klaasvw in #371
  3. Fixed a coding standards issue in FieldEntityReferenceTest
  4. Fixed the test failures in #371 to have the tests assert that the filter is entity_reference rather than numeric
webiator gmbh’s picture

Works like a charm

dww’s picture

Status: Needs review » Needs work

@scott_euser Thanks for all the Git shenanigans!

I still haven't been able to carefully review all the code in here. But a $day_job project required me to investigate trying to use this for something. I ran into some fairly catastrophic problems. ;) Fearing it was weirdness from the test site, I tried with a clean copy of core, and ran into the same things:

A) On a site with a lot of content, if you just apply the patch and try to use it in a view, the site completely hangs. Before you can successfully configure the filter, the fallback behavior in getValueOptionsCallback() ends up trying to load all the entities on the site (or something), the DB connection times out, and all is dead. I had to add an early return []; to that method to be able to configure the view at all. Once I actually configured the 'extra settings' (see below), I could remove the early return and then the filter started working.

B) The AJAX behavior for the "extra settings" form is broken. If you change the "Reference method", there's a little AJAX spinner, but the form doesn't rebuild to use your new thing. So, e.g. if it starts on 'default', you try to change it to 'view', you can't select which view to use. You have to select 'view', pick something arbitrary from the content type checkboxes, save, click "Settings" again, *then* the new modal will let you select which ER view to use. Then you can save. Then your filter actually works.

C) I'm not totally clear why these are even settings. ;) I know the answer is "because someone will need that flexibility some day", but naive me asks: "why not just use all the same selection handler settings from the field configuration?" I can't initially fathom why a site builder would want the view filter to give you different options than the field itself supports.

I'm out of steam for the week, but I'll probably dive back in on Monday to try to more carefully understand where this is going wrong and hopefully upload some new code that resolves these problems.

Thanks!
-Derek

scott_euser’s picture

Hi @dww,

Sorry for the slow reply on this! I have had a look and I think we have a fundamental issue that has occurred somewhere in the back and forth. The default for an entity reference field is Drupal\views\Plugin\views\filter\NumericFilter. This has different options then both the Autocomplete widget and the Select widget offered by the new Drupal\views\Plugin\views\filter\EntityReference filter. I don't think an update hook is going to cut it as the Autocomplete default from EntityReference doesn't offer an equivalent scenario as NumericFilter has more operators. This seems to be an issue going many patch versions back (spot checked a few).

To reproduce:

  1. No patch
  2. Create node type with entity reference to another node type
  3. Create view to list content
  4. Add filter for entity reference

This results in this long list of operators that make perfect sense for a numeric field (less sense for an entity autocomplete, but doesn't stop it from having been possible, and therefore I believe we need to maintain compatibility):

If I understand how it works correctly, the change in core_field_views_data() changes the filter being used to our new EntityReference. I think what would make this simplest is allowing initial widget selection of:

  1. Numeric (default)
  2. Autocomplete
  3. Select list

Ie, adding back in Numeric.

If you do think that's the right approach, what I'm not sure of is how to avoid adding a significant amount of code to bring numeric in as an option. Any suggestions?

A) On a site with a lot of content, if you just apply the patch and try to use it in a view, the site completely hangs. Before you can successfully configure the filter, the fallback behavior in getValueOptionsCallback() ends up trying to load all the entities on the site (or something), the DB connection times out, and all is dead. I had to add an early return []; to that method to be able to configure the view at all. Once I actually configured the 'extra settings' (see below), I could remove the early return and then the filter started working.

I think this is why other contributors added in the default maximum. I suppose the exact same could happen on a large site with tens of thousands of Terms as the TaxonomyIndexTid views filter also loads all entities, its just that that is far less likely to occur. Maybe we need to bring back the maximum with the assumption that its much more likely to be a problem with Nodes/other entities than it has been with Taxonomy Terms?

B) The AJAX behavior for the "extra settings" form is broken. If you change the "Reference method", there's a little AJAX spinner, but the form doesn't rebuild to use your new thing. So, e.g. if it starts on 'default', you try to change it to 'view', you can't select which view to use. You have to select 'view', pick something arbitrary from the content type checkboxes, save, click "Settings" again, *then* the new modal will let you select which ER view to use. Then you can save. Then your filter actually works.

I'm guessing this is related to the above with the NumericFilter, so I think let's start with deciding how to solve that. Feel free to disagree, I haven't investigated this to see how/when it occurs.

C) I'm not totally clear why these are even settings. ;) I know the answer is "because someone will need that flexibility some day", but naive me asks: "why not just use all the same selection handler settings from the field configuration?" I can't initially fathom why a site builder would want the view filter to give you different options than the field itself supports.

Well imagine you have 2 different Node Types using the same Entity Reference field. The content types they allow selection of can differ I believe.

In any case, definitely a fair bit more work to go. Thanks for testing this out and helping move it forward!
Scott

en-cc-org’s picture

Huge thanks to all who developed, this filled a critical need for us. Patch #351 on 8.9.10 is working well.

NOTE: Even if 'expose this filter to visitors' was not selected, the patch modified all filters based on entity references. I'm not sure why you would need a drop-down or autocomplete for a non-exposed filter - was this expected?

Two of our views broke, due to the problem described in #379. We had a (non-exposed) field_district "is equal to" a specific node id, but with the removal of those numeric operators the filter became invalid. I was able to fix by filtering on ID (using a relationship) instead so all is well.

Other (non-exposed) entity reference filters did not break, but now had the new, unconfigured extra "settings". I selected the appropriate content type and left the default 'autocomplete', hoping to mitigate any performance impacts (we have a large site with many complex views). Just seems like extra overhead for a non-exposed use case.

Thanks again.

Anonymous’s picture

FYI, for those who arrived here from a Google search looking for help on select fields on exposed filter for an entity reference field, this module could be an alternative while this issue is being resolved:
https://www.drupal.org/project/entityreference_filter

Entity Reference Filter was particularly helpful in the use case I'm currently working on, as the entity reference field uses an entity reference view. This helps them neatly tie together.

(Yes, I know that this comment doesn't relate to the proposed solution. I'm putting this here for those who can't wait on this issue or who are using an entity reference field that's linked to an entity reference view.)

czigor’s picture

StatusFileSize
new48.76 KB

Reroll of #376 for 9.2.x.

czigor’s picture

Status: Needs work » Needs review
heddn’s picture

Latest patch doesn't apply to 9.1.3. It does apply. Just temporary issues with gitlab.

a.dmitriiev’s picture

StatusFileSize
new53.55 KB

I tried to make a patch for 8.9.x out from Merge request #18.

heddn’s picture

Status: Needs review » Needs work
Issue tags: +Needs reroll

The MR branch doesn't apply on 9.1.4. Also doesn't seem to apply on 9.2.x.

sokru’s picture

Status: Needs work » Needs review
Issue tags: -Needs reroll
StatusFileSize
new48.91 KB
new2.6 KB

Reroll from MR18's latest commit 0b5b8313. Interdiff done with diff command.

avpaderno’s picture

Status: Needs review » Needs work
sokru’s picture

Status: Needs work » Needs review
StatusFileSize
new48.91 KB
new542 bytes
scott_euser’s picture

Sorry forgot to update after commits yesterday. MR now contains the typo fix and reroll fix.

Still there are some issues to address however. If @dww or someone else is able to further review. I've added some comments in #379 that I think need discussion in order to take next steps in further updating the MR. Getting there!

yepa’s picture

StatusFileSize
new41.73 KB

We've a view based on a custom content entity with taxonomy field reference.
I've applied the patch #389 on a Drupal 9.1.4.

And it works fine ! Thanks folks.

taxonomy filter on a view based on a custom entity

luksak’s picture

StatusFileSize
new0 bytes

Here is a re-roll against 8.9.x.

luksak’s picture

StatusFileSize
new53.62 KB

Sorry, made a mistake while creating the patch.

luksak’s picture

It turned out that I had an issue on my now computer. The patch in #385 applies perfectly! Sorry for the noise!

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

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

rho_’s picture

I have a custom content entity that has a term reference created with BaseFieldDefinition on a 8.9.x install.

Can confirm patch #385 applies cleanly and works as expected.

mr.york’s picture

StatusFileSize
new49.53 KB
new974 bytes

Reroll last patch and little performance fix.

mr.york’s picture

StatusFileSize
new49.44 KB

Reroll patch.

mr.york’s picture

StatusFileSize
new52.91 KB
new974 bytes

Add performance fix.

mr.york’s picture

StatusFileSize
new49.62 KB

Fixed last patch. (Sorry, this is not my day :) )

mr.york’s picture

StatusFileSize
new56.15 KB
new49.71 KB

Fixed TaxonomyRelationshipTest reroll.

avpaderno’s picture

Status: Needs review » Needs work
scott_euser’s picture

Status: Needs work » Needs review

Is the latest work against 9.3.x still what is in the merge request? Its hard to tell if the patches are for backporting only or if the intention is for that to be the new 'head'.

If latest is still what's in the merge request then its still needs review, with #379 questions pending to move this forward I believe. I'll set it back to that for now, but sorry if I got it wrong! (and if so, should we then apply a diff to get the latest work back into the merge request so we don't end up having two diverging sets of work).

Is there a better way to manage this? Eg, a separate issue to handle backporting to keep this issue focused?

kapilv’s picture

StatusFileSize
new49.71 KB
new542 bytes

fixed Custom Commands Failed.

avpaderno’s picture

Status: Needs review » Needs work
scott_euser’s picture

Status: Needs work » Needs review

As per #403 unless someone explains otherwise, setting back to needs review as the merge request still merges and passes tests fine. Patches seem to be for back-porting with the exception of #404 which is unclear what the interdiff is between.

pyrello’s picture

At the top of this issue, there is a checkbox that seems to indicate that it handles configuration entities. However, doing a search through the thread, I see scant discussion of this aspect of the functionality. Also, in looking at the code changes, it seems like this is more focused on content entities. Also, in testing it against an entity reference field to a custom-defined configuration entity, I am not seeing any of the additional options show up that seem to be indicated.

Am I missing something?

kim.pepper’s picture

Issue tags: +#pnx-sprint
jacobbell84’s picture

StatusFileSize
new49.69 KB

The re-roll for 9.1 in comment 401 didn't apply and included some of the orig/rej files. I rolled a new one for anyone that needs it.

pyrello’s picture

#409 did not apply for me against 9.19

jacobbell84’s picture

@pyrello, this was a reroll for the 9.1.10 release. If you're on 9.1.9 you can use the patch from comment #389. Even though it says 9.2.x, it works fine for 9.1.9, we had been using it for a while.

pyrello’s picture

@jacobbell84 Ah! Thanks for the clarification. I misunderstood.

willpeps’s picture

StatusFileSize
new49.69 KB

Updating #409 as patch version is different to my version (9.1.5) due to assertEquals being assertEqual

Here is what is in my version of TaxonomyRelationshipTest.php

$this->assertEqual(t('Parent'), $views_data['parent_target_id']['relationship']['label']);                                                                                                                                            $this->assertEqual('standard', $views_data['parent_target_id']['relationship']['id']);                                                                                                                                                // Check the parent filter and argument data.                                                                                                                                                                                         $this->assertEqual('numeric', $views_data['parent_target_id']['filter']['id']);                                                                                                                                                       $this->assertEqual('taxonomy', $views_data['parent_target_id']['argument']['id']);

// Check an actual test view.    

Whereas the patch in 409 is expecting a different set of lines, which can be seen here:

--- a/core/modules/taxonomy/tests/src/Functional/Views/TaxonomyRelationshipTest.php
+++ b/core/modules/taxonomy/tests/src/Functional/Views/TaxonomyRelationshipTest.php
@@ -82,7 +82,7 @@ class TaxonomyRelationshipTest extends TaxonomyTestBase {
     $this->assertEquals(t('Parent'), $views_data['parent_target_id']['relationship']['label']);
     $this->assertEquals('standard', $views_data['parent_target_id']['relationship']['id']);
     // Check the parent filter and argument data.
-    $this->assertEquals('numeric', $views_data['parent_target_id']['filter']['id']);
+    $this->assertEquals('entity_reference', $views_data['parent_target_id']['filter']['id']);
     $this->assertEquals('taxonomy', $views_data['parent_target_id']['argument']['id']);
 
     // Check an actual test view.
klaasvw’s picture

StatusFileSize
new49.71 KB

Another update of #409, taking into account that assertEquals is also used in the original code since 9.1.10.

sershevchyk’s picture

Patch 413 works fine for me on Drupal 9.1.5. Thanks

colan’s picture

#414 seems to work on 9.2.0 and our Behat tests are passing, but it seems like the MR is out-of-date.

Maybe:

  1. Update the MR to target 9.3.x, not 9.2.x. (I don't seem to have permission to do this.)
  2. Merge 9.3.x (using a `theirs` strategy), and then
  3. Add anything back from the patch that's missing?

I hid a bunch of old patches.

isa.bel’s picture

We have a user role field on a view, after applying this patch it worked like a charm!
Thanks all!

nixou’s picture

In #295 this feature was removed for taxonomy term reference fields.

As I need it for a project I'm upgrading to Drupal 9.2, I reintroduced the feature in the attached patch.

If you do not want to keep the feature for taxonomy term reference fields, just ignore this patch.

catch’s picture

Status: Needs work » Needs review
StatusFileSize
new49.71 KB

Posting an identical patch to #414 except with the typo that cspell doesn't like fixed. Haven't reviewed yet.

catch’s picture

StatusFileSize
new50.08 KB

And a re-roll so it applies to 9.3.x

nickdickinsonwilde’s picture

StatusFileSize
new49.96 KB

reroll to remove some unicode conversion mess(?) (next/previous strings)

Status: Needs review » Needs work

The last submitted patch, 421: 2429699-421.patch, failed testing. View results

bramdriesen’s picture

The patch also needs a re-roll.

ankithashetty’s picture

Status: Needs work » Needs review
StatusFileSize
new50 KB
new3.08 KB

Patch in #421 needed reroll after #3116481: Convert EntityViewsDataTest from a unit test to a kernel test got in. Also changed Drupal\Tests\views\Kernel\Handler\FieldEntityReferenceTest::$modules property to protected.

Thanks!

Status: Needs review » Needs work

The last submitted patch, 424: 2429699-424.patch, failed testing. View results

yogeshmpawar’s picture

Assigned: Unassigned » yogeshmpawar

Working on it.

yogeshmpawar’s picture

Assigned: yogeshmpawar » Unassigned
Status: Needs work » Needs review
StatusFileSize
new54.79 KB
new1.9 KB

Hope this will fix test failure & changed $entity->label(); method to $entity->getLabel();

Status: Needs review » Needs work

The last submitted patch, 427: 2429699-427.patch, failed testing. View results

yogeshmpawar’s picture

Status: Needs work » Needs review
StatusFileSize
new54.79 KB
new1.36 KB

Reverting changes made to $entity->label();.

marcushenningsen’s picture

Subscribe +

volker23’s picture

None of the recent patches applies to 9.2.7 in my case. Neither #429, #424 nor #389 does. Do i need something else?

Thx!

bramdriesen’s picture

@Volker23 That makes sense because the patch is targeted on the DEV branch and not any of the stable releases (tags)

volker23’s picture

@BramDriesen, i see now, thanks. I was successfully using the patch #351 on a production 8.9.16 and was trying to get this up to Drupal 9. Now i need to find a solution for the taxonomy filters we're using there...

bramdriesen’s picture

You can always re-roll the patch on a different branch/tag, fix the "conflicts" and create a patch with the result after you resolved the conflicts.

ldavidsp’s picture

StatusFileSize
new2.96 KB
ldavidsp’s picture

StatusFileSize
new2.96 KB

The last submitted patch, 435: 2429699-435.patch, failed testing. View results

Status: Needs review » Needs work

The last submitted patch, 436: 2429699-436.patch, failed testing. View results

ldavidsp’s picture

StatusFileSize
new48.91 KB

Patch apply for Drupal 9.2.7

ldavidsp’s picture

@Volker23 try patch 439.

bramdriesen’s picture

Status: Needs work » Needs review

Back to needs review for the patch in #429

volker23’s picture

Thanks a lot @ldavidsp! patch #439 works like a charm.

(I think I need to learn how to reroll a patch, when comparing #439 with #429, basically some tests seem to have removed and line numbers differ. I have no idea how to accomplish something like this...)

chucksimply’s picture

For Drupal 9.2.8...

- Patch #439 would not apply
- Patch #436 applied but didn't work (broken handlers all over)
- Patch #429 applied and worked as desired. Thanks!

ruslan piskarov’s picture

Confirming.
For Drupal 9.2.8 only patch #429 can be applied.

avpaderno’s picture

Version: 9.3.x-dev » 9.4.x-dev
catch’s picture

StatusFileSize
new54.79 KB

#429 applies to 9.3.x and 9.4.x, it's not clear what the purpose of #435 onwards was. Re-uploading #429 as a new patch so that DrupalCI can see it. It's very hard to keep track of this issue with 400+ comments, so please only upload new versions of the patch when absolutely necessary, and explain what the difference is (re-roll, or with an interdiff) when doing so.

dat deaf drupaler’s picture

Patch #446 applied cleanly on drupal/core 9.2.8 (disclaimer - incompatible with drupal/core-recommended if used in your composer.json).. look forward getting this merged into core.

Thank you everybody for working on bringing this amazing feature into the core! ***waving hands***

maximpodorov’s picture

Does this patch really support fields which reference configuration entities?

berdir’s picture

No, that's impossible, content and config entities can't be joined in a relationship, config entities are not stored in a way that allows an SQL JOIN to work.

maximpodorov’s picture

But we don't need joins for filters.
And what does this line mean in the task description?
☑ support for configuration entity reference

chucksimply’s picture

So we've switched the ER filter's Value textfield widget to Autocomplete or Select. This is obviously ideal, especially for exposed filters.

But what about use cases where the Value textfield widget is still preferred (especially managing values for non-exposed filters). Would it not be smart to keep the textfield as an option? Maybe as a radio option under the initial "Selection Type" setting?

micnap’s picture

StatusFileSize
new14.28 KB

Interdiff between 439 and 446 for quick reference.

seanb’s picture

StatusFileSize
new49.1 KB

The reroll in #446 didn't apply to 9.3.x. Here is a new one.

ahaomar’s picture

@seanB patch #453 only works fine with new views from scratch but not working for existing views. When going to change existing views it gave error
The operator is invalid on filter: Content: Users. also when going to delete that field so can add later we cant delete the filter too it show new error
An illegal choice has been detected. Please contact the site administrator

Could you and any advice how to fix that please?

scott_euser’s picture

The comments in #451 and #454 I think reinforce that to get this over the line perhaps instead of changing the default, we add these as new options and maintain the existing option as is.

We could optionally of course set a new default to the autocomplete for newly created filters.

It would make it far simpler to get this functionality over the line.

I've described this more in #379. If someone could confirm that this makes sense as an approach I am very happy to do the work on it and get it there. Then hopefully with a final community review, it should be in a reviewable state for a maintainer to consider merging. Feel free to slack me in drupal slack if you want to discuss approach.

ahaomar’s picture

Thanks @scott_euser, just one thing does this patch 2429699-453-9.3.x.patch have ever test with "drupal/core-dev" is that working with that?

kepesv’s picture

Great, 2429699-453-9.3.x.patch worked for me.

jonathanshaw’s picture

I agree with you @scott_euser about #379, keeping NumericFilter for existing views. I would have select or autocomplete as the default for new views. I wonder if this might be the most back-compatible option even without the settings mismatch.

chucksimply’s picture

Wait, so is 2429699-453-9.3.x.patch breaking existing views in core 9.3. I need to upgrade from 9.2 to 9.3, but need this patch functional. Any further notes?

m.stenta’s picture

@ChuckSimply we are using 2429699-453-9.3.x.patch with core 9.3.3 in the farmOS distro: https://github.com/farmOS/farmOS/blob/e834a8c84e77a99407097b68325cc1dcc2... - automatic builds are working: https://github.com/farmOS/farmOS/runs/4879054942?check_suite_focus=true#...

Edit: I may have misunderstood your question. Thought you were asking if the patch works (it does) - but I can't speak to existing Views that might be affected by this patch.

chucksimply’s picture

Thanks @m.stenta. Yeah I am wondering if existing views are negatively affected by the latest patch.

chucksimply’s picture

@scott_euser - Regarding your comment #455, for what my opinion is worth... YES! I agree that adding autocomplete and select as options instead of replacing the default seems to be the best solution for integration in most uses, both past and going forward.

musa.thomas’s picture

hello I test the 2429699-453-9.3.x.patch, set the field, set the view, add exposed filter. On form entity I havn't got any exposed filter did i miss something ? I'm on drupal 9.3 with better exposed filter (set on basic for this view) idk if it change something.

ericdsd’s picture

Patch #453 works fine over core 9.3.5

ironsizide’s picture

Confirming patch #453 working well in core 9.3.5 for me.

rcodina’s picture

Patch on #453 works but I agree with @scott_euser on #455 because I experience the same problem described on #454 on existing views. Having to manually redo all affected views from scratch it's not an option.

alvarito75’s picture

Confirming patch #453 working well in core 9.3.7 for me after upgrading from Drupal 8.9 and applying this patch.

smustgrave’s picture

Status: Needs review » Reviewed & tested by the community

Worked for me

jonathanshaw’s picture

Status: Reviewed & tested by the community » Needs work

We are NW for #455

scott_euser’s picture

Thanks for the feedback, at Drupal Dev Days I managed to have a sit-down about this with @lendude (thanks again!) and he also agreed avoiding the BC is likely the only realistic way of this getting in, so exposing this as an alternative rather than a requirement. Similar to the approach of having 'Grid' and 'GridResponsive' where we provide both options to avoid the breaking change.

Attached patch exposes the new reference option, leaving Numeric as the default:

Screenshot of the new additional views data available to make use of the entity_reference filter plugin

This does mean if you already use the patch and want to upgrade use the code in the attached update-hook-2429699-comment-470-onwards-add-to-your-own-module.txt or your filters will be back to using the numeric filter.. Add it to your own custom module (not Views from core otherwise you will miss out on the next hook update and likely end up with a broken site).

scott_euser’s picture

Ah missed changing Taxonomy Reference test back to expecting numeric as the default - that test will fail. Updated patch.

Status: Needs review » Needs work
scott_euser’s picture

Status: Needs work » Needs review
StatusFileSize
new47.1 KB
new565 bytes

One more bit I missed reverting in the existing tests.

Status: Needs review » Needs work
scott_euser’s picture

Status: Needs work » Needs review

What are the chances of randomString() actually being a key on config. Anyways reran without change and the randomString() was no longer an existing key. Tests passing on 9.4 and 10.0

scott_euser’s picture

Updates/code cleanup:

  • Removing constructor code that appears to now do nothing
  • Remove condition check for unsetValue since the isset check happens there already
  • Adding specific relative created times to Nodes in the tests since the View is sorted by created date to prevent test failures if the created time ends up being exactly the same second.
lendude’s picture

Status: Needs review » Needs work

Just looked through this, and it feels like the right approach to take the whole upgrade thing out of it. Any simplification will make this easier to land.

But, just by scanning through this, this still lacks a great amount of test coverage.

I've just picked some samples of test coverage we need, some of these might actually have some coverage and there is still plenty of logic in here that I skipped, so it needs more tests than those I picked out here. Also added some other things that I happened across.

  1. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +  public static function extraOptionsAjaxProcess(array $form, FormStateInterface $form_state): array {
    ...
    +  public static function extraOptionsAjaxProcessElement(array &$element, array $main_form, FormStateInterface $form_state) {
    

    Since there is no FunctionalJavascript test, none of the AJAX stuff here seems to have test coverage. And this seems like the most fragile part currently with some workarounds and forcing it to play nice in the Views UI, so it really needs good coverage.

  2. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +  protected function valueForm(&$form, FormStateInterface $form_state) {
    

    lots of if's and switches, this all needs test coverage

  3. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +  protected function valueFormAddSelect(array &$form, FormStateInterface $form_state): void {
    ...
    +    if ($is_exposed) {
    ...
    +      if (!empty($this->options['expose']['reduce'])) {
    ...
    +        if (!empty($this->options['expose']['multiple']) && empty($this->options['expose']['required'])) {
    ...
    +      if (empty($this->options['expose']['multiple'])) {
    +        if (empty($this->options['expose']['required']) && (empty($default_value) || !empty($this->options['expose']['reduce']))) {
    ...
    +        elseif (empty($default_value)) {
    ...
    +        elseif ($default_value == ['']) {
    ...
    +        else {
    

    That's a lot of if's, do we have test coverage for all these cases?

  4. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +        // Due to https://www.drupal.org/node/1464174 there is a chance that
    

    This is currently a D7 views bug, is this really relevant here?

  5. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +    switch ($this->options['widget']) {
    +      case self::WIDGET_SELECT:
    +        $entities = $selection_handler->getReferenceableEntities(NULL, 'CONTAINS');
    +        break;
    +
    +      case self::WIDGET_AUTOCOMPLETE:
    +        $entities = [];
    +        break;
    +    }
    

    do we really need a switch for this?

    $entities = [];
    if ($this->options['widget'] === self:WIDGET_SELECT) {
      $entities = ....
    }
    
  6. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +      // Set value from the autocomplete reference to match the select list
    +      // widget to ensure the two widgets can be interchangeable.
    +      $ids = [];
    +      if ($values = $form_state->getValue(['options', 'value'])) {
    +        foreach ($form_state->getValue(['options', 'value']) as $value) {
    +          $ids[] = $value['target_id'];
    +        }
    +      }
    

    Are we testing this, are the two widgets interchangeable?

  7. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +    // If view is an attachment and is inheriting exposed filters, then assume
    +    // exposed input has already been validated.
    +    if (!empty($this->view->is_attachment) && $this->view->display_handler->usesExposed()) {
    +      $this->validatedExposedInput = (array) $this->view->exposed_raw_input[$this->options['expose']['identifier']];
    +    }
    

    Do we have test coverage for this scenario?

  8. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +    // If we're checking for EMPTY or NOT, we don't need any input, and we can
    +    // say that our input conditions are met by just having the right operator.
    +    if ($this->operator == 'empty' || $this->operator == 'not empty') {
    +      return TRUE;
    +    }
    ...
    +    // If it's non-required and there's no value don't bother filtering.
    +    if (!$this->options['expose']['required'] && empty($this->validatedExposedInput)) {
    +      return FALSE;
    +    }
    

    Do we have test coverage for these scenarios?

  9. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +  public function validateExposed(&$form, FormStateInterface $form_state) {
    

    Logic in here needs test coverage.

  10. +++ b/core/modules/views/src/Plugin/views/filter/EntityReference.php
    @@ -0,0 +1,728 @@
    +  public function calculateDependencies(): array {
    

    Logic in here needs test coverage.

scott_euser’s picture

Assigned: Unassigned » scott_euser

Thank you so much for the quick review! I'll work on test coverage today, so assigning to myself.

bramdriesen’s picture

Issue tags: +ddd2022

Great work Scott ;-)

acbramley’s picture

I may be missing something but testing #476 on a client site I can't see this working for config entity reference fields despite the IS saying it does.

Looking into the code core_field_views_data is still checking if ($target_entity_type instanceof ContentEntityTypeInterface) {

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

pebosi’s picture

I found this patch today, used it on 9.3.15 and its working for my content entities, except for the custom views handler. Thanks so much!

akalam’s picture

I have updated the patch on #476 to add support to "Content revision: Author" base field.

avpaderno’s picture

Assigned: scott_euser » Unassigned
Status: Needs work » Needs review
la558’s picture

Hello,
Thank you all for working on this.
I have to be doing something wrong or have to be missing a step, I don't see any difference after installing the patch.
> downloaded the patch: drupal-views-entity-reference-filter-2429699-483.patch
> added it to the 'patches' folder
> added its corresponding entry to the composer.json file
> run 'composer install' to success (I can see the additions to the /core/modules/node/src/NodeViewsData.php file)

I followed the above instructions:
1. created a new content type
2. added an entity reference to this content type
3. created a new view
4. added the entity reference field to the view
5. added the entity reference field to the filter
Result: nothing special, it looks the same as before installing the patch; I don't see the options, I don't see the " | settings" next to the filter, etc

What do you think I might be completely missing?

Many Thanks in advance!

scott_euser’s picture

Okay finally managed to get some time to work on this. To recap, after discussion with @lendude goal is to simplify as much as possible and remove need for upgrade path being a significant part of that simplification (handled in #476).

Views Selection Handlers now working
For #476 and earlier, switching views handler doesn't actually work because of sub-sub-forms (ie, views selection handlers are subforms of config handler extra, which is a subform of views). Sitting with @wim-leers trying to work this out one suggestion he had was to look into using states instead of ajax, to simplify that. This patch covers that; all selection handlers are now shown using states instead, making far less ajax.

Added functional javascript tests
However, there is still ajax happening using the wizard, so as @lendude suggested in #477, we need more test coverage. I have refactored the existing patch tests to share a trait for creating the test contents and added in a functional javascript test.

This still needs further tests to ensure everything noted in #477 is also covered. The tests now focus on the configuration, but we need to also test visitor usage of the exposed filters for instance.

Conditionally required fields within selection hanlders
In all prior patches and still in this one, required fields from the default selection handler (ie, you must select at least one Content Type) do not get validated as required or not. ConfigHandlerExtra does not support showing validation messages it seems - looking through plugins in core implementing it, none seem to actually have any need for that. Prior to switching to states, the browser validation would at least handle some cases; however, with this method, the browser validation fails given required fields would not be focusable, and again conditionally required via #states is also not supported via ConfigHandlerExtra. I would suggest those can be follow-up issues rather than blockers for this, given it means that failing validation means the selection handler is then not set, so no harm is done. You can see the two TODOs where I marked these attempts to use setErrorByName() and required via #states in case you want to try them.

Content revision: Author
Sorry @akalam (#483), I have left your change out, I think it further adds to the scope and perhaps is better placed as a follow-up if others feel its useful, otherwise as part of contrib. This seems to be already listed in follow-ups in the issue summary ("conversion of the "authored by" filter to use the entity reference filter")

ConfigEntityInterface
Similarly maybe that can be a follow-up as well @acbramley (#480). From my conversations with @lendude on this, the smaller the scope, the more likely this has a fighting chance of becoming a reality. I will cross it off from the issue summary as well for now.

Next steps
So some things need some further discussion but hopefully a step in the right direction for something that actually has a chance of getting committed. Looking forward to feedback.

Further tests still needed as noted above.

Patch not merge request
Finally, to note I have opted to keep this as a patch rather than MR, as each time I've updated the MR, others work from older patches and subsequent changes in the MRs have been discarded. So while we still have a hybrid situation with MRs and patches in this thread, will stick to the patch route.

scott_euser’s picture

Attached should fix coding standards issue to allow tests that are in place to run

scott_euser’s picture

Updated form nesting to prevent double nesting of fieldsets for selection handler subforms within the options extra subform.

Status: Needs review » Needs work
scott_euser’s picture

Status: Needs work » Needs review
StatusFileSize
new160.81 KB
new66.22 KB
new1.85 KB

Hmmm not sure why the test is failing. Passing locally. Another attempt, otherwise would appreciate if someone else can test running it - I am not very confident with the ajax request testing, with handler saving, and preview auto-updating my guess is local order of the two ajax requests is different than via the test runner.

Screenshot of console output from test successfully running within ddev

scott_euser’s picture

Issue with validation not being applied is already an active issue it seems: https://www.drupal.org/project/drupal/issues/3163740 (ie, "Conditionally required fields within selection handlers" from #486

smustgrave’s picture

following the steps in the issue summary.

I verified that a filter for an entity reference field is appearing.
Verified it works as a select list and autocomplete
Verified its actually filtering as well.

RTBC+1

I'd move it but appears the 9.5 branch isn't building so would want to see the test cases

Status: Needs review » Needs work
jksloan2974’s picture

Issue summary: View changes
jksloan2974’s picture

Issue summary: View changes

I have an Exposed Group Content filter set on a view. I am running Drupal 9.1.11. Patch #414 seems to be the only one that works. If I update Drupal to anything above 9.2 patch 414 fails.

Other patches apply at higher Drupal versions but the exposed group still is incorrect. I have attached 2 screenshots the first is the desired behavior with Drupal 9.1.11 #414 applied. The second is Drupal 9.4.5 #491 applied.

D9.1.11

D9.4.5

jksloan2974’s picture

StatusFileSize
new99.22 KB
jksloan2974’s picture

StatusFileSize
new114.44 KB
acbramley’s picture

When using the latest patch (#491) I get a PHP error when trying to add an entity reference filter:

php.ERROR: Error: Cannot use a scalar value as an array in Drupal\Core\Render\Element\RenderElement::preRenderAjaxForm() (line 315 of /data/app/core/lib/Drupal/Core/Render/Element/RenderElement.php)

This is on PHP8 so I imagine this is what's failing the tests too.

lefale’s picture

After applying the latest patch (#491), I started getting memory issues (i.e. PHP Fatal Error: Allowed Memory Size Exhausted) when trying to access some of my views through UI. Long story short, the problem was coming from the default configuration of the Views Entity Reference filter plugin, which had been cleared after an upgrade to Drupal 9.4.5. For some reason, the plugin was trying to load all taxonomy terms of all taxonomies, resulting in a memory exhausted exception...

I solved the problem by adding a constant and setting a default value to the 'list_max' widget in EntityReference::defineOptions().

  /**
   * Maximum number of entities to display in filter for select widget.
   */
  const DEFAULT_LIST_MAXIMUM = 100;
  /**
   * {@inheritdoc}
   */
  protected function defineOptions(): array {
    $options = parent::defineOptions();

    $options['handler'] = ['default' => 'default:' . $this->getReferencedEntityType()->id()];
    $options['handler_settings'] = ['default' => []];
    $options['widget'] = ['default' => self::WIDGET_AUTOCOMPLETE];
    $options['list_max'] = ['default' => self::DEFAULT_LIST_MAXIMUM];

    return $options;
  }

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

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

asad_ahmed’s picture

Status: Needs work » Needs review
StatusFileSize
new2.67 KB
new61.79 KB

Made changes as per #500, thanks. Please review.

Status: Needs review » Needs work

The last submitted patch, 502: 2429699-502.patch, failed testing. View results

highermath’s picture

There is a good likelihood that the memory issues referenced in comment #500 are related to the documented memory leak issues with PHP 8.1.

smustgrave’s picture

Status: Needs work » Needs review

Putting back into NR the failure appears to be a random javascript one.

adriancid’s picture

adriancid’s picture

adriancid’s picture

adriancid’s picture

I don't know what happened to the previous empty messages.

I applied the patch from #491 in D 9.4.7 and is working for reference fields without problem, but I'm not able to add a filter for the workspace owner. I described the issue at #3319556: Owner view filter should be handled like a reference

muriqui’s picture

Looks like #502 accidentally removed most of #491, so re-rolling. Attached patch is just #491 with the changes from #500 added.

Also, referencing #2651418: Non-array values for #ajax which was also needed when I tested this patch.

graber’s picture

Status: Needs review » Needs work

Tried to add a media reference filter with this patch and..
Error: Cannot use a scalar value as an array in Drupal\Core\Render\Element\RenderElement::preRenderAjaxForm() (line 315 of /var/www/html/web/core/lib/Drupal/Core/Render/Element/RenderElement.php)

So we need to cover more and not only nodes when setting ['#ajax'] to [].

I'll handle that at least plus make a proper MR so we can review easily.

graber’s picture

Status: Needs work » Needs review
graber’s picture

Status: Needs review » Needs work
graber’s picture

Unfortunately, I'm stuck here as Drupal\Tests\views_ui\FunctionalJavascript\FilterEntityReferenceTest fails on dispatcher (the filter edit link seems not to be there on views admin UI after adding the filter) and passes on my local with the same core version and on the same branch.

Can someone else run that single test locally?

catch’s picture

It passes locally. The most likely issue is the chromedriver version on DrupalCI being different.

smustgrave’s picture

Don't know much about chromedriver. It also passes locally for me.

Wonder if we can put a waitForElementVisible before attempting to click?

graber’s picture

Status: Needs work » Needs review

waitForElementVisible didn't help, waitForElementRemoved('css', '.ui-dialog') also didn't help. Still passing locally. Setting this to review and someone needs to check the testbot.

daniel.rolls@flightcentre.com.au’s picture

Just rolling an update purely for the validateExposed method.

In some cases, like when using Better Exposed filters with Grouped filters the values are not an array, and values can be anything like "All", "1","2" etc. In these situations the values are masked by the grouping.

For now, just validating $values is an array before we treat it is such.

avpaderno’s picture

Status: Needs review » Needs work
medha kumari’s picture

Status: Needs work » Needs review
StatusFileSize
new2.67 KB

Rerolled the patch #519 in Drupal 10.1.x.

Status: Needs review » Needs work
graber’s picture

Status: Needs work » Needs review
StatusFileSize
new11.16 KB

Posting diff of the last patch with the 2429699-entity-reference-views-filter-d101 head. Can you check it out and answer: What are you trying to do actually?

Moving this back to needs review and please anyone reviewing: ignore those patches and focus on 2429699-entity-reference-views-filter-d101.

Also included #519.

smustgrave’s picture

Seems to be the same error.

smustgrave’s picture

Status: Needs review » Needs work

Still seeing the same error.

Also see it was tagged for change record which still needs to happen.

Will reach out for framework manager review.

smustgrave’s picture

Also think I may know why the test fails on drupal and not locally

/admin/structure/views/nojs/handler-extra/content/page_1/filter/field_test_target_id_reference is locally

but in drupal I bet it's

subdirectory/admin/structure/views/nojs/handler-extra/content/page_1/filter/field_test_target_id_reference

smustgrave’s picture

Lets try this.

Leaving in NW for change record.

Hiding files to avoid confusion

smustgrave’s picture

Lets try this.

Leaving in NW for change record.

Hiding files to avoid confusion

graber’s picture

Status: Needs work » Needs review

https://www.drupal.org/node/3338903 Here's a change record draft.
Not sure about it though as this is a new feature actually that doesn't affect any previous instances. Do we need a CR in such cases as well?

smustgrave’s picture

Status: Needs review » Reviewed & tested by the community
Issue tags: -Needs change record

Add small tweak to CR to include images.

So a CR is also useful to announce new features/major changes. So announcing users can use this new feature could be helpful for some.

catch’s picture

The issue summary currently mentions converting the TaxonomyIndexTid filter to be based on this, but this isn't done in the patch. I don't think we should do it here, already at a possibly record-breaking 530 comments, but I couldn't see a follow-up to do that in the related issues - would be good to create that if it really doesn't exist and link it from the issue summary.

smustgrave’s picture

Issue summary: View changes

This gets any more comments I'm afraid my page won't load haha

Opened #3339738: Convert TaxonomyIndexTid to use new EntityReference filter

smustgrave’s picture

Issue summary: View changes
lendude’s picture

Status: Reviewed & tested by the community » Needs work

@catch asked me to look at this again, mostly the test coverage. The test coverage seems mostly good, but ran into some other issues.

  • calculateDependencies is untested and should be since this is different than the Term plugin
  • The 'sort by' field is empty on initial adding of the filter (the field widget does something ajaxy when selecting bundles, the views widget does not, might be it?)
  • Grouped autocomplete filters don't work/save (but don't work for taxonomy ref filters either), please find the related issue or open it (should be one I think)
  • Description "as a Reference filter" feels a bit vague, did we get UX feedback on this?
  • Should we add this new filter for taxonomy terms too, or should we skip those since it is unclear what the difference is now when have to chose between the two different filters
  • I can create a circular reference by creating an Entity reference View that uses itself as the filter, not sure what goes wrong (mostly getting an empty filter after saving), but that sounds iffy
  • Maybe related : Managed to click my way into "Warning: Undefined array key "reference_views" in Drupal\views\Plugin\views\filter\EntityReference->submitExtraOptionsForm() (line 440 of /app/drupal/core/modules/views/src/Plugin/views/filter/EntityReference.php)"
  • Node titles in the select element are double escaped
  • Exposed filters on the chosen entity reference view are also shown on the view
graber’s picture

Issue tags: -

I'm afraid a few more comments and infra will break for good. Maybe we should close this and open in a new issue with a summary? We could also choose contrib approach I took with Views Date Filter, create a core readiness issue there and merge to core when ready? Some changes seem too big for a single issue and should be handled as epics with their own sub-tasks really, otherwise we're stuck for years and end users don't see any progress.

smustgrave’s picture

Opened up #3347343: Add Views EntityReference filter to support better UX for exposed filters and asked @catch or @lendude to take a look and see if we can close this one one out.

Moved over the changes in the MR and copied comment #534 as those need to be done.

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.

psf_’s picture

Hi, I don't like add more noise to this issue but I think it's a related use case.

The module https://www.drupal.org/project/config_views allow create views that query configuration entities, and I can create a new view that result all taxonomy vocabularies, for example. If I add a entity reference display to that view I can't select it in a reference field to use the view how list options.

I can't because this:

File: web/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php line 141 of Drupal 10.0.9.

      if (in_array($view->get('base_table'), [$entity_type->getBaseTable(), $entity_type->getDataTable()])) {
        $display = $view->get('display');
        $options[$view_id . ':' . $display_id] = $view_id . ' - ' . $display[$display_id]['display_title'];
      }

If I replace that code by:

        $display = $view->get('display');
        $options[$view_id . ':' . $display_id] = $view_id . ' - ' . $display[$display_id]['display_title'];

I can select my view, but after saving the site break with this error:

Error: Call to a member function bundle() on null in Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection->stripAdminAndAnchorTagsFromResults() (line 289 of core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php).

Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection->getReferenceableEntities() (Line: 618)
Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem->getSettableOptions(Object) (Line: 138)
Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase->getOptions(Object) (Line: 34)
Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsSelectWidget->formElement(Object, 0, Array, Array, Object) (Line: 349)
Drupal\Core\Field\WidgetBase->formSingleElement(Object, 0, Array, Array, Object) (Line: 92)
Drupal\Core\Field\WidgetBase->form(Object, Array, Object) (Line: 287)
Drupal\Core\Field\FieldItemList->defaultValuesForm(Array, Object) (Line: 125)
Drupal\field_ui\Form\FieldConfigEditForm->form(Array, Object) (Line: 106)
Drupal\Core\Entity\EntityForm->buildForm(Array, Object)
call_user_func_array(Array, Array) (Line: 536)
Drupal\Core\Form\FormBuilder->retrieveForm('field_config_edit_form', Object) (Line: 283)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 73)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 580)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 163)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 74)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 58)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 48)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 48)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 51)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 51)
Drupal\Core\StackMiddleware\StackedHttpKernel->handle(Object, 1, 1) (Line: 686)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

I think that fail because views only work with content entities, not with configuration entities.

catch’s picture

Status: Needs work » Closed (duplicate)

Closing this as a duplicate of #3347343: Add Views EntityReference filter to support better UX for exposed filters because this issue is crashing browsers at this point. Let's continue over there.

catch’s picture

Issue summary: View changes
catch’s picture

Issue summary: View changes
scott_euser’s picture

biancaradu27’s picture

StatusFileSize
new50.69 KB

add patch for 10.3.x

andyg5000’s picture

We were using the patch from 545. After upgrading to Drupal 10.5.1, it still applied cleanly, but caused critical errors because it duplicated the <?php tag and rest of the code.

If you're seeing `Parse error: syntax error, unexpected '<'` remove the patch.

Just a warning for others that may be using it!

ngal’s picture

StatusFileSize
new3.37 KB

I run into the same issue as #546 is describing, when updated a project to 10.4 so I updated the patch. Feel free to test, its working as expected for me.

ngal’s picture

xjm’s picture

Locking issue to prevent further comments and patches from being posted. This was fixed in #3347343: Add Views EntityReference filter to support better UX for exposed filters and is available in all supported versions of Drupal core.

xjm’s picture

Locking issue to prevent further comments and patches from being posted. This was fixed in #3347343: Add Views EntityReference filter to support better UX for exposed filters and is available in all supported versions of Drupal core.

The patch should no longer be necessary and should be removed before upgrading your site, although you may need to recreate your filter. As always, back up your site and data prior to upgrading.

xjm’s picture