Skip to content

Commit

Permalink
CustomInputModifier: delay obtaining id until form attachment
Browse files Browse the repository at this point in the history
`Container::addDynamic` from `Kdyby/Replicator` would only run the closure passed to it after the form is attached.
This is not the case with `contributte/forms-multiplier`, which runs it during creation, which would result in throwing the following `InvalidStateException`:

    Component 'registry_address' is not attached to 'Nette\Forms\Form'.

Let’s wait until the form is attached before trying to obtain the input’s id.
  • Loading branch information
jtojnar committed Apr 3, 2023
1 parent b87c9dc commit 868ec5e
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions app/Config/CustomInputModifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,18 @@ final class CustomInputModifier implements InputModifier {
public static function modify(Control $input, IContainer $container): void {
// we also have some inputs that are based on Nextras\FormComponents\Fragments\UIComponent\BaseControl
if ($input instanceof BaseControl && $input->getName() === 'registry_address') {
$pairId = 'pair-' . $input->htmlId;
$input->setOption('id', $pairId);
$input->monitor(Form::class, function(Form $form) use ($input, $container): void {
// ID is not available until the Form is attached.
// Note: This will not handle re-attaching the form under different name but entries do not do that.
$pairId = 'pair-' . $input->htmlId;
$input->setOption('id', $pairId);

/** @var BaseControl */
$country = $container->getComponent('country');
$country->addCondition(Form::NOT_EQUAL, 46)->toggle($pairId, false);
$input->setRequired(false);
$input->addConditionOn($country, Form::EQUAL, 46)->setRequired();
/** @var BaseControl */
$country = $container->getComponent('country');
$country->addCondition(Form::NOT_EQUAL, 46)->toggle($pairId, false);
$input->setRequired(false);
$input->addConditionOn($country, Form::EQUAL, 46)->setRequired();
});
}
}
}

0 comments on commit 868ec5e

Please sign in to comment.