Problem/Motivation
When an empty string is used in the replace
key of the core machine_name
form element, it causes a PHP warning to appear in logs:
Warning: preg_match(): Compilation failed: nothing to repeat at offset 1 in /var/www/html/docroot/core/lib/Drupal/Core/Render/Element/MachineName.php on line 240
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21...
Notably it still works, but the warning is due to an assumption that a character will be set.
Steps to reproduce
Create a custom form with a machine_name
element that is configured to replace invalid characters with an empty string. For example, this element creates a subdomain
from another site_name
textfield element. Domains cannot include underscores (the default machine name replace character), so this element serves to remove invalid characters.
$form['subdomain'] = [
'#type' => 'machine_name',
'#title' => $this->t('Subdomain'),
'#machine_name' => [
'exists' => [$this, 'subdomainExists'],
'label' => $this->t('Subdomain'),
'source' => ['site_name'],
'replace_pattern' => '[^a-z0-9-]+',
'replace' => '',
'error' => $this->t('The subdomain can only contain letters, numbers, and dashes.'),
],
];
<code>
<h3 id="summary-proposed-resolution">Proposed resolution</h3>
Add an <code>empty()
check before the preg_match()
(see attached patch).
Remaining tasks
Open a merge request with a fix.- Add tests.
User interface changes
None.
Introduced terminology
None.
API changes
None.
Data model changes
None.
Release notes snippet
TBD