TypeError: strpos(): Argument #1 ($haystack) must be of type string, Drupal\Core\Url given in strpos() (line 358 of /core/lib/Drupal/Component/Utility/UrlHelper.php)

Created on 2 June 2023, almost 2 years ago
Updated 8 February 2024, about 1 year ago

Problem/Motivation

When I call the build method

public function build(): array {
    if (!$simple_block = $this->getEntity()) {
      return [
        '#markup' => $this->t('Simple block with ID %id does not exist. <a href=":url">Add simple block</a>.', [
          '%id' => $this->getDerivativeId(),
          ':url' => Url::fromRoute('simple_block.form_add'),
        ]),
        '#access' => $this->currentUser->hasPermission('administer blocks'),
      ];
    }

    $content = $simple_block->getContent();
    return [
      '#type' => 'processed_text',
      '#text' => $content['value'],
      '#format' => $content['format'],
      '#contextual_links' => [
        'simple_block' => [
          'route_parameters' => ['simple_block' => $simple_block->id()],
        ],
      ],
    ];
  }

, if the simple block does not exist, the return value contains a Url object instead of a string, which will cause drupal core to throw a TypeError: strpos(): Argument #1 ($haystack) must be of type string, Drupal\Core\Url given in strpos() (line 358 of /core/lib/Drupal/Component/Utility/UrlHelper.php)

Steps to reproduce

Proposed resolution

Convert Url object to string Url::fromRoute('simple_block.form_add')->toString()

Remaining tasks

User interface changes

API changes

Data model changes

🐛 Bug report
Status

Fixed

Version

1.0

Component

Code

Created by

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