After javascript prop(‘disabled’, true) on a select box control, form validation fails

8 months ago

Niels
Member | 2
+
0
-

I'm having a Nette Form with two select box lines.
It's for configuring our hardware, which has two slots that can contain crates.

  • slot1: select crate –
  • slot2: select crate –

So far, so good.
Now, some crates are quite large, and require two slots.
I've written some javascript, that will disable slot 2, when you select a big crate in slot 1:
$(‘select[name=slot2]’).prop(‘disabled’, true);

Now the problem.
On POST, ‘slot2’ is not sent in the POST.
Nette will try to validate the form, and it says ‘Please select a valid option.’

How to solve this?
I think I should use ‘setDisabled’ on the select box, but how do I know this inside my createComponentSlotForm() ?

8 months ago

Milo
Nette Core | 1151
+
0
-

Depends on your code. Maybe something like:

$slot1 = $form->addSelect('slot1', 'Title 1', [...items...]);
$slot2 = $form->addSelect('slot2', 'Title 2', [...items...]);

if ($form->isSubmitted() && $slot1->getValue() === '???') {
	$slot2->setDisabled();
}

8 months ago

Niels
Member | 2
+
0
-

Thank you, that works!

Unfortunately, it was difficult to include it in our stack, since we use a class derived from \Nette\Application\UI\Form, that does all the configuration/addSelect in __construct. So I don't have $form at that time.

The solution that was easiest to implement was to add a hidden field in javascript with the same name, and toggle the prop(‘disabled’,…) at the same time as the other prop change. Obviously, I must run javascript when the page is loaded, to make sure that all ‘disableds’ are correct.

I tried to add the hidden field in the form with $this->addHidden(), but Nette does not allow the same name twice. Which I think is a good decision, just not for us ;)