• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / forms / 21852420656

10 Feb 2026 05:00AM UTC coverage: 93.114% (+0.04%) from 93.076%
21852420656

push

github

dg
netteForms: restructured package, includes UMD and ESM (BC break)

2069 of 2222 relevant lines covered (93.11%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.17
/src/Forms/Controls/BaseControl.php
1
<?php
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Nette\Forms\Controls;
11

12
use Nette;
13
use Nette\Forms\Control;
14
use Nette\Forms\Form;
15
use Nette\Forms\Rules;
16
use Nette\Utils\Html;
17
use Stringable;
18
use function array_unique, explode, get_parent_class, implode, is_array, sprintf, str_contains;
19

20

21
/**
22
 * Base class that implements the basic functionality common to form controls.
23
 *
24
 * @property-read Form $form
25
 * @property   mixed $value
26
 * @property   bool $disabled
27
 * @property-read Html $control
28
 * @property-read Html $label
29
 * @property-read Html $controlPrototype
30
 * @property-read Html $labelPrototype
31
 * @property   bool $required
32
 * @property-read string[] $errors
33
 * @property-read string $error
34
 */
35
abstract class BaseControl extends Nette\ComponentModel\Component implements Control
36
{
37
        use Nette\SmartObject;
38

39
        public static string $idMask = 'frm-%s';
40

41
        protected mixed $value = null;
42
        protected Html $control;
43
        protected Html $label;
44
        protected bool $disabled = false;
45

46
        /** @var array<string, array<class-string, callable(self): mixed>> */
47
        private static array $extMethods = [];
48
        private string|Stringable|null $caption;
49

50
        /** @var string[] */
51
        private array $errors = [];
52
        private ?bool $omitted = null;
53
        private Rules $rules;
54

55
        /** true means autodetect */
56
        private Nette\Localization\Translator|true|null $translator = true;
57

58
        /** @var array<string, mixed> */
59
        private array $options = [];
60

61

62
        public function __construct(string|Stringable|null $caption = null)
1 ✔
63
        {
64
                $this->control = Html::el('input', ['type' => null, 'name' => null]);
1 ✔
65
                $this->label = Html::el('label');
1 ✔
66
                $this->caption = $caption;
1 ✔
67
                $this->rules = new Rules($this);
1 ✔
68
                $this->setValue(null);
1 ✔
69
                $this->monitor(Form::class, function (Form $form): void {
1 ✔
70
                        if (!$this->isDisabled() && $form->isAnchored() && $form->isSubmitted()) {
1 ✔
71
                                $this->loadHttpData();
1 ✔
72
                        }
73
                });
1 ✔
74
        }
1 ✔
75

76

77
        /**
78
         * Sets textual caption or label.
79
         */
80
        public function setCaption(string|Stringable|null $caption): static
81
        {
82
                $this->caption = $caption;
×
83
                return $this;
×
84
        }
85

86

87
        public function getCaption(): string|Stringable|null
88
        {
89
                return $this->caption;
1 ✔
90
        }
91

92

93
        /**
94
         * Returns form.
95
         * @return ($throw is true ? Form : ?Form)
96
         */
97
        public function getForm(bool $throw = true): ?Form
1 ✔
98
        {
99
                return $this->lookup(Form::class, $throw);
1 ✔
100
        }
101

102

103
        /**
104
         * Loads HTTP data.
105
         */
106
        public function loadHttpData(): void
107
        {
108
                $this->setValue($this->getHttpData(Form::DataText));
1 ✔
109
        }
1 ✔
110

111

112
        /**
113
         * Loads HTTP data.
114
         */
115
        protected function getHttpData(int $type, ?string $htmlTail = null): mixed
1 ✔
116
        {
117
                return $this->getForm()->getHttpData($type, $this->getHtmlName() . $htmlTail);
1 ✔
118
        }
119

120

121
        /**
122
         * Returns HTML name of control.
123
         */
124
        public function getHtmlName(): string
125
        {
126
                return $this->control->name ?? Nette\Forms\Helpers::generateHtmlName($this->lookupPath(Form::class));
1 ✔
127
        }
128

129

130
        /********************* interface Control ****************d*g**/
131

132

133
        /**
134
         * Sets control's value.
135
         * @internal
136
         */
137
        public function setValue($value): static
138
        {
139
                $this->value = $value;
1 ✔
140
                return $this;
1 ✔
141
        }
142

143

144
        /**
145
         * Returns control's value.
146
         */
147
        public function getValue(): mixed
148
        {
149
                return $this->value;
1 ✔
150
        }
151

152

153
        /**
154
         * Is control filled?
155
         */
156
        public function isFilled(): bool
157
        {
158
                $value = $this->getValue();
1 ✔
159
                return $value !== null && $value !== [] && $value !== '';
1 ✔
160
        }
161

162

163
        /**
164
         * Sets control's default value.
165
         */
166
        public function setDefaultValue(mixed $value): static
1 ✔
167
        {
168
                $form = $this->getForm(throw: false);
1 ✔
169
                if ($this->isDisabled() || !$form || !$form->isAnchored() || !$form->isSubmitted()) {
1 ✔
170
                        $this->setValue($value);
1 ✔
171
                }
172

173
                return $this;
1 ✔
174
        }
175

176

177
        /**
178
         * Disables or enables control.
179
         */
180
        public function setDisabled(bool $state = true): static
1 ✔
181
        {
182
                $this->disabled = $state;
1 ✔
183
                if ($state) {
1 ✔
184
                        $this->setValue(null);
1 ✔
185
                } elseif (($form = $this->getForm(throw: false)) && $form->isAnchored() && $form->isSubmitted()) {
1 ✔
186
                        $this->loadHttpData();
1 ✔
187
                }
188

189
                return $this;
1 ✔
190
        }
191

192

193
        /**
194
         * Is control disabled?
195
         */
196
        public function isDisabled(): bool
197
        {
198
                return $this->disabled;
1 ✔
199
        }
200

201

202
        /**
203
         * Sets whether control value is excluded from $form->getValues() result.
204
         */
205
        public function setOmitted(bool $state = true): static
1 ✔
206
        {
207
                $this->omitted = $state;
1 ✔
208
                return $this;
1 ✔
209
        }
210

211

212
        /**
213
         * Is control value excluded from $form->getValues() result?
214
         */
215
        public function isOmitted(): bool
216
        {
217
                return $this->omitted || ($this->isDisabled() && $this->omitted === null);
1 ✔
218
        }
219

220

221
        /********************* rendering ****************d*g**/
222

223

224
        /**
225
         * Generates control's HTML element.
226
         */
227
        public function getControl(): Html|string
228
        {
229
                $this->setOption('rendered', true);
1 ✔
230
                $el = clone $this->control;
1 ✔
231
                return $el->addAttributes([
1 ✔
232
                        'name' => $this->getHtmlName(),
1 ✔
233
                        'id' => $this->getHtmlId(),
1 ✔
234
                        'required' => $this->isRequired(),
1 ✔
235
                        'disabled' => $this->isDisabled(),
1 ✔
236
                        'data-nette-rules' => Nette\Forms\Helpers::exportRules($this->rules) ?: null,
1 ✔
237
                ]);
238
        }
239

240

241
        /**
242
         * Generates label's HTML element.
243
         */
244
        public function getLabel(string|Stringable|null $caption = null): Html|string|null
1 ✔
245
        {
246
                $label = clone $this->label;
1 ✔
247
                $label->for = $this->getHtmlId();
1 ✔
248
                $caption ??= $this->caption;
1 ✔
249
                $translator = $this->getForm()->getTranslator();
1 ✔
250
                $label->setText($translator && !$caption instanceof Nette\HtmlStringable ? $translator->translate($caption) : $caption);
1 ✔
251
                return $label;
1 ✔
252
        }
253

254

255
        public function getControlPart(): ?Html
256
        {
257
                return $this->getControl();
1 ✔
258
        }
259

260

261
        public function getLabelPart(): ?Html
262
        {
263
                return $this->getLabel();
1 ✔
264
        }
265

266

267
        /**
268
         * Returns control's HTML element template.
269
         */
270
        public function getControlPrototype(): Html
271
        {
272
                return $this->control;
1 ✔
273
        }
274

275

276
        /**
277
         * Returns label's HTML element template.
278
         */
279
        public function getLabelPrototype(): Html
280
        {
281
                return $this->label;
×
282
        }
283

284

285
        /**
286
         * Changes control's HTML id.
287
         */
288
        public function setHtmlId(string|bool|null $id): static
1 ✔
289
        {
290
                $this->control->id = $id;
1 ✔
291
                return $this;
1 ✔
292
        }
293

294

295
        /**
296
         * Returns control's HTML id.
297
         */
298
        public function getHtmlId(): string|bool|null
299
        {
300
                if (!isset($this->control->id)) {
1 ✔
301
                        $form = $this->getForm();
1 ✔
302
                        $prefix = $form instanceof Nette\Application\UI\Form || $form->getName() === null
1 ✔
303
                                ? ''
1 ✔
304
                                : $form->getName() . '-';
1 ✔
305
                        $this->control->id = sprintf(self::$idMask, $prefix . $this->lookupPath());
1 ✔
306
                }
307

308
                return $this->control->id;
1 ✔
309
        }
310

311

312
        /**
313
         * Changes control's HTML attribute.
314
         */
315
        public function setHtmlAttribute(string $name, mixed $value = true): static
1 ✔
316
        {
317
                $this->control->$name = $value;
1 ✔
318
                if (
319
                        $name === 'name'
1 ✔
320
                        && ($form = $this->getForm(throw: false))
1 ✔
321
                        && !$this->isDisabled()
1 ✔
322
                        && $form->isAnchored()
1 ✔
323
                        && $form->isSubmitted()
1 ✔
324
                ) {
325
                        $this->loadHttpData();
1 ✔
326
                }
327

328
                return $this;
1 ✔
329
        }
330

331

332
        /**
333
         * @deprecated  use setHtmlAttribute()
334
         */
335
        public function setAttribute(string $name, mixed $value = true): static
336
        {
337
                return $this->setHtmlAttribute($name, $value);
×
338
        }
339

340

341
        /********************* translator ****************d*g**/
342

343

344
        /**
345
         * Sets translate adapter.
346
         */
347
        public function setTranslator(?Nette\Localization\Translator $translator): static
1 ✔
348
        {
349
                $this->translator = $translator;
1 ✔
350
                return $this;
1 ✔
351
        }
352

353

354
        /**
355
         * Returns translate adapter.
356
         */
357
        public function getTranslator(): ?Nette\Localization\Translator
358
        {
359
                if ($this->translator === true) {
1 ✔
360
                        return $this->getForm(throw: false)
1 ✔
361
                                ? $this->getForm()->getTranslator()
1 ✔
362
                                : null;
1 ✔
363
                }
364

365
                return $this->translator;
1 ✔
366
        }
367

368

369
        /**
370
         * Returns translated string.
371
         */
372
        public function translate(mixed $value, mixed ...$parameters): mixed
1 ✔
373
        {
374
                if ($translator = $this->getTranslator()) {
1 ✔
375
                        $tmp = is_array($value) ? [&$value] : [[&$value]];
1 ✔
376
                        foreach ($tmp[0] as &$v) {
1 ✔
377
                                if ($v != null && !$v instanceof Nette\HtmlStringable) { // intentionally ==
1 ✔
378
                                        $v = $translator->translate($v, ...$parameters);
1 ✔
379
                                }
380
                        }
381
                }
382

383
                return $value;
1 ✔
384
        }
385

386

387
        /********************* rules ****************d*g**/
388

389

390
        /**
391
         * Adds a validation rule.
392
         * @param  (callable(self): bool)|string  $validator
393
         */
394
        public function addRule(
1 ✔
395
                callable|string $validator,
396
                string|Stringable|null $errorMessage = null,
397
                mixed $arg = null,
398
        ): static
399
        {
400
                $this->rules->addRule($validator, $errorMessage, $arg);
1 ✔
401
                return $this;
1 ✔
402
        }
403

404

405
        /**
406
         * Adds a validation condition a returns new branch.
407
         * @param  (callable(self): bool)|string|bool  $validator
408
         */
409
        public function addCondition(callable|string|bool $validator, mixed $value = null): Rules
1 ✔
410
        {
411
                return $this->rules->addCondition($validator, $value);
1 ✔
412
        }
413

414

415
        /**
416
         * Adds a validation condition based on another control a returns new branch.
417
         * @param  (callable(self): bool)|string  $validator
418
         */
419
        public function addConditionOn(Control $control, callable|string $validator, mixed $value = null): Rules
1 ✔
420
        {
421
                return $this->rules->addConditionOn($control, $validator, $value);
1 ✔
422
        }
423

424

425
        /**
426
         * Adds an input filter callback.
427
         * @param callable(mixed): mixed  $filter
428
         */
429
        public function addFilter(callable $filter): static
1 ✔
430
        {
431
                $this->getRules()->addFilter($filter);
1 ✔
432
                return $this;
1 ✔
433
        }
434

435

436
        public function getRules(): Rules
437
        {
438
                return $this->rules;
1 ✔
439
        }
440

441

442
        /**
443
         * Makes control mandatory.
444
         */
445
        public function setRequired(string|Stringable|bool $value = true): static
1 ✔
446
        {
447
                $this->rules->setRequired($value);
1 ✔
448
                return $this;
1 ✔
449
        }
450

451

452
        /**
453
         * Is control mandatory?
454
         */
455
        public function isRequired(): bool
456
        {
457
                return $this->rules->isRequired();
1 ✔
458
        }
459

460

461
        /**
462
         * Performs the server side validation.
463
         */
464
        public function validate(): void
465
        {
466
                if ($this->isDisabled()) {
1 ✔
467
                        return;
1 ✔
468
                }
469

470
                $this->cleanErrors();
1 ✔
471
                $this->rules->validate();
1 ✔
472
        }
1 ✔
473

474

475
        /**
476
         * Adds error message to the list.
477
         */
478
        public function addError(string|Stringable $message, bool $translate = true): void
1 ✔
479
        {
480
                $this->errors[] = $translate ? $this->translate($message) : $message;
1 ✔
481
        }
1 ✔
482

483

484
        /**
485
         * Returns errors corresponding to control.
486
         */
487
        public function getError(): ?string
488
        {
489
                return $this->errors ? implode(' ', array_unique($this->errors)) : null;
1 ✔
490
        }
491

492

493
        /**
494
         * Returns errors corresponding to control.
495
         * @return string[]
496
         */
497
        public function getErrors(): array
498
        {
499
                return array_unique($this->errors);
1 ✔
500
        }
501

502

503
        public function hasErrors(): bool
504
        {
505
                return (bool) $this->errors;
1 ✔
506
        }
507

508

509
        public function cleanErrors(): void
510
        {
511
                $this->errors = [];
1 ✔
512
        }
1 ✔
513

514

515
        /********************* user data ****************d*g**/
516

517

518
        /**
519
         * Sets user-specific option.
520
         */
521
        public function setOption(string $key, mixed $value): static
1 ✔
522
        {
523
                if ($value === null) {
1 ✔
524
                        unset($this->options[$key]);
×
525
                } else {
526
                        $this->options[$key] = $value;
1 ✔
527
                }
528

529
                return $this;
1 ✔
530
        }
531

532

533
        /**
534
         * Returns user-specific option.
535
         */
536
        public function getOption(string $key): mixed
1 ✔
537
        {
538
                return $this->options[$key] ?? null;
1 ✔
539
        }
540

541

542
        /**
543
         * Returns user-specific options.
544
         * @return array<string, mixed>
545
         */
546
        public function getOptions(): array
547
        {
548
                return $this->options;
×
549
        }
550

551

552
        /********************* extension methods ****************d*g**/
553

554

555
        /** @param mixed[] $args */
556
        public function __call(string $name, array $args): mixed
1 ✔
557
        {
558
                $class = static::class;
1 ✔
559
                do {
560
                        if (isset(self::$extMethods[$name][$class])) {
1 ✔
561
                                return (self::$extMethods[$name][$class])($this, ...$args);
1 ✔
562
                        }
563

564
                        $class = get_parent_class($class);
1 ✔
565
                } while ($class);
1 ✔
566

567
                return parent::__call($name, $args);
1 ✔
568
        }
569

570

571
        public static function extensionMethod(string $name, /*callable*/ $callback): void
1 ✔
572
        {
573
                if (str_contains($name, '::')) { // back compatibility
1 ✔
574
                        [, $name] = explode('::', $name);
×
575
                }
576

577
                self::$extMethods[$name][static::class] = $callback;
1 ✔
578
        }
1 ✔
579
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc