Skip to content

Commit

Permalink
Container::setDefaults() fixed passing values to disabled elements [C…
Browse files Browse the repository at this point in the history
…loses #326]

setDefaults(), unlike setDefaultValue(), did not set the value to form element when it was disabled by setDisabled() after the anchor event.
  • Loading branch information
mildabre authored and dg committed Apr 29, 2024
1 parent d4d452f commit cfca44d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
11 changes: 4 additions & 7 deletions src/Forms/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ class Container extends Nette\ComponentModel\Container implements \ArrayAccess
public function setDefaults(array|object $data, bool $erase = false): static
{
$form = $this->getForm(false);
if (!$form || !$form->isAnchored() || !$form->isSubmitted()) {
$this->setValues($data, $erase);
}

$this->setValues($data, $erase, $form?->isAnchored() && $form->isSubmitted());
return $this;
}

Expand All @@ -61,20 +58,20 @@ public function setDefaults(array|object $data, bool $erase = false): static
* Fill-in with values.
* @internal
*/
public function setValues(array|object $values, bool $erase = false): static
public function setValues(array|object $values, bool $erase = false, bool $onlyDisabled = false): static
{
$values = $values instanceof \Traversable
? iterator_to_array($values)
: (array) $values;

foreach ($this->getComponents() as $name => $control) {
if ($control instanceof Control) {
if (array_key_exists($name, $values) || $erase) {
if ((array_key_exists($name, $values) && (!$onlyDisabled || $control->isDisabled())) || $erase) {
$control->setValue($values[$name] ?? null);
}
} elseif ($control instanceof self) {
if (isset($values[$name]) || $erase) {
$control->setValues($values[$name] ?? [], $erase);
$control->setValues($values[$name] ?? [], $erase, $onlyDisabled);
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions tests/Forms/Controls.BaseControl.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,13 @@ test('disabled & submitted', function () {
$form->addText('disabled')
->setDisabled()
->setDefaultValue('default');
$form->addText('disabled2')
->setDisabled();
$form->setDefaults(['disabled2' => 'default']);

Assert::true($form->isSubmitted());
Assert::same('default', $form['disabled']->getValue());
Assert::same('default', $form['disabled2']->getValue());

unset($form['disabled']);
$input = new Nette\Forms\Controls\TextInput;
Expand Down

0 comments on commit cfca44d

Please sign in to comment.