|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types = 1); |
| 4 | + |
| 5 | +namespace Infinityloop\GenericDropdown; |
| 6 | + |
| 7 | +final class GenericDropdown extends \Nette\Application\UI\Control |
| 8 | +{ |
| 9 | + private string $defaultValue; |
| 10 | + private array $dropdownValues = []; |
| 11 | + private $callback; |
| 12 | + |
| 13 | + public function render() : void |
| 14 | + { |
| 15 | + $this->template->setFile(__DIR__ . '/GenericDropdown.latte'); |
| 16 | + $this->template->render(); |
| 17 | + } |
| 18 | + |
| 19 | + public function setDropdownValues(array $dropdownValues) : GenericDropdown |
| 20 | + { |
| 21 | + $this->dropdownValues = $dropdownValues; |
| 22 | + |
| 23 | + return $this; |
| 24 | + } |
| 25 | + |
| 26 | + public function setCallback(callable $callback) : GenericDropdown |
| 27 | + { |
| 28 | + $this->callback = $callback; |
| 29 | + |
| 30 | + return $this; |
| 31 | + } |
| 32 | + |
| 33 | + public function setDefaultValue(string $defaultValue) : GenericDropdown |
| 34 | + { |
| 35 | + $this->defaultValue = $defaultValue; |
| 36 | + |
| 37 | + return $this; |
| 38 | + } |
| 39 | + |
| 40 | + public function formSuccess(\Nette\Application\UI\Form $form, $values) : void |
| 41 | + { |
| 42 | + $newValue = $values['genericDropdown']; |
| 43 | + |
| 44 | + if (\is_callable($this->callback)) { |
| 45 | + $success = \call_user_func($this->callback, $newValue) ?? true; |
| 46 | + $form->reset(); |
| 47 | + $form->setDefaults(['genericDropdown' => ($success ? $newValue : $this->defaultValue)], true); |
| 48 | + } |
| 49 | + |
| 50 | + $this->redrawControl('genericDropDownSnippet'); |
| 51 | + } |
| 52 | + |
| 53 | + protected function createComponentForm() : \Nette\Application\UI\Form |
| 54 | + { |
| 55 | + $form = new \Nette\Application\UI\Form(); |
| 56 | + $form->addProtection(); |
| 57 | + |
| 58 | + $form->addSelect('genericDropdown', null, $this->dropdownValues) |
| 59 | + ->setDefaultValue($this->defaultValue); |
| 60 | + |
| 61 | + $form->onSuccess[] = [$this, 'formSuccess']; |
| 62 | + |
| 63 | + return $form; |
| 64 | + } |
| 65 | +} |
0 commit comments