Skip to content

Commit 39b202c

Browse files
committed
BaseControl: added ability to multiple forms with different HTML ID [Closes #188]
Solution: set Nette\Forms\Controls\BaseControl::$idMask = 'frm-%2$s-%1$s';
1 parent d6c0f2c commit 39b202c

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

src/Forms/Controls/BaseControl.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,8 @@ public function setHtmlId($id)
336336
public function getHtmlId()
337337
{
338338
if (!isset($this->control->id)) {
339-
$this->control->id = sprintf(self::$idMask, $this->lookupPath());
339+
$form = $this->getForm(false);
340+
$this->control->id = sprintf(self::$idMask, $this->lookupPath(), $form ? $form->getName() : '');
340341
}
341342
return $this->control->id;
342343
}

tests/Forms/Forms.idMask.phpt

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Forms\Controls\TextInput;
6+
use Nette\Forms\Form;
7+
use Tester\Assert;
8+
9+
10+
require __DIR__ . '/../bootstrap.php';
11+
12+
13+
Assert::exception(function () {
14+
$input = new TextInput('name');
15+
$input->getHtmlId();
16+
}, Nette\InvalidStateException::class, "Component '' is not attached to ''.");
17+
18+
19+
test(function () {
20+
$container = new Nette\Forms\Container;
21+
$container->setParent(null, 'second');
22+
$input = $container->addText('name');
23+
Assert::same('frm-name', $input->getHtmlId());
24+
});
25+
26+
27+
test(function () {
28+
$form = new Form;
29+
$container = $form->addContainer('second');
30+
$input = $container->addText('name');
31+
Assert::same('frm-second-name', $input->getHtmlId());
32+
});
33+
34+
35+
test(function () {
36+
$form = new Form;
37+
$input = $form->addText('name');
38+
Assert::same('frm-name', $input->getHtmlId());
39+
});
40+
41+
42+
test(function () {
43+
Nette\Forms\Controls\BaseControl::$idMask = 'frm-%s-%s';
44+
45+
$form = new Form;
46+
$input = $form->addText('name');
47+
Assert::same('frm-name-', $input->getHtmlId());
48+
});
49+
50+
51+
test(function () {
52+
Nette\Forms\Controls\BaseControl::$idMask = 'frm-%2$s-%1$s';
53+
54+
$form = new Form('signForm');
55+
$input = $form->addText('name');
56+
Assert::same('frm-signForm-name', $input->getHtmlId());
57+
});

0 commit comments

Comments
 (0)