If the field is #disabled then pass #default_value in valueCallback

Created on 17 November 2024, about 1 month ago

Problem/Motivation

If you use this field element in Form API and set it as #disabled, when the form submits, the #default_value is not passed, so the value is empty in the form submit handler.

Steps to reproduce

  1. Create a form using this field using Form API
  2. set a default value on the field and disable the field
  3. when you submit the form look at the form_state, and the value submitted for this field will be empty.

Proposed resolution

Pass the #default_value in the valueCallback method in PhoneInternationalElement class.

🐛 Bug report
Status

Active

Version

3.3

Component

Code

Created by

🇬🇧United Kingdom joehuggans Harrogate, UK

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

Merge Requests

Comments & Activities

  • Issue created by @joehuggans
  • 🇬🇧United Kingdom joehuggans Harrogate, UK

    I have looked at how other elements in Drupal core handle this such as the Number field, and based on this, I propose changing the valueCallback to:

      public static function valueCallback(&$element, mixed $input, FormStateInterface $form_state): mixed {
    
        if (!empty($input['full_number'])) {
          return $input['full_number'];
        } elseif (!empty($element['#default_value'])) {
          return $element['#default_value'];
        }
    
        return NULL;
      }
    
  • Pipeline finished with Failed
    about 1 month ago
    Total: 163s
    #341344
  • 🇬🇧United Kingdom joehuggans Harrogate, UK

    Patch for anyone who needs this in the meantime.

  • Pipeline finished with Failed
    about 1 month ago
    Total: 174s
    #345537
  • 🇬🇧United Kingdom joehuggans Harrogate, UK

    My first suggestion wasn't working and was causing an error.

    rather than using !empty($input['full_number']), use isset($input['full_number']), otherwise the field will fallback to the default value if the field is left empty.

Production build 0.71.5 2024