Problem/Motivation

This is a portion of #2900409: [Meta] Improve UI of Reference field settings form, separated out after comment #133.

Steps to reproduce these issues:

a) Install with the Standard install profile.

b) Go to Admin > Structure > Content Types.

c) Edit the Article content type -- change its name to Recipe and title field label to Recipe name.

d) Edit the Page content type -- change its name to Vendor and title field label to Vendor name.

[Note: This is similar to the content types used as examples in the User Guide.]

e) Now go to the Recipe content type > Manage fields. Add a Vendor reference field. Or alternatively, go to the Vendor content type and add a Recipe reference field. When you get to the field settings page, you'll see that the title sort option in the "Sort by" select list says "Recipe name" in either case (or it might randomly say "Vendor name" in either case -- I've seen it both ways). Anyway, it is very confusing to say "Recipe name" if you are trying to add a Vendor reference field on the Recipe content type. Here is what the sort options look like:
Sort options for reference field

Also note that this is complementary to #3089529: Sort options for entity reference fields may be confusing if several fields share labels -- this issue is about having multiple labels for the same shared field, and that other one is about having multiple fields for the same shared label.

Proposed resolution

Figure out a way that the user will be able to find what they want in the list for sort options, in the case where a given field (either a built-in field like Title or a user-added field) has different labels on different bundles.

Note that #3089525: Sort options should correspond to bundles selected for entity reference field settings will help with this, because often with Entity Reference fields, in practice, you only want 1 or maybe 2 related bundles to be referenced anyway, so if the choices are limited to the selected bundles, much of this ambiguity goes away.

Remaining tasks

Make a patch with tests.

User interface changes

??? TBD

API changes

None.

Data model changes

None.

Release notes snippet

Probably not needed?

Comments

jhodgdon created an issue. See original summary.

jhodgdon’s picture

Issue summary: View changes

Adding note about related issue.

jhodgdon’s picture

Title: Sort options for entity reference fields can be ambiguous and misleading » Sort options for entity reference fields can be ambiguous if a field has different labels across bundles
benjifisher’s picture

Here is a first step: create one option for each field on each bundle. This creates a lot of duplicates. I expect it will also break some tests.

The related issue #3089521: Sort options for entity reference field are unsorted will sort the options. The next step will be to remove the duplicates.

Since we cannot identify duplicates until the labels have been translated, I think the way to get rid of duplicates is to add a new option, say sort_unique or unique_options, to the Select Form API element. This is related to what we did in #3065903: Add label sort ability to Select element. I am adding #3069844: Provide additional options for sorting the options in Select form elements as a related issue, and I will add a comment there.

jhodgdon’s picture

I think you forgot to upload a patch?

benjifisher’s picture

StatusFileSize
new1.4 KB

So I did. Thanks for pointing it out, Here it is. I will leave a "4" in the file name; I hope that is not too confusing.

benjifisher’s picture

Status: Needs work » Needs review
Issue tags: +Needs tests, +Needs screenshots
StatusFileSize
new3.9 KB
new5.21 KB

The attached patch implements a new option, #sort_unique, on the Select form element, then uses it for the sort-by options. It also makes the change from #3089521: Sort options for entity reference field are unsorted: sort the options before removing duplicates. If we like this approach, then we will have to pick apart the patch: do not duplicate #3089521, and we will probably want a separate issue to add the new option.

The patch does not test for duplicate optgroups. It is careful not to lose the selected value (if any).

benjifisher’s picture

StatusFileSize
new1.37 KB
new5.4 KB

The attached patch sorts on value if the labels are equal. Conceivably, there could be many options with the same label and two different values. If, after sorting by label, the values alternate, then no duplicates would be removed. This version of the patch avoids that possibility.

This patch also removes some hard tabs.

If we want to combine this issue with #3089529: Sort options for entity reference fields may be confusing if several fields share labels without adding another option, then we could disambiguate the options with one more loop through the options, or by making the current loop a little more complicated.

jhodgdon’s picture

Question:

