Problem/Motivation

If a field has unlimited cardinality, then it is always displayed with one input too many. For example, I added a textfield named "Labels" to a content type and gave it unlimited cardinality. I create three label values, as illustrated here:

Labels field pre-save

Then I Save the form and go to Edit it again. When I do, one extra Label input has been added, even though I have not clicked the "Add another item" button. And there's no way to get rid of this extra input field:

Labels field pre-save

Always adding an unused text field gives users the impression that the form was not completely filled out even when it was, or that they clicked the "Add another" button when they did not.

I tracked the source of the "bug" down to a single line in the WidgetBase class. It looks like an off-by-one error to me, with respect to the difference between how the number of elements is calculated for a fixed, multiple cardinality field vs. how the number of elements is calculated for an unlimited cardinality field.

Steps to reproduce

Proposed resolution

Adjust the widget to not display an extra empty field.

Remaining tasks

Decide on the which fix to implement, the one in #3318259: Remove auto added empty field from multiple values field. or the one in patch in #34.
Add a test
Review
Commit

User interface changes

Introduced terminology

API changes

Data model changes

Release notes snippet

CommentFileSizeAuthor
#90 unlimited-cardinality-extra-input-2980806-71-v2.patch776 bytesartyom hovasapyan
#78 extra-inputs.png47.77 KBprashant.c
#76 required-extra-widget.gif1.84 MBpameeela
#74 unlimited-cardinality-extra-input-2980806-71-v2.patch776 bytessathishkumar
#72 unlimited-cardinality-extra-input-2980806-71-v1.patch845 bytessathishkumar
#71 unlimited-cardinality-extra-input-2980806-71.patch703 bytesedwardsay
#66 editing-extra-inputs.png39.91 KBjoaopauloc.dev
#66 3-extra-inputs-configured.png35.36 KBjoaopauloc.dev
#66 field-storage-settings.png65.62 KBjoaopauloc.dev
#64 remove-extra-input-field-2980806-9.5.x-64.patch3.93 KBgorkagr
#59 After Patch.png10.98 KBprasanth_kp
#59 Before Patch.png12.29 KBprasanth_kp
#58 extra-input-removed.png35.56 KBjoaopauloc.dev
#58 remove-extra-input-field-2980806-58.patch4.6 KBjoaopauloc.dev
#51 remove-extra-input-field-2980806-51.patch3.71 KBjoaopauloc.dev
#48 remove-extra-input-field-2980806-48.patch2.55 KBjoaopauloc.dev
#48 new-content.png39.19 KBjoaopauloc.dev
#48 edit-content.png38.73 KBjoaopauloc.dev
#45 2980806-after-34.png12.68 KBabhijith s
#34 interdiff-3-34.txt3.4 KBsmustgrave
#34 2980806-34-WIP.patch3.55 KBsmustgrave
fields_with_unlimited_cardinality-2980806-15.patch634 bytesshivam kaushal
#16 fields_with_unlimited_cardinality-2980806-15.patch634 bytesshivam kaushal
#11 Screen Shot 2020-07-24 at 11.27.00 AM.png311.38 KBtanubansal
#3 unlimited-cardinality-extra-input-2980806-3.patch663 byteslisastreeter
labels-field-post-save.jpg78.24 KBlisastreeter
labels-field-pre-save.jpg57.58 KBlisastreeter

Issue fork drupal-2980806

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

lisastreeter created an issue. See original summary.

lisastreeter’s picture

Issue summary: View changes
lisastreeter’s picture

This patch fixes the rendering of unlimited cardinality fields on edit forms for me by removing the "extra" input.

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.

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.

wiifm’s picture

Status: Active » Needs work

I had exactly the same issue, there was always another 'blank' row at the bottom of an unlimited cardinality field. This is a confusing UX for sure.

Applying the (simple 1 line) patch fixed the issue.

Marking as 'Needs Review' to get more eyeballs on this issue. But this is a +1 from me.

wiifm’s picture

Status: Needs work » Needs review

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.

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.

tanubansal’s picture

StatusFileSize
new311.38 KB

Tested via below mentioned steps on 9.1 :

1. I added a textfield named "Labels" to a content type and gave it unlimited cardinality.
2. Then I Save the form and go to Edit it again. When I do, one extra Label input has been added, even though I have not clicked the "Add another item" button. And there's no way to get rid of this extra input field

