The link formatter option for the email field does not work

Created on 14 April 2025, 11 days ago

Problem/Motivation

If you set up a custom field of type email and save it with a value, it throws an error like this:

Error: Object of class Drupal\Core\Url could not be converted to string in array_unique() (line 73 of /.../web/core/lib/Drupal/Core/Template/AttributeArray.php)

Steps to reproduce

1. I set up a custom field on an article content type with 2 subfields (email and url, for testing purposes)
2. After saving the content with a value the error above is shown.

Proposed resolution

The problem is with this line:
'#url' => Url::fromUri('mailto:' . $value),
in the MailToFormatter.php.

I've temporarily changed the function like below, but its probably not the most optimal solution:

public function formatValue(FieldItemInterface $item, $value) {
    // Check if email is valid.
    if (empty($value) || !filter_var($value, FILTER_VALIDATE_EMAIL)) {
      return ['#markup' => Html::escape($value ?: '')];
    }

    // Render as a plain HTML mailto link to avoid Url object issues.
    $email = Html::escape($value);
    return [
      '#markup' => '<a href="mailto:' . $email . '">' . $email . '</a>',
    ];
  }

Additionally removed the Drupal\Core\Url; class and added the use Drupal\Component\Utility\Html class.

🐛 Bug report
Status

Active

Version

3.1

Component

Code

Created by

🇮🇪Ireland marksmith

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

Comments & Activities

Production build 0.71.5 2024