Skip to content

Commit 3860286

Browse files
committed
LabelDecorator: Allow to customize id generation
1 parent d94df4c commit 3860286

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/FormDecoration/LabelDecorator.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ class LabelDecorator implements FormElementDecoration, DecoratorOptionsInterface
2525
/** @var string|string[] CSS classes to apply */
2626
protected string|array $class = 'form-element-label';
2727

28+
/** @var callable A callback used to generate a unique ID based on the element name */
29+
private $uniqueName = 'uniqid';
30+
2831
/**
2932
* Get the css class(es)
3033
*
@@ -69,7 +72,7 @@ public function decorateFormElement(DecorationResult $result, FormElement $formE
6972
if ($isHtmlElement && ! $formElement instanceof RadioElement) {
7073
$elementAttributes = $formElement->getAttributes();
7174
if (! $elementAttributes->has('id')) {
72-
$elementAttributes->set('id', uniqid('form-element-'));
75+
$elementAttributes->set('id', call_user_func($this->uniqueName, $formElement->getName()));
7376
}
7477

7578
$attributes['for'] = $elementAttributes->get('id')->getValue();
@@ -101,5 +104,12 @@ protected function getElementLabel(FormElement $formElement): ?ValidHtml
101104
protected function registerAttributeCallbacks(Attributes $attributes): void
102105
{
103106
$attributes->registerAttributeCallback('class', null, $this->setClass(...));
107+
$attributes->registerAttributeCallback(
108+
'uniqueName',
109+
null,
110+
function ($callback) {
111+
$this->uniqueName = $callback;
112+
}
113+
);
104114
}
105115
}

tests/FormDecorator/LabelDecoratorTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public function testAttributeForAlwaysExists(): void
6565
new TextElement('test', ['label' => 'Label Here'])
6666
);
6767

68-
$this->assertStringContainsString('for="form-element-', $results->assemble()->render());
68+
$this->assertMatchesRegularExpression('/for="test[^"]+"/', $results->assemble()->render());
6969
}
7070

7171
public function testWithLabelAndIdAttribute(): void

0 commit comments

Comments
 (0)