Same issue is there on drupal 9.1
Can we have a patch for 9.1?

mayurjadhav’s picture

Status: Needs review » Needs work

I have tested the #3 Patch Manually and it works as expected, Test is failing just because of ajax fatal error, While adding more field using Add more button getting ajax fatal error which leads to fail all the test.

paulocs’s picture

@mayurjadhav is right, if we try to create a new content type with the unlimited cardinality field we have to click twice on the button "Add another item" to add an item.

mandclu’s picture

I like this idea, but I would suggest that this should be something that could be configured in the widget settings. I see that #2384889: [PP-1] Initial number of fields visible on the form should be configurable for fields set to unlimited value has proposed something similar, though I feel that might be just for an empty field.

shivam kaushal’s picture

Assigned: shivam kaushal » Unassigned
Status: Needs work » Needs review
StatusFileSize
new634 bytes

The last submitted patch, fields_with_unlimited_cardinality-2980806-15.patch, failed testing. View results

Status: Needs review » Needs work

The last submitted patch, fields_with_unlimited_cardinality-2980806-15.patch, failed testing. View results

gisle’s picture

The patch in comment #16 is the same as the one submitted in #3 - except that the one in #16 adds bloat by not removing a now redundant assignment.

Please do not pretend to participate in fixing stuff when you provide no improvement over what others already have done by others (in fact it is worse).

gisle’s picture

Adding back #2384889: [PP-1] Initial number of fields visible on the form should be configurable for fields set to unlimited value. No grounds for its removal was given in comment #15, and to me, the removals looks like a mistake by an inexperienced new community member.

longwave’s picture

Issue summary: View changes

Also restoring the issue summary which was deleted in #15

longwave’s picture

Personally I always thought this was "by design" to allow extra values to be added easily without needing to click "Add another item" first. But I can also see how this could be considered confusing.

darren oh’s picture

This was by design, but it has always been annoying and difficult to override.

gisle’s picture

I also understand that this is by design. And I have never been annoyed by this – or even thinking about it as an issue until I stumbled across this.

Incidently I've seen identical behaviour lot of other places. For instance the dialogue to add another subdomain provided by my registrar works in the same way.

My vote is for leaving it alone.

mandclu’s picture

I think this pattern works well for simple fields where the behaviour doesn't add a lot complexity, and also in situations where there's a reasonable expectation that a user will need multiple entries.

I maintain Smart Date and one of the things I've struggled with is the balance between power and complexity. If a field is configured to manage timezones and recurring dates, there's a lot to the interface. Having an extra, empty field makes the overall interface look much more complicated, and also deviates from one of the aims for that module, which is to make Drupal's date handling as close as possible to how popular calendar apps work. If you go to create an event in a Google or Apple calendar, it doesn't give you two sets set fields, it gives you one. For Smart Date I was able to add a configuration option to suppress Drupal's default behaviour, but I agree with the sentiment that this should be generally available as part of the standard configuration for WidgetBase, when a field has unlimited values.

I agree that there are plenty of examples of where the current behaviour makes sense, but there are also lots of examples of where it doesn't, so making the behaviour configurable would allow Drupal to meet both. So I'd support the approach suggested in #2384889: [PP-1] Initial number of fields visible on the form should be configurable for fields set to unlimited value.

longwave’s picture

Should this behaviour be determined by the field widget? Simple widgets can opt in and complex widgets can opt out?

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.

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.

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

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

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.

smustgrave’s picture

running patch #3 against latest dev to see what fails.

With regards to #27 the setting makes sense but if this extra field is causing an accessibility issue don't think we should

smustgrave’s picture

Assigned: Unassigned » smustgrave

I'll work on the test cases.

smustgrave’s picture

StatusFileSize
new3.55 KB
new3.4 KB

Testing a new patch to see failures.

smustgrave’s picture

Status: Needs work » Needs review

Oh wow that patch worked.

  1. Steps I used for testing
  2. Add a field to any content type.
  3. Make field settings to unlimited
  4. In the field config page verify the default value is showing one field
  5. Save the field
  6. Create a node of that content type
  7. Verify 1 field appears
  8. Add a value to the field
  9. Click add another item
  10. Verify new field appears
larowlan’s picture

Issue tags: +Bug Smash Initiative

Discussed this with @andrewmacpherson to validate the a11y aspect.

He indicated that there is no a11y issue with having an extra empty field.