-    uasort($sorted, function ($a, $b) {
-      return strcmp((string) $a['label'], (string) $b['label']);
+    usort($sorted, function ($a, $b) {
+      return strcmp((string) $a['label'], (string) $b['label'])
+        ?: strcmp($a['value'], $b['value']);

You changed from uasort to usort -- that seems wrong, because as far as I can tell, uasort preserves array indices, whereas usort doesn't, and I think we need to preserve the indices?
https://www.php.net/manual/en/array.sorting.php

But... I guess I don't understand why we need sort_unique at all. Why are we putting duplicates into the array in the first place? It seems like we could just not put them in. We should be able to tell if the same untranslated label and value are being used during the foreach where we set up the options?

benjifisher’s picture

You changed from uasort to usort

Thanks for bringing that up. I meant to point that out myself.

The array keys are just numeric, so there is no need to preserve them: $options[] = $option;. The values of the options come from $options[$i]['value'], not from the array keys. (At this point in the processing, we do not have to worry about the confusing possibilities for the '#options' key of the Select render array. We have a uniform structure. Well, pretty uniform, since we still have to deal with optgroups.)

More to the point, the patch needs the array to be re-indexed for the next step:

+      for ($i = count($sorted) - 1; $i > 0; --$i) {

If we preserve the keys, then we might as well do this step before sorting!

We should be able to tell if the same untranslated label and value are being used during the foreach where we set up the options?

I guess that is true, as long as "untranslated label" means just the string passed to t(), ignoring any variables that are inserted into the string. I think we want to check for duplicates after translation. Maybe I am safer saying that we want to check for duplicates after inserting variables.

Contrived example: before translation, we have several items whose labels are all different, and the source language is Inuit. Some of the keys are duplicates. After translation, all of the labels are "Snow". We want to eliminate duplicates after translation.

jhodgdon’s picture

On the other hand, when we get to making options, the array keys there are field_name.column... If there are dups, won't they go away when we add them to the array with the same array key?

benjifisher’s picture

No, instead of building $select['#options'] as an array like ['nid' => 'Node ID', 'title' => 'Title'], we are building a numerically indexed array of stdClass objects, like

[
  (object) ['option' => ['nid' => 'Node ID']],
  (object) ['option' => ['title' => 'Title']],
]

I had forgotten about this way of adding an option until we discussed it at the Usability meeting on 2019-10-22. (See #2900409-133: [Meta] Improve UI of Reference field settings form. The technical point of using an object with an option property did not make it into that comment, but there is a link there to the recording of the meeting.)

Here is part of the patch that does this:

+++ b/core/lib/Drupal/Core/Entity/Plugin/EntityReferenceSelection/DefaultSelection.php
@@ -235,11 +235,15 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta
           // @todo: Use property labels instead of the column name.
           if (count($columns) > 1) {
...
           }
           else {
-            $fields[$field_name] = $this->t('@label', ['@label' => $field_definition->getLabel()]);
+            $option = [];
+            $option['option'][$field_name] = $this->t('@label', ['@label' => $field_definition->getLabel()]);
+            $fields[] = (object) $option;
           }
         }
       }

I snipped the part that deals with fields that have multiple columns. It is similar, but a little more complicated.

benjifisher’s picture

P.S. The object option that this patch uses is documented in Drupal\Core\Render\Element\Select:

 * Properties:
 * - #options: An associative array of options for the select. Do not use
 *   placeholders that sanitize data in any labels, as doing so will lead to
 *   double-escaping. Each array value can be:
 *   - A single translated string representing an HTML option element, where
 *     the outer array key is the option value and the translated string array
 *     value is the option label. The option value will be visible in the HTML
 *     and can be modified by malicious users, so it should not contain
 *     sensitive information and should be treated as possibly malicious data in
 *     processing.
 *   - An array representing an HTML optgroup element. The outer array key
 *     should be a translated string, and is used as the label for the group.
 *     The inner array contains the options for the group (with the keys as
 *     option values, and translated string values as option labels). Nesting
 *     option groups is not supported.
 *   - An object with an 'option' property. In this case, the outer array key
 *     is ignored, and the contents of the 'option' property are interpreted as
 *     an array of options to be merged with any other regular options and
 *     option groups found in the outer array.

Just to be clear as mud: the object option is the last #options option. ;)

jhodgdon’s picture

Status: Needs review » Needs work

OK. That makes sense.

I tested this patch today. It kind of works.... One thing, however, is quite jarring:

If you follow the steps in the issue summary: make Article -> Recipe and Basic Page -> Vendor (with corresponding labels for the Title field). Now on Recipe, add a new content reference field called "Vendor".

If you go to the sort options, and select to sort on "Vendor name", it's OK, and the machine name of the sort option chosen is "title" as it should be. However, if you select "Recipe name" (which also has "title" as the machine name of the sort option chosen), as soon as you finish the select, some kind of Ajax magic happens, and the selected item changes to "Vendor name".

This is rather jarring, and I think due to the fact that in the Ajax submission, all that is passed through is that the "title" option is chosen, so when it comes back, the "title" option is still chosen, and the browser has to decide which one to select. In my browser, it is consistently choosing "Vendor name" to select, even if I just selected "Recipe name".

I hope that makes sense. If I were good at making screencasts, I would make a movie of it... but I have no idea how to do that. Alas!

Anyway, I don't think this is a usable UI. So, I don't think it's actually a good idea to have two options in the same select with the same machine name and I'm setting this to Needs work.

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.

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.

jhodgdon’s picture

Status: Needs work » Closed (won't fix)

I discussed this briefly in Slack with @benjifisher...

When we originally looked at this in Usability meetings, the UI mockups where we showed machine names did not get very good reviews from the Usability team. The solution in patches on this issue also had bad usability.

Also, we need to think about the 95% use case. Most people who use reference fields are only referencing one bundle/entity subtype at a time. This is not a problem for these users, because we have already solved #3089523: Use progressive disclosure to hide Sort options on entity reference fields until bundles are selected and #3089525: Sort options should correspond to bundles selected for entity reference field settings. Together, these two resolved issues mean that they only see fields that are present on their 1 bundle, and the labels shown are the labels used in that bundle.

Given that there is not a good proposed solution to this issue, and the 95% use case is working well with the current UI, we should close this issue as Won't Fix.