Problem/Motivation

Cannot affect the visibility or requirement of managed_file with states. Identical to #1118016: conditional visibility of a managed_file using #states attribute does not work so either the bug wasn't fully fixed before, or a regression happened at some point and broke this functionality.

With this definition:

$form['type'] = array(
  '#type' => 'select',
  '#options' => array(
    'video' => t('Video'),
    'audio' => t('Audio'),
    'post' => t('Text'),
  ),
);

$form['audio'] = array(
  '#type' => 'managed_file',
  '#title' => t('Audio File'),
  '#states' => array(
    'visible'  => array(':input[name="type"]' => array('value' => 'audio')),
    'required' => array(':input[name="type"]' => array('value' => 'audio')),
  ),
  '#upload_location' => 'public://',
  '#upload_validators' => array(
    'file_validate_extensions' => array('mp3 wac'),
    'file_validate_size' => array(1048576),
  ),
);

I expect the visibility of "audio" to change when changing the value of "type". What happens is "audio" remains visible and not required. Simply changing "managed_file" to "file" brings the expected behavior.

Steps to reproduce

1. Create a custom form with structure as above
2. Navigate to the form
Problems:
1. On page load the "audio file upload" option is shown, which should show up only on selecting the Audio option.
2. Mandatory asterix is not shown for audio file upload field when the Audio option is selected

Proposed resolution