Which then makes this a feature request rather than a bug.

@smustgrave rightly pointed out that #2384889: [PP-1] Initial number of fields visible on the form should be configurable for fields set to unlimited value would then render this a duplicate, because that is allowing the number to be configured, so that would also solve this problem.

As a result, marking as a duplicate of #2384889: [PP-1] Initial number of fields visible on the form should be configurable for fields set to unlimited value and transferring credit over there.

larowlan’s picture

Status: Needs review » Closed (duplicate)
darren oh’s picture

Status: Closed (duplicate) » Needs review

This is a usability bug because it gives the user the impression that a form has not been completely filled out even when it has. It should not be blocked pending a new feature.

smustgrave’s picture

Can you provide a link or report of how this is an accessibility issue?

darren oh’s picture

Issue summary: View changes

Not sure why this became about accessibility. It is a usability bug as I explained above. I have removed comments from the description that may be causing confusion.

darren oh’s picture

Issue summary: View changes
darren oh’s picture

smustgrave’s picture

Right so the extra field was by design. In https://www.drupal.org/project/drupal/issues/2384889 site builders could configure their fields to remove that extra field or add extra I suppose. Making this ticket moot

darren oh’s picture

Assigned: smustgrave » Unassigned

I like the new feature provided by #2384889: [PP-1] Initial number of fields visible on the form should be configurable for fields set to unlimited value. This is still a design bug and should not be blocked by that feature if a fix is ready.

abhijith s’s picture

StatusFileSize
new12.68 KB

Applied patch #34 on 9.5.x.But the extra field input item is still showing after applying this patch. Attaching screenshot for reference.

after

Needs work

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.

joaopauloc.dev’s picture

Assigned: Unassigned » joaopauloc.dev
joaopauloc.dev’s picture

StatusFileSize
new38.73 KB
new39.19 KB
new2.55 KB

Hey guys the patch above didn't work for me in 10.1.

Based on the thread above if I understood correctly the following scenario should happen.

Considering only cardinality unlimited!

Field X with an unlimed value of any type of field.

Creating new content
The field should appear with only one empty option and the button to add more.
If the user clicks on add more another option will appear.

Editing content.
The field should list all values defined without any empty field to be populated by the user. If the user wants to add one more item it's necessary to click on Add more button and then populate the field.

Creating new content with a default value.
Let's suppose that we have a field unlimited with two values as default.
The field will appear with the default value(s) follow by another empty field for the user to populate what he wants.

See the attachments to check how it will work after this patch and please validate if attend what this issue wants to fix.

Regards.

Status: Needs review » Needs work

The last submitted patch, 48: remove-extra-input-field-2980806-48.patch, failed testing. View results

joaopauloc.dev’s picture

Tests failed fixed.

Functional\NestedFormTest ok
field\Functional\EntityReference\EntityReferenceFieldDefaultValueTest ok

FormTest is already failing before applying the patch in my local tests.

Also was necessary remove the code of the first patch 2980806-34-WIP.patch because started to fail some tests.

Trying to run again and wait if is something wrong in my local configurations.

joaopauloc.dev’s picture

StatusFileSize
new3.71 KB
darren oh’s picture

New content with a default value should be the same as editing existing content. No need to have a blank field when there is a default value.

joaopauloc.dev’s picture

Hey @darren-oh, I will adjuste that.
Also I'm having some problems to fix this test failing. This particulary test are failing without my patch. I don't know how to fix it.

smustgrave’s picture

joaopauloc.dev’s picture

Thanks @smustgrave, I was trying to fix the php units that are failing.
Also the approach to have config to set how many empty items to be displayed is better.

Should we close this issue?

joaopauloc.dev’s picture

Assigned: joaopauloc.dev » Unassigned
darren oh’s picture

The issues are similar but not the same.

joaopauloc.dev’s picture

Status: Needs work » Needs review
StatusFileSize
new4.6 KB
new35.56 KB

No matter if this issue will be merged or not, I spent too much time investigating this issue to not provide the possible fix that I found :). If the issue is still not merged someone can use this patch.

Removing extra input when the field settings have a default value. See the picture attached.

With this change, we don't have an extra input by default in any situation, only when the user clicks in add more button.
Also, the test that failed for me doesn't make sense so I changed how the test works. But I think is necessary to be validated by someone else.

This is the test that failed.

