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

nette / forms / 40615789318

28 Oct 2026 01:33AM UTC coverage: 92.379% (-1.3%) from 93.701%
40615789318

push

github

dg
added upgrading.md

2000 of 2165 relevant lines covered (92.38%)

0.92 hits per line

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

93.8
/src/Forms/Controls/BaseControl.php
1
<?php declare(strict_types=1);
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
namespace Nette\Forms\Controls;
9

10
use Nette;
11
use Nette\Forms\{Control, Form, Rules};
12
use Nette\Utils\Html;
13
use Stringable;
14
use function is_array;
15

16

17
/**
18
 * Base implementation for form controls with HTML rendering, validation, translation, and option support.
19
 *
20
 * @property-read string $name
21
 * @property-read Form $form
22
 * @property-deprecated string $htmlName
23
 * @property   string|bool|null $htmlId
24
 * @property   mixed $value
25
 * @property-deprecated   string|Stringable $caption
26
 * @property   bool $disabled
27
 * @property-deprecated   bool $omitted
28
 * @property-read Html $control
29
 * @property-read Html $label
30
 * @property-read Html $controlPrototype
31
 * @property-read Html $labelPrototype
32
 * @property   bool $required
33
 * @property-deprecated bool $filled
34
 * @property-read string[] $errors
35
 * @property-deprecated array<string,mixed> $options
36
 * @property-read string $error
37
 */