Root cause: During porting of fix from 8.x to 9.x the bug seems to be introduced. In the
function template_preprocess_file_managed_file(&$variables) {
there
$variables['attributes'] = [];
is overridden.

Proposed fix: Conditionally override to ensure if that the attributes set for #states is not lost.

For the "required" capability of #states to work, the label has to be correctly set, so that the mandatory asterix can be set. The managed_file introduces a "upload" index. Set the #states to the "upload" index as the label refers to the this and not the original "audio" field.

Remaining tasks

User interface changes

API changes

Data model changes

Release notes snippet

CommentFileSizeAuthor
#93 2847425-93.patch6.98 KBewout goosmann
#92 2847425-92.patch6.69 KBsboden
#65 2847425.57_65.interdiff.txt3.45 KBdww
#65 2847425-65.patch6.95 KBdww
#65 2847425-65.test-only.patch5.22 KBdww
#62 after states working.png172.58 KBameymudras
#62 patch applies cleanly.png233.99 KBameymudras
#62 before states not working.png27.55 KBameymudras
#57 interdiff_56-57.txt731 bytesravi.shankar
#57 2847425-57.patch10.3 KBravi.shankar
#56 interdiff_55-56.txt651 bytesravi.shankar
#56 2847425-56.patch10.26 KBravi.shankar
#55 2847425-55.patch10.25 KBanushrikumari
#49 interdiff_47-49.txt632 bytesvsujeetkumar
#49 2847425-49.patch6.98 KBvsujeetkumar
#47 interdiff_45-47.txt726 bytesvsujeetkumar
#47 2847425-47.patch6.9 KBvsujeetkumar
#45 2847425-44_45.txt526 bytesgauravvvv
#45 2847425-45.patch6.91 KBgauravvvv
#44 states_not_affecting-2847425-44.patch6.9 KBabu-zakham
#39 states_not_affecting-2847425-39.patch6.91 KByury n
#37 states_not_affecting-2847425-37.patch6.53 KBkostyashupenko
#24 states_not_affecting-2847425-24.patch6.48 KBscott_euser
#24 interdiff-2847425-20-24.txt315 bytesscott_euser
#20 interdiff-2847425-14-20.txt4.06 KBscott_euser
#20 states_not_affecting-2847425-20.patch6.88 KBscott_euser
#14 interdiff-2847425-8-14.txt3.91 KBscott_euser
#14 interdiff-2847425-13-14.txt745 bytesscott_euser
#14 states_not_affecting-2847425-14.patch6.37 KBscott_euser
#13 interdiff-2847425-8-13.txt3.9 KBscott_euser
#13 states_not_affecting-2847425-13.patch6.36 KBscott_euser
#8 interdiff-2847425-8.txt865 bytesscott_euser
#8 drupal-core-states-not-affecting-visibility-requirement-of-managed-file-2847425-8-D8.patch1.73 KBscott_euser
#3 drupal-core-states-not-affecting-visibility-requirement-of-managed-file-2847425-3-D8.patch1.8 KBscott_euser

Issue fork drupal-2847425

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

bander2 created an issue. See original summary.

scott_euser’s picture

Issue summary: View changes

There appears to be two issues with the managed file. This is my understanding of it, but please correct me if I have it wrong.

The managed file input is loaded via ajax and appears within an 'ajax-wrapper' div
By the time it is loaded it appears that this bit of core/misc/states.js

Drupal.behaviors.states = {
  attach: function (context, settings) {
  }
};

which assigns the fields as Dependants of the triggering input (in this case the select) has already been run. The ajax loaded file_managed field is then not assigned as a Dependent. Because of that, when the 'state:visible' event is triggered, the ajax loaded file_managed is uneffected.

The 'data-drupal-states' attribute is not being added to the ajax loaded file_managed input
With a file input instead of file managed, a 'data-drupal-states' attribute is added to the input with json encoded settings specifying which element the Dependent is dependent upon and when it should be made visible. This information is not available in the ajax loaded element, so even if triggered the attach function (above) again, it wouldn't know how to handle this input.

Possible solution
Perhaps we can attach the data-drupal-states directly to the ajax-wrapper container so regardless of what happens within the file_managed, we can be sure the states are obeyed. I am not sure if that might have other unintended consequences so perhaps the above two issues need to be addressed independently.

scott_euser’s picture

The attached patch follows my possible solution listed above and appears to correctly hide the managed file on load as well as on change of the field it depends upon.

scott_euser’s picture

Saphyel’s picture

Reviewed!

Saphyel’s picture

Status: Needs review » Reviewed & tested by the community
tstoeckler’s picture

Status: Reviewed & tested by the community » Needs work
  1. +++ b/core/modules/file/src/Element/ManagedFile.php
    @@ -348,8 +349,20 @@ public static function processManagedFile(&$element, FormStateInterface $form_st
    +    // Add states to ajax wrapper to states.js can potentially attach this
    

    The second "to" should be "so"

  2. +++ b/core/modules/file/src/Element/ManagedFile.php
    @@ -348,8 +349,20 @@ public static function processManagedFile(&$element, FormStateInterface $form_st
    +      // Add a preceeding space.
    +      $attributes = ' ' . $attribute;
    

    This should not be necessary, the Attribute class should be adding that. In fact I'm fairly sure there will be a double space currently.

scott_euser’s picture

Status: Needs work » Needs review
StatusFileSize
new1.73 KB
new865 bytes

Thanks both for the review! I have updated the patch based on your feedback tstoeckler; you're right, it does add the space already.
If you are happy with it, good to switch to 'reviewed & tested by the community'?

tstoeckler’s picture

Status: Needs review » Reviewed & tested by the community

I can't say anything about the JS changes, but other than that looks good. Since this was RTBC before, marking as such.

xjm’s picture

Status: Reviewed & tested by the community » Needs work
Issue tags: +Needs tests

Thanks everyone!

I think we should add a JS test for this, especially if it's a major bug. The states system is definitely something where JS tests help.

xjm’s picture

Oh and @Saphyel, when you review a patch, can you document what you reviewed and how? Code, manual testing, etc. Screenshots are always good for visual issues like this; see: https://www.drupal.org/contributor-tasks/add-screenshots

Thanks also @scott_euser for the careful explanations!

scott_euser’s picture

Assigned: Unassigned » scott_euser

@xjm Thanks! I will work on adding a JS test for it, probably tomorrow or Wednesday.

scott_euser’s picture

Assigned: scott_euser » Unassigned
Status: Needs work » Needs review
StatusFileSize
new6.36 KB
new3.9 KB

Updated with a javascript test.

scott_euser’s picture

Fixed docblocks in last patch. Interdiff to last major change as well to make it easier to review.

gambry’s picture

Version: 8.2.5 » 8.4.x-dev
Status: Needs review » Needs work
Issue tags: -Needs tests +SpringSprintLondon2017

Wonderful work, well done everyone!

Below my feedbacks.

  1. +++ b/core/modules/file/src/Element/ManagedFile.php
    @@ -352,8 +353,17 @@ public static function processManagedFile(&$element, FormStateInterface $form_st
    +    // Add states to ajax wrapper so states.js can potentially attach this
    +    // element as a Dependent.
    +    $attributes = '';
    +    if (isset($element['#states']) && !empty($element['#states'])) {
    +      $attributes = new Attribute([
    +        'data-drupal-states' => json_encode($element['#states']),
    +      ]);
    +    }
    +
         // Prefix and suffix used for Ajax replacement.
    -    $element['#prefix'] = '<div id="' . $ajax_wrapper_id . '">';
    +    $element['#prefix'] = '<div id="' . $ajax_wrapper_id . '"' . $attributes . '>';
    

    $attributes is first a string, then an Attribute() instance. Why don't we make it an Attribute() instance since definition, and maybe we create it with [id=$ajax_wrapper_id] and so print all prefix element attributes in the same way?

  2. +++ b/core/modules/file/tests/src/FunctionalJavascript/FileManagedStateTest.php
    @@ -0,0 +1,60 @@
    +  protected function setUp() {
    +    parent::setUp();
    +  }
    

    I don't think this is needed then, as it's overriding the parent::setUp() just to call it. :D

  3. +++ b/core/modules/file/file.js
    @@ -36,6 +36,10 @@
    +      $(document).trigger('state:visible');
    

    This looks to handle only the visible, so I tried some other states and something looks broken. Apparently all states are applied to the parent wrapper and not to the input element itself. So some states work (visible, invisible, disabled) but other like required don't.
    States changes should affect the element and not the parent.

ajaynimbolkar’s picture

Hi,

I have used Patch #14.

Following are my code snippet, When i apply patch then entire field set get disable.
When i check using firebug then i got to know that the fieldset has apply "display:none" attribute.

$form['test'] = [
'#title' => t('Login Button Settings'),
'#type' => 'details',
'#open' => TRUE,
];

// Login link type.
$form['test']['test1'] = [
'#type' => 'select',
'#options' => [
'' => t('- Select - '),
'text' => t('Text'),
'image' => t('Image'),
],
'#default_value' => $settings->get('o365_user_auth_login_type'),
'#title' => t('What type login link you want to show?'),
];

// Login link text.
$form['test']['test2'] = array(
'#type' => 'textfield',
'#title' => t('Login Link Text'),
'#default_value' => $settings->get('o365_user_auth_login_link_text'),
'#states' => [
'visible' => [':input[name="test[test1]"]' => ['value' => 'text']],
],
);

// Image link
$form['test']['test2'] = [
'#title' => t('Image Login Link'),
'#type' => 'managed_file',
'#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
'#default_value' => $settings->get('o365_user_auth_login_link_image'),
'#upload_location' => 'public://o365_user_auth/',
'#states' => [
'visible' => [
':input[name="test[test1]"]' => ['value' => 'image'],
],
],
];

please help me.

Thanks,
Ajay

shashikant_chauhan’s picture

Related issue, with working patch.
https://www.drupal.org/node/2871794

shashikant_chauhan’s picture

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.

scott_euser’s picture

Status: Needs work » Needs review
StatusFileSize
new6.88 KB
new4.06 KB

I've updated the patch so the state settings are applied to the element as well as wrapper. This now works for required, visible, and all other options. I've attempted to update the tests to cover required as well so we can see the two cases (where the wrapper needs to change + where the form element needs to change) - not sure if tests will pass though - need to get phantomjs working in my docker containers.

I've fixed the other feedback items, thank you for reviewing.

gambry’s picture

Hey @scott_euser have you seen work on the related issue?
Can we merge the two issues, and close the duplicate?

scott_euser’s picture

Hey @gambry, just took a look at it - seems to not be solving the whole issue. Have posted a comment there suggesting we close that.
Not sure if we should bring this bit into here:

diff --git a/core/modules/file/file.module b/core/modules/file/file.module
index a6fc3f6..d0bfe07 100644
--- a/core/modules/file/file.module
+++ b/core/modules/file/file.module
@@ -1220,7 +1220,6 @@ function file_managed_file_save_upload($element, FormStateInterface $form_state)
 function template_preprocess_file_managed_file(&$variables) {
   $element = $variables['element'];
 
-  $variables['attributes'] = [];
   if (isset($element['#id'])) {
     $variables['attributes']['id'] = $element['#id'];
   }
scott_euser’s picture

Have taken a look, that results in invalid html actually. Essentially results in this:

<div data-drupal-selector="edit-managed-file" data-drupal-states="{&quot;visible&quot;:{&quot;:input[name=\u0022toggle_me\u0022]&quot;:{&quot;checked&quot;:true}}}" id="edit-managed-file-upload" class="js-form-managed-file form-managed-file">
  <div id="ajax-wrapper" data-drupal-states="{&quot;visible&quot;:{&quot;:input[name=\&quot;toggle_me\&quot;]&quot;:{&quot;checked&quot;:true}}}"><input data-drupal-selector="edit-managed-file-upload" type="file" id="edit-managed-file-upload" name="files[managed_file]" size="22" class="js-form-file form-file" data-drupal-states="{&quot;visible&quot;:{&quot;:input[name=\u0022toggle_me\u0022]&quot;:{&quot;checked&quot;:true}}}">
    <input class="js-hide button js-form-submit form-submit" data-drupal-selector="edit-managed-file-upload-button" formnovalidate="formnovalidate" type="submit" id="edit-managed-file-upload-button" name="managed_file_upload_button" value="Upload">
    <input data-drupal-selector="edit-managed-file-fids" type="hidden" name="managed_file[fids]">
  </div>
</div>

Notice 2 id's 'edit-managed-file-upload' where there should of course only be one on the page.

scott_euser’s picture

Re-rolling without any change to file.js as that was a lingering change simply from saving the file (ie, code editor automatically added in new line at end of file that was missing), but no need to keep that in scope. Otherwise identical to #20. Ready for review.

wesleydv’s picture

Status: Needs review » Needs work

When a managed_file field is inside a fieldset, the entire fieldset is hidden when using visible or invisible states on the instead of just the field.
Have not tested this using other states.

I believe that @ajayNimbolkar in #16 is describing a similar issue while using 'details' as a wrapper instead of 'fieldset'.

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.

nwoodland’s picture

Patch from #24 is working great for me, thanks for all your work on this scott_euser!

jrockowitz’s picture

johannes-maximilian’s picture

I encountered this problem when creating a custom field widget where managed_file fields along others should be visible according to a select filed. Applying this patch made the whole custom field disappearing because states.js now changed the visibility of the entire fieldset. Because of state.js function $(e.target).closest('.js-form-item, .js-form-submit, .js-form-wrapper').toggle(e.value) the fieldset appeared als closest to the ajax-wrapper element. I discovered, that the upload element didn't had states by default. So for my needs, it was enough to add states to just the upload input element without the ajax wrapper, because states.js can still get the states of these elements and toggle them accordingly. I placed it right below the $element['upload'] definition, to keep it in line. Starting from line 303

        // The file upload field itself.
        $element['upload'] = [
            '#name'             => 'files[' . $parents_prefix . ']',
            '#type'             => 'file',
            '#title'            => t('Choose a file'),
            '#title_display'    => 'invisible',
            '#size'             => $element['#size'],
            '#multiple'         => $element['#multiple'],
            '#theme_wrappers'   => [],
            '#weight'           => -10,
            '#error_no_message' => true,
        ];
        if (!empty($element['#accept'])) {
            $element['upload']['#attributes'] = ['accept' => $element['#accept']];
        }
        // add #states to upload element
        if (isset($element['#states']) && !empty($element['#states'])) {
            $element['upload']['#states'] = $element['#states'];
        }

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.

aadeshvermaster@gmail.com’s picture

Hi Team,

I have checked patch #24 with Drupal 8.5.8 & PHP 7.2. Its working for me.

Thanks

meickol’s picture

I am using #states for in a node edit form, with this code

$form["field_ad_image"]["widget"][0]['#states'] = [
      'visible' => [
        ':input[name="field_interstitial_ad[value]"]' => ['checked' => TRUE]
      ],
      'required' => [
        ':input[name="field_interstitial_ad[value]"]' => ['checked' => TRUE]
      ]
    ];

Using the patch #24 the field `field_ad_image` get visible if the `field_interstitial_ad` is checked, if not get hidden, but with the required is not working right because the field get the required mark but anyway you can save the form without upload any image.

Drupal/core 8.6.4 , PHP 7.2.5

andrewmacpherson’s picture

Issue tags: +accessibility

tagging, relevant for WCAG guideline 3.3 Input assistance.

tim.plunkett’s picture

Issue tags: -SprintWeekend2017, -london_2017_january, -SpringSprintLondon2017, -accessibility (duplicate tag) +Accessibility

Fixing tags

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.

acrosman’s picture

Issue tags: +Needs reroll

Adding re-roll tag. Looks like the current patch does not apply to 8.8.

kostyashupenko’s picture

Status: Needs work » Needs review
Issue tags: -Needs reroll
StatusFileSize
new6.53 KB

Status: Needs review » Needs work

The last submitted patch, 37: states_not_affecting-2847425-37.patch, failed testing. View results

yury n’s picture

StatusFileSize
new6.91 KB

Patch #37 works for required state when field has no uploaded file. But with file uploaded 'upload' element is hidden and field label's 'for' points to nothing, so required state does not work. I made a label and states to refer to 'fids' element in this case.

P.S. You need a patch from https://www.drupal.org/project/drupal/issues/1091852 to have states working with AJAX elements

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.

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.

abu-zakham’s picture

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

I have re-rolled patch #39, and removed core from info file to fix core_version_requirement issue.

gauravvvv’s picture

StatusFileSize
new6.91 KB
new526 bytes

Re-rolled patch #44, Updating prefix for dependencies.
Added interdiff for same.

Status: Needs review » Needs work

The last submitted patch, 45: 2847425-45.patch, failed testing. View results

vsujeetkumar’s picture

Status: Needs work » Needs review
StatusFileSize
new6.9 KB
new726 bytes

Fixed the fail tests.
Changed Class "Drupal\FunctionalJavascriptTests\JavascriptTestBase" to "Drupal\FunctionalJavascriptTests\WebDriverTestBase".

Status: Needs review » Needs work

The last submitted patch, 47: 2847425-47.patch, failed testing. View results

vsujeetkumar’s picture

Status: Needs work » Needs review
StatusFileSize
new6.98 KB
new632 bytes

Fixed the fail tests. Added "$defaultTheme" and "$modules" property changed to protected.

evamtinez’s picture

Patch #24 is working for me in Drupal 8.9.16 and PHP 7.1.

berramou’s picture

Patch #24 is working for me with Drupal 9.2.9 and PHP 7.4 for require state.

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.

samaphp’s picture

Status: Needs review » Reviewed & tested by the community
quietone’s picture

Status: Reviewed & tested by the community » Needs work
Issue tags: +Needs issue summary update, +Needs reroll, +Bug Smash Initiative, +Needs steps to reproduce

Doing a review.

The Issue Summary begins with a statement that this issue is identical to another one, and the one has been fixed. I am not sure what this issue is fixing. Tagging for an issue summary update, see Write an issue summary for an existing issue for guidance.

There was a gap between Sept 2019 and July 2021 after which there have been rerolls only and no code reviews. The last code review was in #15, in May 2017.

This patch no longer applies, tagging for a reroll.

I applied the patch so I could run the test but then I saw it was a FunctionalJavascript test which I am not set up for. So I followed the steps by hand. I installed the test module and navigated to the form. The toggle button had no effect so I stopped. Because of that I am adding a tag for steps to reproduce.

Not sure if this should be Major, but leaving for now.

anushrikumari’s picture

StatusFileSize
new10.25 KB

Re-roll patch #47 for 9.4.x-dev

ravi.shankar’s picture

StatusFileSize
new10.26 KB
new651 bytes

Fixed failed test of patch #55.

ravi.shankar’s picture

StatusFileSize
new10.3 KB
new731 bytes

Fixed failed tests of patch #56.

gauravvvv’s picture

Status: Needs work » Needs review
Narendra@drupalchamp’s picture

hi, There
I am using drupal 9.2.7 and i have an issue with managed_file. I used a custom form with managed_file, it creates a directory and uploads the document but in submitForm function, it gives only a "blank array". there are no details about fid, file type, size, etc on submit function. i am using $form_state->getValues('file_name'); as below code-

$form['select_file'] = [
'#type' => 'managed_file',
'#title' => $this->t('choose file'),
'#multiple' => FALSE,
'#description' => t("Document should be in .jpeg, .jpg, .png, .gif, .txt, .docx and .pdf format!"),
'#upload_location' => 'public://Applicant-file/applicant_'.$id.'',
'#upload_validators' => array
(
'file_validate_extensions' => array('pdf jpg jpeg png gif txt docx '),
'file_validate_size' => array(25600000),
),
];

public function submitForm(array &$form, FormStateInterface $form_state) {
$select_file = $form_state->getValue('select_file');
................................
................................
}

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.

damienmckenna’s picture

Issue summary: View changes
Status: Needs review » Needs work
Related issues: +#1118016: conditional visibility of a managed_file using #states attribute does not work

Slight update to the issue summary to note that while this may have been working in #1118016, it doesn't work right now.

ameymudras’s picture

Status: Needs work » Needs review
StatusFileSize
new27.55 KB
new233.99 KB
new172.58 KB

Reviewed the code and tested the patch on 9.5.x

- The patch applies cleanly
- All the issues mentioned above are already taken care off
- Tests pass, would be good to add test only patch
- states work as expected after the patch is applied

+1 for RTBC

damienmckenna’s picture

@ameymudras: Did you actually test to see if the field worked correctly, i.e. that you could not submit a form without selecting a file?

ameymudras’s picture

Status: Needs review » Needs work

@DamienMcKenna I had tested the form submit without adding a file which worked fine. I tested again and noticed an issue:

- When we select Audio, file is marked as required with asterisks but it lets me submit the form. As in the required field is not respected here.

dww’s picture

Status: Needs work » Needs review
Issue tags: -Needs reroll
StatusFileSize
new5.22 KB
new6.95 KB
new3.45 KB

I reverted a bunch of hunks from #57 that were out of scope code style and other refactoring. Here's a patch with only the actually necessary parts of it, both test-only (fails locally) and full (passes). No longer needs reroll.

Re: #64:

- When we select Audio, file is marked as required with asterisks but it lets me submit the form. As in the required field is not respected here.

This is why I think #states should drop support for toggling required. As documented, this #states toggle has nothing to do with form validation. It literally just paints or erases your little red * next to the field. 😂 That's it. This "works as designed".

Back to NR.

Thanks! -Derek

The last submitted patch, 65: 2847425-65.test-only.patch, failed testing. View results

rcodina’s picture

Patch on #65 works for me on Drupal 9.3.19. Thanks!

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.

joekers’s picture

Patch from #65 is working for me too - on 9.4.4. Cheers!

ameymudras’s picture

Status: Needs review » Reviewed & tested by the community

Reviewed the code and tested the patch on 9.5.x

- The patch #65 applies cleanly
- Issue summary is clear and explains the problem
- Was able to replicate the issue with the code snippet provided in summary
- After applying the patch field works correctly and was able to submit the form
- Did a quick code review and no issues were identified

Marking this issue as RTBC unless there are anything else pending here. Not including screenshots to avoid duplicate ones

quietone’s picture

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

@ameymudras, thanks for reviewing this patch. To answer your question, yes there is more work to do here. Have a look at the tags, this issues is tagged for a summary update and for steps to reproduce. That was asked for in #54, 10 months ago and has yet to be done.

Setting back to NW for an issue summary update. At the very least the proposed resolution needs to be completed to explain the agreed solution so that any other reviewers and the committers know what should be implemented. Steps to repI've added the standard template to make it a bit easier. It shouldn't take too long for someone to update.

mgifford’s picture

Issue tags: +wcag331

Think this is most closely tied to 3.3.1.

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.

tim-diels’s picture

Using Drupal 10.0.9

When putting these inside a fieldset, the fieldset is targetted and set to display none when changing the values.
It does work without a fieldset. So the test and code should be updated to also address this issue.

mgifford’s picture

Yes, we really want to avoid using display:none; unless we really want it to be invisible to everyone including screen reader users.

piotrkonefal’s picture

The same issue seems to be occurring on Webforms. Conditional logic options based on state of `managed_file` field does not seem to work.
Steps to reproduce:

  1. Create a webform with a file field.
  2. In Webform configuration (Build > Elements section), choose 'Edit' option for 'Submit button(s)'.
  3. Switch to 'Conditions' tab.
  4. Set a condition as: Visible - If - File Field (is) - Filled
  5. Save webform settings.
  6. Go to the webform. Observe that submit button is hidden, based on configured condition.
  7. Upload a file - see that 'Submit' button is still NOT visible (but it should be)

There is a working workaround for that scenario:
1. Add custom webform handler and use it on affected webform.
2. Define alterForm() method and build conditional visibility there.
Example:

$form['elements']['actions']['#states'] = [
      'visible' => [
          '.webform-submission-activity-tasks-form :input[data-drupal-selector="edit-presentation-fids"]' => ['filled' => TRUE],
      ],
    ];

In terms of Webforms there is another issue I've caught which is related to this one. I've created a separate thread: https://www.drupal.org/project/webform/issues/3399906#comment-15308665

er.garg.karan’s picture

The patch #65 not working for me when I am trying to add a #required state.
Drupal version 9.5.9

adwivedi008’s picture

Patch #65 works for me i am using it on D-9.5

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

sukr_s’s picture

Issue summary: View changes

sukr_s’s picture

Status: Needs work » Needs review

- Issue summary has been updated.
- Root cause of #1118016: conditional visibility of a managed_file using #states attribute does not work not working has been identified and fixed. Different from the patch.
- Test case reused from #2847425-65: #states not affecting visibility/requirement of managed_file and included.

smustgrave’s picture

Status: Needs review » Needs work

Reviewing the proposed solution seems to describe the problem or steps to reproduce vs what the fix was. So leaving both issue summary and steps to reproduce tags.

Also some comments on the MR.

sukr_s’s picture

Issue summary: View changes
Status: Needs work » Needs review

- Updated the IS
- Updated the proposed changes

smustgrave’s picture

mahde’s picture

Patch #65 only allows to add the red asterisk next to the upload field but I can submit without uploading any file.

kim.pepper’s picture

Status: Needs review » Needs work

NW for #86

sukr_s’s picture

Status: Needs work » Needs review

required in #states only places a * label against the field. It does not do any validation. It's designed as such. see #65. Please open a new ticket for implementing mandatory check when required is set in #states.

smustgrave’s picture

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

If follow up is needed it should be created but #65 also mentions this may be works as designed.

sukr_s’s picture

@smustgrave there are two issues here
1. visibility i.e. hide / show does not work like other fields. This is a bug and has been fixed in the MR.
2. required does not perform the mandatory check. This is mentioned as "works as designed". Therefore I suggested to open a new ticket for performing required validation in 88.

if it's agreed to open a new ticket for required validation, the title & problem needs to be updated and a new ticket needs to be opened.

sboden’s picture

Patch #65 does something weird to drupal/webform 6.2.2. Without the patch my app using webform works fine (behat unit tests). After applying the patch webform seems to miss a button. Remove the patch, all is ok again. It's weird, since there are no managed files in the webform.

Update:
Patch #65 will need a reroll for Drupal 10.1.3. When you apply patch #65 to Drupal 10.1.3 you will end up with

Fatal error: Cannot use Drupal\Core\Template\Attribute as Attribute because the name is already in use in www/core/modules/file/src/Element/ManagedFile.php on line 19

since Drupal 10.1.3 already added use Drupal\Core\Template\Attribute on a different line, and after the patch you have a duplicate use statement.

sboden’s picture

StatusFileSize
new6.69 KB

Patch #65 rerolled for Drupal 10.3.1 (I guess >= 10.3)

ewout goosmann’s picture

StatusFileSize
new6.98 KB

Reroll of patch #92, because the Attribute class was not imported and caused the following error:

Error: Class "Drupal\file\Element\Attribute" not found in Drupal\file\Element\ManagedFile::processManagedFile() (line 380 of core/modules/file/src/Element/ManagedFile.php).

eduardo morales alberti’s picture

As work around it can be hidden by:

    $form['files_container'] = [
      '#type' => 'container',
      '#states' => [
        'visible' => [
          ':input[id="edit-subject"]' => [
            ['value' => $this->t('Question')],
            'or',
            ['value' => $this->t('Complaint')],
          ],
        ],
      ],
    ];

    $form['files_container']['images'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Choose an image (jpg/png)'),
      '#description' => $this->t('You may select up to 5 files.'),
      '#multiple' => TRUE,
      '#upload_validators' => [
        'file_validate_extensions' => ['png jpg jpeg'],
        'file_validate_size' => ['4194304'],
      ],
      '#cardinality' => 5,
    ];

prudloff changed the visibility of the branch 2847425-states-not-affecting to hidden.

prudloff’s picture

Status: Needs work » Needs review
Issue tags: -Needs followup
Related issues: +#3513308: Required attribute on file inputs not working

I created the followup issue for required not working on file inputs: #3513308: Required attribute on file inputs not working

I also incorporated changes from the latest patch into the MR.

smustgrave’s picture

Status: Needs review » Reviewed & tested by the community
Issue tags: +Needs Review Queue Initiative

Believe all feedback has been resolved on this one. Test coverage is failing in 2 spots https://git.drupalcode.org/issue/drupal-2847425/-/jobs/4682940

IS seems to line up to me.

LGTM

prudloff’s picture

If this gets committed, we might need to reopen #3213580: File upload fields are not working through conditionnal logic.

kim.pepper’s picture

Ran the test-only job and confirmed it fails.

quietone’s picture

Status: Reviewed & tested by the community » Needs work

I skimmed the comments and didn't find unanswered questions. On reading the MR I made one suggestion to a comment and left some questions, all pretty simple. I would usually just accept the suggestion but since there were some questions I left that for now. Because of the questions, setting this to NW.

xjm’s picture

Amending attribution.

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.

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