Skip to content

Commit 9d89c8b

Browse files
authored
Update TAjaxSelect.php
1 parent 361e0a4 commit 9d89c8b

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/Form/TAjaxSelect.php

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,21 @@ trait TAjaxSelect
2222
/** @var callable */
2323
private $callback;
2424

25+
/** @var callable */
26+
private $onchange;
27+
2528
public function setCallback(callable $callback): self
2629
{
2730
$this->callback = $callback;
2831
return $this;
2932
}
3033

34+
public function setOnchange(callable $onchange) : self
35+
{
36+
$this->onchange = $onchange;
37+
return $this;
38+
}
39+
3140
public function getControl(): \Nette\Utils\Html
3241
{
3342
$this->initiateItems();
@@ -36,7 +45,11 @@ public function getControl(): \Nette\Utils\Html
3645
$control = parent::getControl();
3746

3847
$attrs['data-ajaxselect'] = $this->getForm()->getPresenter()->link(
39-
$this->lookupPath(Presenter::class) . IComponent::NAME_SEPARATOR . self::SIGNAL_NAME . '!'
48+
$this->lookupPath(Presenter::class) . IComponent::NAME_SEPARATOR . self::CALLBACK_SIGNAL_NAME . '!'
49+
);
50+
51+
$attrs['data-onchange'] = $this->getForm()->getPresenter()->link(
52+
$this->lookupPath(Presenter::class) . IComponent::NAME_SEPARATOR . self::ONCHANGE_SIGNAL_NAME . '!'
4053
);
4154

4255
$control->addAttributes($attrs);
@@ -61,11 +74,18 @@ public function signalReceived(string $signal): void
6174
{
6275
$presenter = $this->lookup(Presenter::class);
6376

64-
if ($signal !== self::SIGNAL_NAME || !$presenter->isAjax() || $this->isDisabled()) {
77+
if (!$presenter->isAjax() || $this->isDisabled()) {
6578
return;
6679
}
6780

68-
$presenter->sendJson($this->getData($presenter->getParameter('q')));
81+
switch ($signal) {
82+
case self::CALLBACK_SIGNAL_NAME:
83+
$presenter->sendJson($this->getData($presenter->getParameter('q')));
84+
break;
85+
case self::ONCHANGE_SIGNAL_NAME:
86+
$this->fireOnchange($presenter->getParameter('s'));
87+
break;
88+
}
6989
}
7090

7191
private function getData(string $query = '', $default = null): array
@@ -95,4 +115,13 @@ private function initiateItems($value = null): void
95115
$this->items = $this->getData();
96116
}
97117
}
118+
119+
private function fireOnchange($selected = null) : void
120+
{
121+
if ($this->onchange === null) {
122+
throw new \Nette\InvalidStateException('Onchange for "' . $this->getHtmlId() . '" is not set.');
123+
}
124+
125+
\call_user_func($this->onchange, $selected);
126+
}
98127
}

0 commit comments

Comments
 (0)