-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBootstrapFormRenderer.php
More file actions
346 lines (292 loc) · 11.4 KB
/
Copy pathBootstrapFormRenderer.php
File metadata and controls
346 lines (292 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
<?php
declare(strict_types=1);
namespace ADT\Forms;
use ADT\Forms\Controls\PhoneNumberInput;
use Nette;
use Nette\Forms\Controls\SelectBox;
use Nette\Utils\Html;
use Nette\Utils\IHtmlString;
class BootstrapFormRenderer extends Nette\Forms\Rendering\DefaultFormRenderer
{
const VERSION_4 = 4;
const VERSION_5 = 5;
public static int $version = self::VERSION_5;
public function __construct(Nette\Forms\Form $form)
{
$form->onError[] = function(Nette\Forms\Form $form) {
if ($form->getPresenter()->isAjax()) {
static::makeBootstrap($form);
}
static::sendErrorPayload($form);
};
$form->onRender[] = function(Nette\Forms\Form $form) {
static::makeBootstrap($form);
};
$form->getElementPrototype()->setAttribute('data-adt-submit-form', true);
$this->form = $form;
}
public function renderLabel(Nette\Forms\Control $control): Html
{
if ($control->getLabel() && $control->getLabel()->getHtml()) {
return parent::renderLabel($control);
}
return Html::el();
}
public function renderControl(Nette\Forms\Control $control): Html
{
$body = $this->getWrapper('control container');
if ($this->counter % 2) {
$body->class($this->getValue('control .odd'), true);
}
if (!$this->getWrapper('pair container')->getName()) {
$body->class($control->getOption('class'), true);
$body->id = $control->getOption('id');
}
$description = $control->getOption('description');
if ($description instanceof Nette\HtmlStringable) {
$description = ' ' . $description;
} elseif ($description != null) { // intentionally ==
if ($control instanceof Nette\Forms\Controls\BaseControl) {
$description = $control->translate($description);
}
$description = ' ' . $this->getWrapper('control description')->setText($description);
} else {
$description = '';
}
if ($control->isRequired()) {
$description = $this->getValue('control requiredsuffix') . $description;
}
$prepend = $control->getOption('prepend') ?: '';
if ($prepend instanceof Nette\HtmlStringable) {
} elseif ($prepend != null) { // intentionally ==
if ($control instanceof Nette\Forms\Controls\BaseControl) {
$prepend = $control->translate($prepend);
}
}
if ($prepend) {
$prepend = '<span class="input-group-text">' . $prepend . '</span>';
}
$append = $control->getOption('append') ?: '';
if ($append instanceof Nette\HtmlStringable) {
} elseif ($append != null) { // intentionally ==
if ($control instanceof Nette\Forms\Controls\BaseControl) {
$append = $control->translate($append);
}
}
if ($append) {
$append = '<span class="input-group-text">' . $append . '</span>';
}
$inputGroupStart = $inputGroupEnd = '';
if ($prepend || $append) {
$inputGroupStart = '<div class="input-group">';
$inputGroupEnd = '</div>';
}
$control->setOption('rendered', true);
$el = $control->getControl();
if ($el instanceof Html) {
if ($el->getName() === 'input') {
$el->class($this->getValue("control .$el->type"), true);
}
$el->class($this->getValue('control .error'), $control->hasErrors());
}
$el = $body->setHtml($inputGroupStart . $prepend . $el . $append . $this->renderErrors($control) . $description . $inputGroupEnd);
// Is this an instance of a RadioList or CheckboxList?
if (
$control instanceof Nette\Forms\Controls\RadioList ||
$control instanceof Nette\Forms\Controls\CheckboxList ||
$control instanceof Nette\Forms\Controls\Checkbox
) {
// Get original container
$container = $control->getContainerPrototype();
$container->removeChildren();
// Create an empty Html container object
$el = Html::el();
// Get all the child items
$items = $control instanceof Nette\Forms\Controls\Checkbox ? [$control] : $control->getItems();
// For each child item, add the appropriate control part and label part after one another
foreach($items as $key => $item) {
$_container = clone $container;
$_container->addHtml($control->getControlPart($key));
$_container->addHtml($control->getLabelPart($key));
$el->addHtml($_container);
}
if ($control instanceof Nette\Forms\Controls\Checkbox) {
$_container->addHtml($this->doRenderErrors($control->getErrors(), true, $control->getHtmlId()));
} else {
$el->addHtml($this->doRenderErrors($control->getErrors(), true, $control->getHtmlId()));
}
}
elseif ($control instanceof PhoneNumberInput) {
$el = Html::el('div')
->setAttribute('class', static::$version === self::VERSION_4 ? 'form-row' : 'row g-2')
->addHtml('<div class="col-5">' . $control->getControlPart(PhoneNumberInput::CONTROL_COUNTRY_CODE)->setAttribute('class', static::$version === self::VERSION_4 ? 'form-control' : 'form-select') . '</div>')
->addHtml('<div class="col-7">' . $control->getControlPart(PhoneNumberInput::CONTROL_NATIONAL_NUMBER)->setAttribute('class', 'form-control') . $description . $this->renderErrors($control) . '</div>');
}
return $el;
}
/**
* Renders validation errors (per form or per control).
*/
public function renderErrors(?Nette\Forms\Control $control = null, bool $own = true): string
{
$errors = $control
? $control->getErrors()
: ($own ? $this->form->getOwnErrors() : $this->form->getErrors());
return $this->doRenderErrors($errors, (bool) $control, $control ? $control->getHtmlId() : $this->form->getElementPrototype()->getId());
}
/**
* We want to render erros if
* @param array $errors
* @param bool $control
* @param string|null $elId
* @return string
*/
public function doRenderErrors(array $errors, bool $control = false, ?string $elId = null): string
{
$container = $this->getWrapper($control ? 'control errorcontainer' : 'error container');
$item = $this->getWrapper($control ? 'control erroritem' : 'error item');
foreach ($errors as $error) {
$item = clone $item;
if ($error instanceof IHtmlString) {
$item->addHtml($error);
} else {
$item->setText($error);
}
$container->addHtml($item);
}
if ($elId) {
$errorElId = 'snippet-' . $elId . '-errors';
// we want to render container for errors even if there are no errors
// to be able to redraw it on ajax call
$container
->setAttribute('id', $errorElId);
if ($errors) {
$el = 'document.getElementById("' . $elId . '")';
$container->addHtml("
<script>
if ($el.tagName !== 'FORM') {
$el.classList.add('is-invalid');
// because of radio lists and checkbox lists
if ($el.name.endsWith('[]') || $el.type === 'radio') {
$el.parentNode.classList.add('is-invalid');
}
// because of https://github.com/twbs/bootstrap/issues/25110
if ($el.parentNode.classList.contains('input-group')) {
$el.parentNode.classList.add('has-validation');
}
}
</script>
");
}
}
return $control
? "\n\t" . $container->render()
: "\n" . $container->render(0);
}
public static function makeBootstrap(Nette\Forms\Container $container)
{
if (static::$version === self::VERSION_4) {
static::bootstrap4($container);
} elseif (static::$version === self::VERSION_5) {
static::bootstrap5($container);
} else {
throw new \Exception('Unsupported Bootstrap version.');
}
}
/**
* @throws Nette\Application\AbortException
*/
public static function sendErrorPayload(Nette\Application\UI\Form $form)
{
if ($form->getPresenter()->isAjax()) {
$renderer = $form->getRenderer();
$presenter = $form->getPresenter();
$renderer->wrappers['error']['container'] = null;
$presenter->payload->snippets['snippet-' . $form->getElementPrototype()->getAttribute('id') . '-errors'] = $renderer->renderErrors();
$renderer->wrappers['control']['errorcontainer'] = null;
/** @var Nette\Forms\Control $control */
foreach ($form->getControls() as $control) {
if ($control->getErrors()) {
$presenter->payload->snippets['snippet-' . $control->getHtmlId() . '-errors'] = $renderer->renderErrors($control);
$presenter->payload->hasErrors = true;
}
}
if (!$form->getPresenter()->isControlInvalid()) {
$presenter->sendPayload();
}
}
}
protected static function bootstrap4(Nette\Forms\Container $container): void
{
$renderer = $container->getForm()->getRenderer();
$renderer->wrappers['error']['container'] = 'div';
$renderer->wrappers['error']['item'] = 'div class="alert alert-danger"';
$renderer->wrappers['controls']['container'] = null;
$renderer->wrappers['group']['container'] = null;
$renderer->wrappers['pair']['container'] = 'div class=form-group';
$renderer->wrappers['label']['container'] = null;
$renderer->wrappers['control']['container'] = null;
$renderer->wrappers['control']['.error'] = 'is-invalid';
$renderer->wrappers['control']['.file'] = 'form-control-file';
$renderer->wrappers['control']['errorcontainer'] = 'div class=invalid-feedback';
$renderer->wrappers['control']['erroritem'] = 'div';
$renderer->wrappers['control']['description'] = 'small class="form-text text-muted"';
// we need to create a template container for DynamicContainer
// to apply bootstrap4 styles below
/** @var DynamicContainer $_dynamicContainer */
foreach ($container->getComponents(true, DynamicContainer::class) as $_dynamicContainer) {
if ($_dynamicContainer->isAllowAdding()) {
$_dynamicContainer->getTemplate();
}
}
/** @var Nette\Forms\Controls\BaseControl $control */
foreach ($container->getControls() as $control) {
$type = $control->getOption('type');
if ($control instanceof Nette\Forms\Controls\Button) {
$control->renderAsButton();
if ($control->getValidationScope() !== null) {
$control->getControlPrototype()->addClass('btn btn-outline-secondary');
} else {
$control->getControlPrototype()->addClass(empty($usedPrimary) ? 'btn btn-primary' : 'btn btn-outline-secondary');
$usedPrimary = true;
}
} elseif (in_array($type, ['checkbox', 'radio'], true)) {
if ($control->getOption('switch') === true) {
$control->getContainerPrototype()
->setName('div')
->addClass('form-check form-switch');
$control->getControlPrototype()
->addClass('form-check-input');
}
elseif ($control instanceof Nette\Forms\Controls\Checkbox) {
$control->getLabelPrototype()->addClass('form-check-label');
} else {
$control->getItemLabelPrototype()->addClass('form-check-label');
}
$control->getControlPrototype()->addClass('form-check-input');
$control->getContainerPrototype()->setName('div')->addClass('form-check');
} elseif ($control instanceof PhoneNumberInput) {
$control->getControlPrototype(PhoneNumberInput::CONTROL_COUNTRY_CODE)->addClass('form-control');
$control->getControlPrototype(PhoneNumberInput::CONTROL_NATIONAL_NUMBER)->addClass('form-control');
} elseif ($type !== 'hidden') {
$control->getControlPrototype()->addClass('form-control');
}
}
}
protected static function bootstrap5(Nette\Forms\Container $container): void
{
static::bootstrap4($container);
$renderer = $container->getForm()->getRenderer();
$renderer->wrappers['pair']['container'] = 'div class=mb-3';
$renderer->wrappers['control']['.file'] = 'form-control';
foreach ($container->getControls() as $control) {
$type = $control->getOption('type');
if (!in_array($type, ['checkbox', 'radio'], true)) {
$control->getLabelPrototype()->addClass('form-label');
}
if ($control instanceof SelectBox) {
$control->getControlPrototype()->removeClass('form-control')->addClass('form-select');
}
}
}
}