38
abstract class BaseControl extends Nette\ComponentModel\Component implements Control
39
{
40
        use Nette\SmartObject;
41

42
        public static string $idMask = 'frm-%s';
43

44
        protected mixed $value = null;
45
        protected Html $control;
46
        protected Html $label;
47

48
        /** @var bool|bool[] */
49
        protected bool|array $disabled = false;
50

51
        /** @var array<string, array<class-string, callable(static): mixed>> */
52
        private static array $extMethods = [];
53

54
        /** @var list<string|Stringable> */
55
        private array $errors = [];
56
        private ?bool $omitted = null;
57
        private Rules $rules;
58

59
        /** true means autodetect */
60
        private Nette\Localization\Translator|true|null $translator = true;
61

62
        /** @var array<string, mixed> */
63
        private array $options = [];
64

65

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

80

81
        public function setCaption(string|Stringable|null $caption): static
82
        {
83
                $this->caption = $caption;
×
84
                return $this;
×
85
        }
86

87

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

93

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

103

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

112

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

121

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

130

131
        /********************* interface Control ****************d*g**/
132

133

134
        /**
135
         * @return static
136
         * @internal
137
         */
138
        public function setValue(mixed $value)
139
        {
140
                $this->value = $value;
1 ✔
141
                return $this;
1 ✔
142
        }
143

144

145
        /** @return mixed */
146
        public function getValue()
147
        {
148
                return $this->value;
1 ✔
149
        }
150

151

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

161

162
        /**
163
         * Sets the default value. Has no effect on submitted or disabled controls.
164
         * @return static
165
         */
166
        public function setDefaultValue(mixed $value)
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
         * @return static
180
         */
181
        public function setDisabled(bool $state = true)
182
        {
183
                $this->disabled = $state;
1 ✔
184
                if ($state) {
1 ✔
185
                        $this->setValue(null);
1 ✔
186
                } elseif (($form = $this->getForm(throw: false)) && $form->isAnchored() && $form->isSubmitted()) {
1 ✔
187
                        $this->loadHttpData();
1 ✔
188
                }
189

190
                return $this;
1 ✔
191
        }
192

193

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

202

203
        /**
204
         * Excludes or includes the control value from $form->getValues() result.
205
         */
206
        public function setOmitted(bool $state = true): static
207
        {
208
                $this->omitted = $state;
1 ✔
209
                return $this;
1 ✔
210
        }
211

212

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

221

222
        /********************* rendering ****************d*g**/
223

224

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

242

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

259

260
        public function getControlPart(): ?Html
261
        {
262
                $control = $this->getControl();
1 ✔
263
                return $control instanceof Html ? $control : null;
1 ✔
264
        }
265

266

267
        public function getLabelPart(): ?Html
268
        {
269
                $label = $this->getLabel();
1 ✔
270
                return $label instanceof Html ? $label : null;
1 ✔
271
        }
272

273

274
        /**
275
         * Returns control's HTML element template.
276
         */
277
        public function getControlPrototype(): Html
278
        {
279
                return $this->control;
1 ✔
280
        }
281

282

283
        /**
284
         * Returns label's HTML element template.
285
         */
286
        public function getLabelPrototype(): Html
287
        {
288
                return $this->label;
×
289
        }
290

291

292
        /**
293
         * Changes control's HTML id.
294
         */
295
        public function setHtmlId(string|bool|null $id): static
296
        {
297
                $this->control->id = $id;
1 ✔
298
                return $this;
1 ✔
299
        }
300

301

302
        /**
303
         * Returns control's HTML id.
304
         */
305
        public function getHtmlId(): string|bool|null
306
        {
307
                if (!isset($this->control->id)) {
1 ✔
308
                        $form = $this->getForm();
1 ✔
309
                        $prefix = $form instanceof Nette\Application\UI\Form || $form->getName() === null
1 ✔
310
                                ? ''
1 ✔
311
                                : $form->getName() . '-';
1 ✔
312
                        $this->control->id = sprintf(self::$idMask, $prefix . $this->lookupPath());
1 ✔
313
                }
314

315
                return $this->control->id;
1 ✔
316
        }
317

318

319
        /**
320
         * Changes control's HTML attribute.
321
         */
322
        public function setHtmlAttribute(string $name, mixed $value = true): static
323
        {
324
                $this->control->$name = $value;
1 ✔
325
                if (
326
                        $name === 'name'
1 ✔
327
                        && ($form = $this->getForm(throw: false))
1 ✔
328
                        && !$this->isDisabled()
1 ✔
329
                        && $form->isAnchored()
1 ✔
330
                        && $form->isSubmitted()
1 ✔
331
                ) {
332
                        $this->loadHttpData();
1 ✔
333
                }
334

335
                return $this;
1 ✔
336
        }
337

338

339
        /**
340
         * @deprecated  use setHtmlAttribute()
341
         */
342
        public function setAttribute(string $name, mixed $value = true): static
343
        {
344
                return $this->setHtmlAttribute($name, $value);
×
345
        }
346

347

348
        /********************* translator ****************d*g**/
349

350

351
        public function setTranslator(?Nette\Localization\Translator $translator): static
352
        {
353
                $this->translator = $translator;
1 ✔
354
                return $this;
1 ✔
355
        }
356

357

358
        /**
359
         * Returns the translator, or inherits it from the form when not explicitly set.
360
         */
361
        public function getTranslator(): ?Nette\Localization\Translator
362
        {
363
                if ($this->translator === true) {
1 ✔
364
                        return $this->getForm(throw: false)
1 ✔
365
                                ? $this->getForm()->getTranslator()
1 ✔
366
                                : null;
1 ✔
367
                }
368

369
                return $this->translator ?: null;
1 ✔
370
        }
371

372

373
        /**
374
         * Translates a string or array of strings, or returns the value unchanged without a translator or when it is HtmlStringable.
375
         */
376
        public function translate(mixed $value, mixed ...$parameters): mixed
377
        {
378
                if ($translator = $this->getTranslator()) {
1 ✔
379
                        $tmp = is_array($value) ? [&$value] : [[&$value]];
1 ✔
380
                        foreach ($tmp[0] as &$v) {
1 ✔
381
                                if ($v != null && !$v instanceof Nette\HtmlStringable) { // intentionally ==
1 ✔
382
                                        $v = $translator->translate($v, ...$parameters);
1 ✔
383
                                }
384
                        }
385
                }
386

387
                return $value;
1 ✔
388
        }
389

390

391
        /********************* rules ****************d*g**/
392

393

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

408

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

418

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

428

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

439

440
        public function getRules(): Rules
441
        {
442
                return $this->rules;
1 ✔
443
        }
444

445

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

455

456
        /**
457
         * Is control mandatory?
458
         */
459
        public function isRequired(): bool
460
        {
461
                return $this->rules->isRequired();
1 ✔
462
        }
463

464

465
        /**
466
         * Performs server-side validation against all rules.
467
         */
468
        public function validate(): void
469
        {
470
                if ($this->isDisabled()) {
1 ✔
471
                        return;
1 ✔
472
                }
473

474
                $this->cleanErrors();
1 ✔
475
                $this->rules->validate();
1 ✔
476
        }
1 ✔
477

478

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

487

488
        /**
489
         * Returns all control errors joined into one string, or null if there are no errors.
490
         */
491
        public function getError(): ?string
492
        {
493
                return $this->errors ? implode(' ', array_unique($this->errors)) : null;
1 ✔
494
        }
495

496

497
        /**
498
         * Returns all unique validation errors for this control.
499
         * @return list<string|Stringable>
500
         */
501
        public function getErrors(): array
502
        {
503
                return array_values(array_unique($this->errors));
1 ✔
504
        }
505

506

507
        public function hasErrors(): bool
508
        {
509
                return (bool) $this->errors;
1 ✔
510
        }
511

512

513
        public function cleanErrors(): void
514
        {
515
                $this->errors = [];
1 ✔
516
        }
1 ✔
517

518

519
        /********************* user data ****************d*g**/
520

521

522
        /**
523
         * Sets a rendering or user-specific option (e.g. 'description', 'class', 'id').
524
         */
525
        public function setOption(string $key, mixed $value): static
526
        {
527
                if ($value === null) {
1 ✔
528
                        unset($this->options[$key]);
×
529
                } else {
530
                        $this->options[$key] = $value;
1 ✔
531
                }
532

533
                return $this;
1 ✔
534
        }
535

536

537
        /**
538
         * Returns a rendering or user-specific option value.
539
         */
540
        public function getOption(string $key): mixed
541
        {
542
                return $this->options[$key] ?? null;
1 ✔
543
        }
544

545

546
        /**
547
         * Returns all rendering and user-specific options.
548
         * @return array<string, mixed>
549
         */
550
        public function getOptions(): array
551
        {
552
                return $this->options;
×
553
        }
554

555

556
        /********************* extension methods ****************d*g**/
557

558

559
        /**
560
         * @param  mixed[]  $args
561
         * @return mixed
562
         */
563
        public function __call(string $name, array $args)
564
        {
565
                $class = static::class;
1 ✔
566
                do {
567
                        if (isset(self::$extMethods[$name][$class])) {
1 ✔
568
                                return (self::$extMethods[$name][$class])($this, ...$args);
1 ✔
569
                        }
570

571
                        $class = get_parent_class($class);
1 ✔
572
                } while ($class);
1 ✔
573

574
                Nette\Utils\ObjectHelpers::strictCall(static::class, $name);
1 ✔
575
        }
×
576

577

578
        /** @param callable(static): mixed  $callback */
579
        public static function extensionMethod(string $name, callable $callback): void
580
        {
581
                if (str_contains($name, '::')) { // back compatibility
1 ✔
582
                        [, $name] = explode('::', $name);
×
583
                }
584

585
                self::$extMethods[$name][static::class] = $callback;
1 ✔
586
        }
1 ✔
587
}
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