Validating managed files should account for null triggering elements

Created on 20 September 2017, about 7 years ago
Updated 20 March 2023, over 1 year ago

Problem/Motivation

When programmatically submitting forms, I noticed the logs filling up with the following warning:

Warning: end() expects parameter 1 to be array, null given in Drupal\file\Element\ManagedFile::validateManagedFile() (line 404 of
/core/modules/file/src/Element/ManagedFile.php)

This is because of the following code:

  /**
   * Render API callback: Validates the managed_file element.
   */
  public static function validateManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {
    // If referencing an existing file, only allow if there are existing
    // references. This prevents unmanaged files from being deleted if this
    // item were to be deleted.
    $clicked_button = end($form_state->getTriggeringElement()['#parents']);

According to the FormStateInterface, a valid return value for getTriggeringElement() is null:

  /**
   * Gets the form element that triggered submission.
   *
   * @return array|null
   *   The form element that triggered submission, of NULL if there is none.
   */
  public function &getTriggeringElement();

In the case of my programmatic submission, the call to getTriggeringElement() returns null (again, this is valid according to the interface), which is then passed to php's end function, which expects an array.

One potential solution is below (patch to come):

    $triggering_element = $form_state->getTriggeringElement();
    $clicked_button = $triggering_element ? end($triggering_element['#parents']) : '';

Steps to reproduce

- Install and enable webform 8.x-5.0-beta13
- Create a webform with an element for attachments (i.e. managed_file element)
- Write code to submit a webform programmatically as seen in the webform cookbook β†’ .
- Submit the form programmatically

Note: This should happen with any programmatic form submission with a managed_file element, my entry point just happened to be through the webform module.

Expected behavior:
- Submission validated or created without PHP warnings.

What happened instead:
- PHP warning described below observed.

This issue was observed on:
- macOS Sierra 10.12.2
- Drupal 8.3.7 instance of Core, but see that it still exists in 8.5.x.

Proposed resolution

Remaining tasks

Add a test
review
commit

User interface changes

API changes

Data model changes

Release notes snippet

πŸ› Bug report
Status

Fixed

Version

9.5

Component
File moduleΒ  β†’

Last updated 3 days ago

Created by

πŸ‡ΊπŸ‡ΈUnited States malik.kotob

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024