Drupal\Tests\field\Functional\FormTest::testLabelOnMultiValueFields
Behat\Mink\Exception\ExpectationException: The string "alert('a configurable field');" was not found anywhere in the HTML response of the current page.

The test check $this->assertSession()->assertEscaped("

alert('a configurable field');

");
But when we create a field with this label the tag script is filtered and the label becomes alert('a configurable field');
So I think the correct way to validate if the tag script is filtered is to check if the tag script doesn't appear on the page as my changes do.
But will amazing if someone else confirms that in a code review.

$this->assertSession()->pageTextContains("alert('a configurable field');");
$this->assertSession()->pageTextNotContains("

alert('a configurable field');

");

prasanth_kp’s picture

StatusFileSize
new12.29 KB
new10.98 KB

@joaopauloc.dev thanks for the patch. #58 Patch Applied on 10.1.x-dev and it fixes the issue.

joaopauloc.dev’s picture

Status: Needs review » Needs work

Didn't work as expected when we use unlimited fields with paragraphs.

dpi’s picture

Seems to me like there might be a lot of crossover between this and #1156338: Fixed maximum number of field values, but use «add more» similar to when cardinality «unlimited» is used

Maybe both should be triaged into a _Optimising add more button behavior_ issue

anybody’s picture

I like this idea, but I would suggest that this should be something that could be configured in the widget settings.

Strongly agree! :)

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.

gorkagr’s picture

Hi!

Thanks joaopauloc.dev for the patch. Unfortunately i could not apply it for 9.5.x so here it goes a path for that version.

I have noticed a duplicated declaration of $context that you have removed in your patch (I think the reason it does not work with 9.5.x), but i have opened an issue (https://www.drupal.org/project/drupal/issues/3378657) to spot that duplication and remove it, so i have omitted it from my patch.

PD: I have not tested it within fields inside paragraphs, but once i have a bit of time, i will check this too

Best

joaopauloc.dev’s picture

StatusFileSize
new65.62 KB
new35.36 KB
new39.91 KB

Hey folks, I created a new merge request regarding the comments above, the number of extra inputs to be displayed should be a configuration.

A new configuration was added to the field storage settings, like the image below:
field storage settings
When the unlimited option is selected a new field is displayed for the user to choose how many extra inputs will be displayed.

  1. By default, I choose 1, because this is how it works today, one extra input appears.
  2. If the user selects 0, no extra input will appear, if the user is adding the form entity. Only one input will appear.
  3. If the user selects 0 and is editing the form entity, if there is no value one input will appear, otherwise only the input with value populate will appear without any extra input.

Example:
Field with 3 extra inputs to be displayed:
unlmited field with 3 extra input
So, for the editing form, as I configured 3 extra inputs but populated only 2, any extra input will appear.
editing form
Once we define a number of extra inputs to be displayed when the user is adding the number of inputs selected will appear, If the user is editing but there is no value added previously, the number of inputs keeps the configuration, since the user added more or fewer items that were configured, only the values populated is displayed without any extra input.

Maybe we need to discuss the rules mentioned above, how we should display the inputs if the user is editing.

joaopauloc.dev’s picture

Status: Needs work » Needs review
smustgrave’s picture

Status: Needs review » Needs work
Issue tags: +Needs upgrade path, +Needs upgrade path tests, +Needs change record

If we are going to change the schema we will need an upgrade path with tests.

anybody’s picture

Priority: Normal » Major
Issue summary: View changes

There's another aspect, which makes this fix major from my perspective. If the added field is a required field (or contains a required field in a compound field widget), there's no way to remove the extra field, and you're unable to submit the form with the required field!

That makes using #required impossible on custom compound field widgets!
But without the required indicator, the user can't see which compound fields are required, until submit (validation)!

So the best solution is to not add the new line automatically and be able to remove it.
Just ran into this when implementing Homebox 3.x.

edwardsay’s picture

Adding 10.2 support for patch #3

sathishkumar’s picture

Version: 11.x-dev » 10.2.x-dev
Assigned: Unassigned » sathishkumar
StatusFileSize
new845 bytes
sathishkumar’s picture

Assigned: sathishkumar » Unassigned
sathishkumar’s picture

StatusFileSize
new776 bytes
plach’s picture

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

@sathishkumar

Thanks for the patches, but the changes will be merged to the development branch first, then backported.

pameeela’s picture

Priority: Major » Normal
Issue summary: View changes
StatusFileSize
new1.84 MB

I can't reproduce the behaviour reported in #69 on D11.

Steps:

  1. Add a new field with unlimited cardinality
  2. Add a node with one value
  3. Edit the node, see the extra input
  4. Save

Bumping down to normal, unless someone has different steps to reproduce that? I am 50-50 on the usability aspect, I could see both sides of the argument.

prashant.c changed the visibility of the branch 11.x to hidden.

prashant.c’s picture

StatusFileSize
new47.77 KB
  • Rebase the current PR branch with 11.x
  • Tested on Drupal 11 have following points
  1. The placement of the section Extra inputs to displayis not good from the usability point as it giving an impression that the cardinality text field is standalone, it has moved the cardinality text field which should be next to the dropdown Allowed number of values
  2. When the cardinality has been specified, the value in the Extra inputs to display text field should be validated for the max value either on Form submit or on value change, currently it allows greater values than cardinality, however on the frontend displaying the fields correctly but the value is still allowed to be entered
  3. Extra Inputs

Thanks!

quietone’s picture

I was triaging #3318259: Remove auto added empty field from multiple values field. and came here because this seems like a duplicate. In fact this was closed as a duplicate of a different issue and credit was moved over there. That was issue #2384889: [PP-1] Initial number of fields visible on the form should be configurable for fields set to unlimited value. After reading three incomplete issue summaries and the comments on three issue, I have decided that this one should go back to the original intention, which was a UX issue. And, since this is the older issue and has more discussion I am closing #3318259: Remove auto added empty field from multiple values field. as a duplicate and moving credit. The work here, from about #47 is out of scope and should move to #2384889: [PP-1] Initial number of fields visible on the form should be configurable for fields set to unlimited value, the original issue to add the extra configuration.

This issue is solely about the UX of the extra blank field that appears on edit. See the remaining tasks for what needs to be done.

Everyone, please keep the issue summaries up to date. Incomplete summaries makes it more difficult to work with an issue and to get it to commit. Thanks.

anybody’s picture

Re #76 I still think this is Major, see the reason given in my comment in #69.
That also means @quietone (#80): I wouldn't say this is *only* UX, it's also a heavy logical validation issue for all cases where this applies to compound fields (widgets) like IEF (#3099844: Required fields inside referenced entity make an optional IEF (erroneously) required) and others.

Until this issue is fixed, if the additionally added empty entry, if containing a required field, blocks saving the parent entity due to

  • Form validation (could be circumvented in the module, but logically it would just be better to never have that empty entry!)
  • HTML5 required attribute validation (can just be hacked)

So getting this fixed isn't only UX for more complex widgets than just autocomplete.
For that reason, I'm setting this back to Major, but of course we can still discuss that. Even better: Let's just fix it and also unblock #2384889: [PP-1] Initial number of fields visible on the form should be configurable for fields set to unlimited value then.

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

grevil’s picture

I don't think we should add the new "cardinality_display" setting on the field definition? Outside the Widget, this setting seems to be quite useless IMO.

I think it should be rather implemented as a Widget Setting, which only appears if the cardinality is set to above 1 (including -1 for unlimited). I'll create a second branch for this, so we can always go back, to the original field definition solution by @joaopauloc.dev.

pameeela’s picture

Based on the screenshot in #78, I'm concerned we are trading one usability problem for another. This increases the complexity of this form widget a lot.

I agree that having the empty widget causes confusion and have had this complaint from clients. I can see the case for having it but I don't really think this needs to be a setting in the UI. If people really want to be able to override it, we can still have the configuration and allow code overrides?

anybody’s picture

@pameeela, thanks for the feedback. That's not a bad idea. In core we could add methods for the programmatic part, but leave out the widget settings (maybe) and implement them in contrib, if anyone needs it?

So we'd have clean solution in core available, but not cluttering the UI!

One difficult thing @grevil and me had issues with is the difference between:

  1. Showing an empty line if the field is not filled at all (Which might be expected for many field types, like autocomplete or text, but not for others, especially complex ones or compound with required fields that fail then, like IEF)
  2. Showing an additional empty line if there are values present already (current behavior)
  3. Showing a number of lines initially (similar to what https://www.drupal.org/project/sam and #1394184: Add multiple items at once does)

All are different valid cases that the Core API should support better!

Both need to be handled separately for an excellent and complete solution in our eyes!

Might this be a topic for the UX meetup?

pameeela’s picture

Of course, it is never simple! And I agree also that having better support for configuring this generally would be ideal.

As for this specific issue, I would say by default:

  • If the field is empty, show one
  • If there are values, don't show an extra one

And then add support for configuring both of those in code?

anybody’s picture

@pameeela: Great! Agreed on that! Here are the details I'd like to propose:

If the field is empty, show one

I'd say we should solve that using the cardinality_display variable, defaulting to 1 so it can also be set to 0 or any number of fields to show generally (<= cardinality)

If there are values, don't show an extra one

I'd vote for a boolean option for this one. Do you have an idea for a good machine name?
Maybe sth. like:

  • add_one
  • add_blank
  • additional_input
  • blank_input
  • ...?

I'm not a native speaker, so maybe you have a better idea! :)

Once we're clear on these points, let's do it!

ckrina’s picture

Agreed with the latest comments: as @pameeela suggested, if settings can be moved out of the UI would help not increasing Drupal's complexity. And since several of these assumptions don't follow a specific or generic UX rule and can change based on project & form specific case (but are necessary decisions to be taken) a setting in code is the best solution.
Just make sure the work happens on the right issues as @quietone suggested: specific and focused changes have better chances to get in, faster (it took me 30min to understand what happened in this issue).

artyom hovasapyan’s picture

#74 works for me, but we need to change `>` to `>=` .
When there is 1 saved item and you open the node, you will see 2 item (1th with value and 2nd is empty). Using `>=` fixes this problem.

Version: 11.x-dev » main

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

Read more in the announcement.

artyom hovasapyan’s picture

I found a quick solution. It works, but the implementation is not very clean.
This works for field/paragraph_field, but you must add the .multivalue_extra_value_fields class to each field where it is needed.

You can use this code example:

.JS file

Drupal.behaviors.mainMenu = {
    attach: function (context) {
// Remove multivalue field extra 1 empty item.
      const fields = context.querySelectorAll(".multivalue_extra_value_fields");
      fields.forEach(function (field) {
        if (field.classList.contains("only-one-item")) {
          return;
        }
        const rows = field.querySelectorAll(".field-multiple-table > tbody > tr");

        if (rows.length === 1) {
          field.classList.add("only-one-item");
        }
      });
}}

CSS file

.multivalue_extra_value_fields {
  .remove-extra-empty-field .field-multiple-table tbody tr:last-child:not(:first-child) {
    display: none;
  }

  &.only-one-item .remove-extra-empty-field .field-multiple-table tbody tr:last-child {
    display: table-row;
  }
}

module/theme code:

/**
 * Implements hook_preprocess_field_multiple_value_form().
 */
function MODULENAME_preprocess_field_multiple_value_form(&$variables) {
  $element = $variables['element'];

  // Check if this field is in the list of multivalue fields
  // that require removal of extra empty items.
  if (in_array($element['#field_name'], _intranet_article_multivalue_fields_need_remove_extra_empty_item())) {
    $item_count = 0;
    foreach ($element as $key => $value) {
      if (is_numeric($key)) {
        $item_count++;
      }
    }
    // If more than one item exists, mark wrapper for JS handling.
    // Note: AJAX rebuilds may require this class to be re-applied.
    if ($item_count > 1) {
      $variables['attributes']['class'][] = 'remove-extra-empty-field';
    }
  }
}

/**
 * Implements hook_field_widget_complete_form_alter().
 */
function MODULENAME_field_widget_complete_form_alter(array &$element, FormStateInterface $form_state, $context) {
  if ($element['widget']['#field_name'] == 'field_aa_paper_affiliation') {
    // Add class for JS detection of multivalue field behavior.
    $element['#attributes']['class'][] = 'multivalue_extra_value_fields';
  }
}

/**
 * Returns list of multivalue fields that require extra empty item handling.
 *
 * These fields are used in custom JS logic to detect and manage
 * extra empty values in multivalue widgets (e.g., removing or controlling
 * automatically added empty rows).
 *
 * Note: Each field listed here should also receive the
 * "multivalue_extra_value_fields" CSS class to ensure consistent
 * behavior across AJAX rebuilds and initial page load.
 */
function _MODULENAME_multivalue_fields_need_remove_extra_empty_item() {
  return [
    'field_aa_paper_affiliation',
  ];
}