From 162bfa8e01620f5255bc7db8e8884d44e8206f2a Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Sat, 11 Feb 2023 21:48:56 +0100 Subject: [PATCH] CustomInputModifier: delay obtaining id until form attachment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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. --- app/Config/CustomInputModifier.php | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/app/Config/CustomInputModifier.php b/app/Config/CustomInputModifier.php index 9bc709b..b593897 100644 --- a/app/Config/CustomInputModifier.php +++ b/app/Config/CustomInputModifier.php @@ -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(); + }); } } }