FormStateInterface::setError $message parameter does not match core implementations

Created on 7 July 2023, over 1 year ago
Updated 29 January 2024, 12 months ago

Problem/Motivation

While checking the Glossary 2 module with phpstan, I noticed a warning about the setError method.

FormStateInterface::setError() is defined as:

  /**
   * ...snip..
   * @param string $message
   *   (optional) The error message to present to the user.
   * ...snip..
   */
  public function setError(array &$element, $message = '');

However, most (82) implementations in core actually take a TranslatableMarkup for the $message parameter.

The 23 exceptions are:

  • web/core/lib/Drupal/Core/Form/FormStateInterface.php specifies the default as "", being self-consistent
  • web/core/lib/Drupal/Core/Form/FormState.php specifies the default as ""
  • web/core/lib/Drupal/Core/Form/FormStateDecoratorBase.php specifies the default as ""
  • web/core/tests/Drupal/Tests/Core/Form/FormStateTest.php passes 'Fail'
  • web/core/modules/settings_tray/tests/modules/settings_tray_test/src/Plugin/Block/ValidationErrorBlock.php passes 'Sorry system error. Please save again.'
  • web/core/modules/responsive_image/src/ResponsiveImageStyleForm.php passes 'Provide a value for the sizes attribute.' and 'Select at least one image style.', which looks like they should actually be translated
  • 16 cases of pass variables, like web/core/modules/views/src/Plugin/views/display/PathPluginBase.php passing an $error, which is actually always a TranslatableMarkup.

Steps to reproduce

Compare the outputs of

  • grep -irE "setError\([^\)]" web/core | cut -c1-180 | grep -E '(this->t|this->formatPlural| t|new TranslatableMarkup)\('
  • grep -irE "setError\([^\)]" web/core | cut -c1-180 | grep -vE '(this->t|this->formatPlural| t|new TranslatableMarkup)\('

Proposed resolution

  • Modify setError to match what code actually does: update the PHPdoc to @param Drupal\Core\StringTranslation $error

Remaining tasks

Decide on how to change the non-TranslatableMarkup calls. Most of them appear to be in tests or missing translations (ResponsiveImageStyle).

User interface changes

None.

API changes

If it is just a phpdoc, none. If we type the return value, it may qualify as an API change, but one that matches core implementations, and those implementations I looked at in contrib.

Data model changes

None.

Release notes snippet

None.

🐛 Bug report
Status

Needs work

Version

10.1

Component
Form 

Last updated about 6 hours ago

Created by

🇫🇷France fgm Paris, France

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

Comments & Activities

Production build 0.71.5 2024