Skip to content

Commit

Permalink
BaseControl: added ability to multiple forms with different HTML ID [C…
Browse files Browse the repository at this point in the history
…loses #188]

Solution: set Nette\Forms\Controls\BaseControl::$idMask = 'frm-%2$s-%1$s';
  • Loading branch information
dg committed Sep 12, 2018
1 parent e3d2294 commit 0fa9e5e
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Forms/Controls/BaseControl.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
55 changes: 55 additions & 0 deletions tests/Forms/Forms.idMask.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

use Nette\Forms\Controls\TextInput;
use Nette\Forms\Form;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


Assert::exception(function () {
$input = new TextInput('name');
$input->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());
});

2 comments on commit 0fa9e5e

@f3l1x
Copy link
Member

@f3l1x f3l1x commented on 0fa9e5e Sep 13, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add this to docs?

Edit: Should I prepare PR?

@dg
Copy link
Member Author

@dg dg commented on 0fa9e5e Sep 13, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be great :)

Please sign in to comment.