#states not affecting visibility/requirement of managed_file

Created on 27 January 2017, almost 8 years ago
Updated 18 September 2024, 2 months ago

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

🐛 Bug report
Status

Needs work

Version

11.0 🔥

Component
File system 

Last updated about 10 hours ago

Created by

🇺🇸United States bander2

Live updates comments and jobs are added and updated live.
  • Accessibility

    It affects the ability of people with disabilities or special needs (such as blindness or color-blindness) to use Drupal.

Missing content requested by

🇦🇺Australia dpi
12 months ago
Sign in to follow issues

Merge Requests

Comments & Activities

  • Issue created by @bander2
  • 🇬🇧United Kingdom scott_euser

    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.

  • 🇬🇧United Kingdom scott_euser

    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.

  • 🇬🇧United Kingdom Saphyel

    Reviewed!

  • 🇩🇪Germany tstoeckler Essen, Germany
    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.

  • 🇬🇧United Kingdom scott_euser

    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'?

  • 🇩🇪Germany tstoeckler Essen, Germany

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

  • 🇺🇸United States xjm

    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.

  • 🇺🇸United States xjm

    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!

  • 🇬🇧United Kingdom scott_euser

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

  • 🇬🇧United Kingdom scott_euser

    Updated with a javascript test.

  • 🇬🇧United Kingdom scott_euser

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

  • 🇮🇹Italy gambry Milan

    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.

  • 🇮🇳India ajayNimbolkar

    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

  • 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 .

  • 🇬🇧United Kingdom scott_euser

    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.

  • 🇮🇹Italy gambry Milan

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

  • 🇬🇧United Kingdom scott_euser

    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'];
       }
  • 🇬🇧United Kingdom scott_euser

    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.

  • 🇬🇧United Kingdom scott_euser

    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.

  • 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 .

  • 🇧🇪Belgium wesleydv

    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'.

  • 🇺🇸United States nwoodland

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

  • 🇺🇸United States jrockowitz Brooklyn, NY
  • 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 .

  • 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'];
            }
    
  • Hi Team,

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

    Thanks

  • 🇨🇴Colombia meickol

    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

  • 🇬🇧United Kingdom andrewmacpherson

    tagging, relevant for WCAG guideline 3.3 Input assistance.

  • 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 .

  • 🇺🇸United States tim.plunkett Philadelphia

    Fixing tags

  • 🇺🇸United States acrosman South Carolina, US

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

  • 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 .

  • 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 .

  • 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 .

  • 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 .

  • 🇧🇾Belarus Yury N

    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 🐛 Display Bug when using #states (Forms API) with Ajax Request Needs work to have states working with AJAX elements

  • 🇯🇴Jordan abu-zakham

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

  • 🇮🇳India gauravvvv Delhi, India

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

  • 🇮🇳India vsujeetkumar Delhi

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

  • 🇮🇳India vsujeetkumar Delhi

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

  • 🇪🇸Spain evamtinez

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

  • 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 .

  • 🇫🇷France berramou

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

  • 🇸🇦Saudi Arabia samaphp Riyadh, SA 🇸🇦
  • 🇳🇿New Zealand quietone

    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.

  • 🇮🇳India anushrikumari

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

  • Fixed failed test of patch #55.

  • Fixed failed tests of patch #56.

  • 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 .

  • 🇮🇳India Narendra@drupalchamp

    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');
    ................................
    ................................
    }

  • 🇺🇸United States DamienMcKenna NH, USA

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

  • 🇮🇳India ameymudras

    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

  • 🇺🇸United States DamienMcKenna NH, USA

    @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?

  • 🇮🇳India ameymudras

    @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.

  • 🇺🇸United States dww

    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

  • 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 .

  • 🇪🇸Spain rcodina Barcelona

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

  • 🇬🇧United Kingdom joekers UK

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

  • 🇮🇳India ameymudras

    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

  • 🇳🇿New Zealand quietone

    @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.

  • 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 .

  • 🇨🇦Canada mgifford Ottawa, Ontario

    Think this is most closely tied to 3.3.1.

  • 🇧🇪Belgium tim-diels Belgium 🇧🇪

    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.

  • 🇨🇦Canada mgifford Ottawa, Ontario

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

  • 🇵🇱Poland piotrkonefal

    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 🐛 Conditional logic options are not getting saved Active

  • 🇮🇳India er.garg.karan Chandigarh

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

  • 🇮🇳India adwivedi008

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

  • First commit to issue fork.
  • Merge request !7305support for #states for managed_file → (Open) created by sukr_s
  • Pipeline finished with Failed
    8 months ago
    Total: 177s
    #136162
  • Pipeline finished with Failed
    8 months ago
    Total: 630s
    #136183
  • Pipeline finished with Failed
    8 months ago
    Total: 580s
    #136228
  • Pipeline finished with Success
    8 months ago
    Total: 648s
    #136266
  • Status changed to Needs review 8 months ago
  • 🇮🇳India sukr_s

    - 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.

  • Status changed to Needs work 7 months ago
  • 🇺🇸United States smustgrave

    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.

  • Pipeline finished with Canceled
    7 months ago
    Total: 225s
    #143587
  • Pipeline finished with Success
    7 months ago
    Total: 604s
    #143597
  • Status changed to Needs review 7 months ago
  • 🇮🇳India sukr_s

    - Updated the IS
    - Updated the proposed changes

  • 🇺🇸United States smustgrave

    cleaning tags.

  • 🇨🇦Canada mahde Vancouver

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

  • Status changed to Needs work 6 months ago
  • 🇦🇺Australia kim.pepper 🏄‍♂️🇦🇺Sydney, Australia

    NW for #86

  • Pipeline finished with Failed
    5 months ago
    Total: 1009s
    #195243
  • Pipeline finished with Success
    5 months ago
    Total: 540s
    #195268
  • Status changed to Needs review 5 months ago
  • 🇮🇳India sukr_s

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

  • Status changed to Needs work 4 months ago
  • 🇺🇸United States smustgrave

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

  • 🇮🇳India sukr_s

    @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 🐛 #states not affecting visibility/requirement of managed_file Needs work .

    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.

  • 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.

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

  • 🇳🇱Netherlands Ewout Goosmann

    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).

  • 🇪🇸Spain eduardo morales alberti Spain, 🇪🇺

    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,
        ];
    
Production build 0.71.5 2024