Programmatic setting of default value can throw fatal error

Created on 12 March 2025, 28 days ago

Problem/Motivation

Programmatic display of field form triggers error.

I have a custom module that invokes various fields. When it gets to the name, it throws an error:

TypeError: Unsupported operand types: null + array in Drupal\name\Element\Name::valueCallback() (line 125 of ..../modules/contrib/name/src/Element/Name.php).

Steps to reproduce

Programmatically attempt to set a default value for the name field.

Proposed resolution

The problem appears at line 124. I believe this method of concatenating arrays leads to no entry in this case

    if ($input === FALSE) { 
      $element += ['#default_value' => []]; 
      return $element['#default_value'] + $value;
    }

If instead we were to say

 $element['#default_value'] =[];

the problem goes away.

Remaining tasks

Make the change, test, and commit

User interface changes

none

API changes

none

Data model changes

none

πŸ› Bug report
Status

Active

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States Cayenne

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

Comments & Activities

  • Issue created by @Cayenne
  • πŸ‡¨πŸ‡¦Canada Liam Morland Ontario, CA πŸ‡¨πŸ‡¦

    Please provide your suggested change in a merge request. It would be great if you can add a test that surfaces this problem.

  • πŸ‡ΊπŸ‡ΈUnited States bluegeek9

    The error happens when $element is NULL.

    The proposed change does not work like the existing code.

    In the existing code , any '#default_value' already set will be preserved.

  • πŸ‡ΊπŸ‡¦Ukraine Tyapchyc

    @cayenne Could you provide an example of your custom code?

    The next code works fine.

        $form['name_field'] = [
          '#type' => 'name',
          '#default_value' => [],
        ];
    

    or

        $form['name_field'] = [
          '#type' => 'name',
          '#default_value' => [
            'given' => 'Default given',
          ],
        ];
    

    Thanks.

Production build 0.71.5 2024