diff --git a/src/Forms/Controls/BaseControl.php b/src/Forms/Controls/BaseControl.php index ace5d7eeb..4cbb4e08d 100644 --- a/src/Forms/Controls/BaseControl.php +++ b/src/Forms/Controls/BaseControl.php @@ -334,7 +334,8 @@ public function setHtmlId($id) public function getHtmlId() { if (!isset($this->control->id)) { - $this->control->id = sprintf(self::$idMask, $this->lookupPath()); + $form = $this->getForm(false); + $this->control->id = sprintf(self::$idMask, $this->lookupPath(), $form ? $form->getName() : ''); } return $this->control->id; } diff --git a/tests/Forms/Forms.idMask.phpt b/tests/Forms/Forms.idMask.phpt new file mode 100644 index 000000000..ed7ddbbbe --- /dev/null +++ b/tests/Forms/Forms.idMask.phpt @@ -0,0 +1,55 @@ +getHtmlId(); +}, Nette\InvalidStateException::class, "Component '' is not attached to ''."); + + +test(function () { + $container = new Nette\Forms\Container; + $container->setParent(null, 'second'); + $input = $container->addText('name'); + Assert::same('frm-name', $input->getHtmlId()); +}); + + +test(function () { + $form = new Form; + $container = $form->addContainer('second'); + $input = $container->addText('name'); + Assert::same('frm-second-name', $input->getHtmlId()); +}); + + +test(function () { + $form = new Form; + $input = $form->addText('name'); + Assert::same('frm-name', $input->getHtmlId()); +}); + + +test(function () { + Nette\Forms\Controls\BaseControl::$idMask = 'frm-%s-%s'; + + $form = new Form; + $input = $form->addText('name'); + Assert::same('frm-name-', $input->getHtmlId()); +}); + + +test(function () { + Nette\Forms\Controls\BaseControl::$idMask = 'frm-%2$s-%1$s'; + + $form = new Form('signForm'); + $input = $form->addText('name'); + Assert::same('frm-signForm-name', $input->getHtmlId()); +});