ContentTranslationHandler::entityFormAlter doesn't handle entities with null labels

Created on 11 November 2024, about 1 month ago

Problem/Motivation

The signature for EntityInterface::label():

/**
* Gets the label of the entity.
*
* @return string|\Drupal\Core\StringTranslation\TranslatableMarkup|null
* The label of the entity, or NULL if there is no label defined.
*/
public function label();

It allows an entity to return NULL as a label, which basically means that the entity does not have a label at all.

ContentTranslationHandler::entityFormAlter has this line:

        $t_args = ['%language' => $languages[$form_langcode]->getName(), '%title' => $entity->label(), '@title' => $title];

But since this change in Drupal 11, it is not allowed to use a NULL value as an argument value. That means these pages become unavailable because of this.

The website encountered an unexpected error. Try again later.

TypeError: Drupal\Component\Utility\Html::escape(): Argument #1 ($text) must be of type string, null given, called in /var/www/html/web/core/lib/Drupal/Component/Render/FormattableMarkup.php on line 256

Steps to reproduce

Create an entity without a label.
Go to translate it.

Proposed resolution

Change the code to handle null labels, perhaps something like this?

     $label = $entity->label() ?? $entity->getEntityType()->getSingularLabel();
     $t_args = ['%language' => $languages[$form_langcode]->getName(), '%title' => $label, '@title' => $title];

Remaining tasks

* Agree on approach
* Write test
* Update code

User interface changes

none

Introduced terminology

none

API changes

none

Data model changes

none

Release notes snippet

none

🐛 Bug report
Status

Active

Version

11.1 🔥

Component

content_translation.module

Created by

🇬🇧United Kingdom nicrodgers Monmouthshire, UK

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

Merge Requests

Comments & Activities

Production build 0.71.5 2024