|
1 | | -# ajaxselect |
| 1 | +# Ajaxselect |
2 | 2 | :wrench: Ajax-filled selectbox for nette forms. |
| 3 | + |
| 4 | + |
| 5 | + |
| 6 | +[]() |
| 7 | + |
| 8 | +[](https://codeclimate.com/github/nepttune/ajaxselect) |
| 9 | +[](https://scrutinizer-ci.com/g/nepttune/ajaxselect/?branch=master) |
| 10 | + |
| 11 | +## Introduction |
| 12 | + |
| 13 | +This extension provides easy to use ajax-driven selectbox. |
| 14 | + |
| 15 | +## Dependencies |
| 16 | + |
| 17 | +- [nepttune/base-requirements](https://github.com/nepttune/base-requirements) |
| 18 | + |
| 19 | +## How to use |
| 20 | + |
| 21 | +- Register `\Nepttune\DI\AjaxSelectExtension` as nette extension. |
| 22 | +- Use `addAjaxSelect` or `addAjaxMultiSelect` in your forms. |
| 23 | + |
| 24 | +### Example configuration |
| 25 | + |
| 26 | +``` |
| 27 | +extensions: |
| 28 | + ajaxSelect: Nepttune\DI\AjaxSelectExtension |
| 29 | +``` |
| 30 | + |
| 31 | +### Example form |
| 32 | + |
| 33 | +``` |
| 34 | +$form->addAjaxSelect('client_id', 'Klient', function (string $query, ?int $default = 0) { |
| 35 | + if ($default) { |
| 36 | + $row = $this->repository->getRow($default); |
| 37 | + return [$row->id => $row->name]; |
| 38 | + } |
| 39 | +
|
| 40 | + return $this->repository->search($query); |
| 41 | + }) |
| 42 | + ->setPrompt('--- Vyberte ---') |
| 43 | + ->setRequired(); |
| 44 | +``` |
| 45 | + |
| 46 | +Parameter `$query` contains text being searched, parametered `$default` contains value which is set as default (for example when editing existing entry, you need to provide saved key => value in your callback). |
| 47 | + |
| 48 | +### Javascript snippet using select2 |
| 49 | +``` |
| 50 | +if ($(this).data('ajaxselect')) { |
| 51 | + $(this).select2({ |
| 52 | + tokenSeparators: [',', ' '], |
| 53 | + ajax: { |
| 54 | + url: $(this).data('ajaxselect'), |
| 55 | + delay: 250, |
| 56 | + dataType: 'json', |
| 57 | + data: function (params) { |
| 58 | + return { |
| 59 | + q: params.term |
| 60 | + }; |
| 61 | + }, |
| 62 | + processResults: function (data, params) { |
| 63 | + var result = []; |
| 64 | + $.each(data, function (key, value) { |
| 65 | + result.push({ |
| 66 | + id: key, |
| 67 | + text: value |
| 68 | + }); |
| 69 | + }); |
| 70 | + return { |
| 71 | + results: result |
| 72 | + }; |
| 73 | + } |
| 74 | + } |
| 75 | + }); |
| 76 | +} |
| 77 | +``` |
0 commit comments