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

nette / forms / 44437313773

19 Nov 2026 01:14AM UTC coverage: 93.665% (+0.8%) from 92.843%
44437313773

push

github

dg
updated upgrading.md

2898 of 3094 relevant lines covered (93.67%)

0.94 hits per line

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

96.49
/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, Validation};
12
use Nette\Utils\Html;
13
use Stringable;
14
use function is_array, is_scalar, is_string;
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
                __call as private callEvent;
42
        }
43

44
        public static string $idMask = 'frm-%s';
45

46
        protected mixed $value = null;
47
        protected Html $control;
48
        protected Html $label;
49
        protected bool $disabled = false;
50

51
        /** @var array<string, array<class-string, callable(static, never, never, never, never, never, never, never, never, never): 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;
1 ✔
84
                return $this;
1 ✔
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->getSubmittedValue(Form::DataText));
1 ✔
110
        }
1 ✔
111

112

113
        /**
114
         * Returns the submitted HTTP value for this control, or one of its sub-values when $key is specified.
115
         */
116
        protected function getSubmittedValue(int $type, ?string $key = null): mixed
117
        {
118
                $htmlName = $this->control->name;
1 ✔
119
                if (is_string($htmlName)) {
1 ✔
120
                        // overridden HTML name attribute is an absolute pointer into the raw submitted data, bypassing the component hierarchy
121
                        $path = explode('[', str_replace(['[]', ']', '.'], ['', '', '_'], $htmlName . ($key === null ? '' : "[$key]")));
1 ✔
122
                        $value = Nette\Utils\Arrays::get($this->getForm()->getSubmittedData(), $path, null);
1 ✔
123
                        return Nette\Forms\Helpers::sanitizeData($type, $value);
1 ✔
124
                }
125

126
                $parent = $this->getParent() ?? throw new Nette\InvalidStateException('Control is not attached to any form.');
1 ✔
127
                assert($parent instanceof Nette\Forms\Container);
128
                $name = $this->getName();
1 ✔
129
                assert($name !== null);
130
                if ($parent instanceof Form) {
1 ✔
131
                        $name = Nette\Forms\Helpers::sanitizeHtmlName($name); // mirrors generateHtmlName() which sanitizes only top-level names
1 ✔
132
                }
133

134
                $value = $parent->getSubmittedData()[$name] ?? null;
1 ✔
135
                if ($key !== null) {
1 ✔
136
                        $value = is_array($value) ? ($value[$key] ?? null) : null;
1 ✔
137
                }
138

139
                return Nette\Forms\Helpers::sanitizeData($type, $value);
1 ✔
140
        }
141

142

143
        /**
144
         * Returns the submitted HTTP value for this control.
145
         * @deprecated use getSubmittedValue()
146
         */
147
        #[\Deprecated('use getSubmittedValue()', since: '4.0')]
148
        protected function getHttpData(int $type, ?string $htmlTail = null): mixed
149
        {
150
                if ($htmlTail === null || $htmlTail === '') {
1 ✔
151
                        return $this->getSubmittedValue($type);
×
152
                }
153

154
                if (str_ends_with($htmlTail, '[]')) {
1 ✔
155
                        $type |= Form::DataList;
1 ✔
156
                        $htmlTail = substr($htmlTail, 0, -2);
1 ✔
157
                }
158

159
                $keys = explode('[', str_replace([']', '.'], ['', '_'], $htmlTail));
1 ✔
160
                if ($keys[0] === '') {
1 ✔
161
                        array_shift($keys);
1 ✔
162
                }
163

164
                $data = $this->getSubmittedValue(Form::DataArray);
1 ✔
165
                assert(is_array($data));
166
                return Nette\Forms\Helpers::sanitizeData($type, Nette\Utils\Arrays::get($data, $keys, null));
1 ✔
167
        }
168

169

170
        /**
171
         * Returns HTML name of control. When the 'name' attribute is overridden, it is used
172
         * both for rendering and as an absolute key for reading submitted data.
173
         */
174
        public function getHtmlName(): string
175
        {
176
                return $this->control->name ?? Nette\Forms\Helpers::generateHtmlName($this->lookupPath(Form::class));
1 ✔
177
        }
178

179

180
        /********************* interface Control ****************d*g**/
181

182

183
        /** @internal */
184
        public function setValue(mixed $value): static
185
        {
186
                $this->value = $value;
1 ✔
187
                return $this;
1 ✔
188
        }
189

190

191
        public function getValue(): mixed
192
        {
193
                return $this->value;
1 ✔
194
        }
195

196

197
        /**
198
         * Is control filled?
199
         */
200
        public function isFilled(): bool
201
        {
202
                $value = $this->getValue();
1 ✔
203
                return $value !== null && $value !== [] && $value !== '';
1 ✔
204
        }
205

206

207
        /**
208
         * Sets the default value. Has no effect on submitted or disabled controls.
209
         */
210
        public function setDefaultValue(mixed $value): static
211
        {
212
                $form = $this->getForm(throw: false);
1 ✔
213
                if ($this->isDisabled() || !$form || !$form->isAnchored() || !$form->isSubmitted()) {
1 ✔
214
                        $this->setValue($value);
1 ✔
215
                }
216

217
                return $this;
1 ✔
218
        }
219

220

221
        /**
222
         * Disables or enables control.
223
         */
224
        public function setDisabled(bool $state = true): static
225
        {
226
                $this->disabled = $state;
1 ✔
227
                if ($state) {
1 ✔
228
                        $this->setValue(null);
1 ✔
229
                } elseif (($form = $this->getForm(throw: false)) && $form->isAnchored() && $form->isSubmitted()) {
1 ✔
230
                        $this->loadHttpData();
1 ✔
231
                }
232

233
                return $this;
1 ✔
234
        }
235

236

237
        /**
238
         * Is control disabled?
239
         */
240
        public function isDisabled(): bool
241
        {
242
                return $this->disabled;
1 ✔
243
        }
244

245

246
        /**
247
         * Excludes or includes the control value from $form->getValues() result.
248
         */
249
        public function setOmitted(bool $state = true): static
250
        {
251
                $this->omitted = $state;
1 ✔
252
                return $this;
1 ✔
253
        }
254

255

256
        /**
257
         * Is control value excluded from $form->getValues() result?
258
         */
259
        public function isOmitted(): bool
260
        {
261
                return $this->omitted || ($this->isDisabled() && $this->omitted === null);
1 ✔
262
        }
263

264

265
        /**
266
         * Sets the value and disables the control, so it ignores submitted data and its value stays among
267
         * the form values. The code can still change it: setDefaults() overwrites it and Form::reset() clears it.
268
         */
269
        public function setFixedValue(mixed $value): static
270
        {
271
                return $this->setDisabled()
1 ✔
272
                        ->setOmitted(false)
1 ✔
273
                        ->setValue($value);
1 ✔
274
        }
275

276

277
        /********************* rendering ****************d*g**/
278

279

280
        /**
281
         * Generates control's HTML element.
282
         */
283
        public function getControl(): Html|string
284
        {
285
                $this->setOption('rendered', true);
1 ✔
286
                $el = clone $this->control;
1 ✔
287
                $attrs = [
1 ✔
288
                        'name' => $this->getHtmlName(),
1 ✔
289
                        'id' => $this->getHtmlId(),
1 ✔
290
                        'required' => $this->isRequired(),
1 ✔
291
                        'disabled' => $this->isDisabled(),
1 ✔
292
                ];
293
                if ($names = $this->getRuleAttributeNames()) {
1 ✔
294
                        $declared = $this->rules->getHtmlAttributes();
1 ✔
295
                        foreach ($names as $name) {
1 ✔
296
                                $value = $declared[$name] ?? null;
1 ✔
297
                                if ($value instanceof \DateTimeInterface) {
1 ✔
298
                                        $value = Nette\Forms\ClientRuleExporter::formatDateTime($value, $this);
1 ✔
299
                                } elseif (!is_scalar($value)) {
1 ✔
300
                                        continue;
1 ✔
301
                                }
302

303
                                if (!isset($el->attrs[$name])) {
1 ✔
304
                                        $attrs[$name] = $value;
1 ✔
305
                                } elseif (is_scalar($el->attrs[$name])) {
1 ✔
306
                                        $attrs[$name] = Rules::mergeAttribute($name, $el->attrs[$name], $value);
1 ✔
307
                                }
308
                                // a manually set non-scalar attribute always wins
309
                        }
310
                }
311

312
                $attrs['data-nette-rules'] = Nette\Forms\ClientRuleExporter::export($this->rules) ?: null;
1 ✔
313
                return $el->addAttributes($attrs);
1 ✔
314
        }
315

316

317
        /**
318
         * HTML validation attributes this control renders from the attributes declared
319
         * by its rules' validator objects (the validator offers, the control decides).
320
         * @return list<string>
321
         */
322
        protected function getRuleAttributeNames(): array
323
        {
324
                return [];
1 ✔
325
        }
326

327

328
        /**
329
         * Generates label's HTML element.
330
         */
331
        public function getLabel(string|Stringable|null $caption = null): Html|string|null
332
        {
333
                $label = clone $this->label;
1 ✔
334
                $label->for = $this->getHtmlId();
1 ✔
335
                $caption ??= $this->caption;
1 ✔
336
                $translator = $this->getForm()->getTranslator();
1 ✔
337
                $label->setText(
1 ✔
338
                        $translator && $caption !== null && !$caption instanceof Nette\HtmlStringable ? $translator->translate($caption) : $caption,
1 ✔
339
                );
340
                return $label;
1 ✔
341
        }
342

343

344
        public function getControlPart(): ?Html
345
        {
346
                $control = $this->getControl();
1 ✔
347
                return is_string($control)
1 ✔
348
                        ? throw new Nette\InvalidStateException("Control '{$this->getName()}' renders a string, not an Html element, so it cannot be used with n:name or rendered by parts.")
1 ✔
349
                        : $control;
1 ✔
350
        }
351

352

353
        public function getLabelPart(): ?Html
354
        {
355
                $label = $this->getLabel();
1 ✔
356
                return is_string($label)
1 ✔
357
                        ? throw new Nette\InvalidStateException("Label of control '{$this->getName()}' is a string, not an Html element, so it cannot be used with n:name or rendered by parts.")
1 ✔
358
                        : $label;
1 ✔
359
        }
360

361

362
        /**
363
         * Returns control's HTML element template.
364
         */
365
        public function getControlPrototype(): Html
366
        {
367
                return $this->control;
1 ✔
368
        }
369

370

371
        /**
372
         * Returns label's HTML element template.
373
         */
374
        public function getLabelPrototype(): Html
375
        {
376
                return $this->label;
×
377
        }
378

379

380
        /**
381
         * Changes control's HTML id.
382
         */
383
        public function setHtmlId(string|bool|null $id): static
384
        {
385
                $this->control->id = $id;
1 ✔
386
                return $this;
1 ✔
387
        }
388

389

390
        /**
391
         * Returns control's HTML id.
392
         */
393
        public function getHtmlId(): string|bool|null
394
        {
395
                if (!isset($this->control->id)) {
1 ✔
396
                        $form = $this->getForm();
1 ✔
397
                        $prefix = $form instanceof Nette\Application\UI\Form || $form->getName() === null
1 ✔
398
                                ? ''
1 ✔
399
                                : $form->getName() . '-';
1 ✔
400
                        $this->control->id = sprintf(self::$idMask, $prefix . $this->lookupPath());
1 ✔
401
                }
402

403
                return $this->control->id;
1 ✔
404
        }
405

406

407
        /**
408
         * Changes control's HTML attribute.
409
         */
410
        public function setHtmlAttribute(string $name, mixed $value = true): static
411
        {
412
                $this->control->$name = $value;
1 ✔
413
                if (
414
                        $name === 'name'
1 ✔
415
                        && ($form = $this->getForm(throw: false))
1 ✔
416
                        && !$this->isDisabled()
1 ✔
417
                        && $form->isAnchored()
1 ✔
418
                        && $form->isSubmitted()
1 ✔
419
                ) {
420
                        $this->loadHttpData();
1 ✔
421
                }
422

423
                return $this;
1 ✔
424
        }
425

426

427
        #[\Deprecated('use setHtmlAttribute()', since: '3.0')]
428
        public function setAttribute(string $name, mixed $value = true): static
429
        {
430
                return $this->setHtmlAttribute($name, $value);
×
431
        }
432

433

434
        /********************* translator ****************d*g**/
435

436

437
        public function setTranslator(?Nette\Localization\Translator $translator): static
438
        {
439
                $this->translator = $translator;
1 ✔
440
                return $this;
1 ✔
441
        }
442

443

444
        /**
445
         * Returns the translator, or inherits it from the form when not explicitly set.
446
         */
447
        public function getTranslator(): ?Nette\Localization\Translator
448
        {
449
                if ($this->translator === true) {
1 ✔
450
                        return $this->getForm(throw: false)
1 ✔
451
                                ? $this->getForm()->getTranslator()
1 ✔
452
                                : null;
1 ✔
453
                }
454

455
                return $this->translator ?: null;
1 ✔
456
        }
457

458

459
        /**
460
         * Translates a string or array of strings, or returns the value unchanged without a translator or when it is HtmlStringable.
461
         */
462
        public function translate(mixed $value, mixed ...$parameters): mixed
463
        {
464
                if ($translator = $this->getTranslator()) {
1 ✔
465
                        $tmp = is_array($value) ? [&$value] : [[&$value]];
1 ✔
466
                        foreach ($tmp[0] as &$v) {
1 ✔
467
                                if ($v != null && !$v instanceof Nette\HtmlStringable) { // intentionally ==
1 ✔
468
                                        $v = $translator->translate($v, ...$parameters);
1 ✔
469
                                }
470
                        }
471
                }
472

473
                return $value;
1 ✔
474
        }
475

476

477
        /********************* rules ****************d*g**/
478

479

480
        /**
481
         * Adds a validation rule.
482
         * @param  Validation\Validator|(callable(never, never): bool)|string  $validator
483
         */
484
        public function addRule(
485
                Validation\Validator|callable|string $validator,
486
                string|Stringable|null $errorMessage = null,
487
                mixed $arg = null,
488
        ): static
489
        {
490
                $this->rules->addRule($validator, $errorMessage, $arg);
1 ✔
491
                return $this;
1 ✔
492
        }
493

494

495
        /**
496
         * Adds a validation condition and returns a new branch.
497
         * @param  Validation\Validator|(callable(never, never): bool)|string|bool  $validator
498
         */
499
        public function addCondition(
500
                Validation\Validator|callable|string|bool $validator,
501
                mixed $value = null,
502
        ): Rules
503
        {
504
                return $this->rules->addCondition($validator, $value);
1 ✔
505
        }
506

507

508
        /**
509
         * Adds a validation condition based on another control and returns a new branch.
510
         * @param  Validation\Validator|(callable(never, never): bool)|string  $validator
511
         */
512
        public function addConditionOn(
513
                Control $control,
514
                Validation\Validator|callable|string $validator,
515
                mixed $value = null,
516
        ): Rules
517
        {
518
                return $this->rules->addConditionOn($control, $validator, $value);
1 ✔
519
        }
520

521

522
        /**
523
         * Adds an input filter callback.
524
         * @param callable(mixed): mixed  $filter
525
         */
526
        public function addFilter(callable $filter): static
527
        {
528
                $this->getRules()->addFilter($filter);
1 ✔
529
                return $this;
1 ✔
530
        }
531

532

533
        public function getRules(): Rules
534
        {
535
                return $this->rules;
1 ✔
536
        }
537

538

539
        /**
540
         * Makes control mandatory.
541
         */
542
        public function setRequired(string|Stringable|bool $value = true): static
543
        {
544
                $this->rules->setRequired($value);
1 ✔
545
                return $this;
1 ✔
546
        }
547

548

549
        /**
550
         * Is control mandatory?
551
         */
552
        public function isRequired(): bool
553
        {
554
                return $this->rules->isRequired();
1 ✔
555
        }
556

557

558
        /**
559
         * Performs server-side validation against all rules.
560
         */
561
        public function validate(): void
562
        {
563
                if ($this->isDisabled()) {
1 ✔
564
                        return;
1 ✔
565
                }
566

567
                $this->cleanErrors();
1 ✔
568
                $this->rules->validate();
1 ✔
569
        }
1 ✔
570

571

572
        /**
573
         * Adds error message to the list.
574
         */
575
        public function addError(string|Stringable $message, bool $translate = true): void
576
        {
577
                $this->errors[] = $translate ? $this->translate($message) : $message;
1 ✔
578
        }
1 ✔
579

580

581
        /**
582
         * Returns all control errors joined into one string, or null if there are no errors.
583
         */
584
        public function getError(): ?string
585
        {
586
                return $this->errors ? implode(' ', array_unique($this->errors)) : null;
1 ✔
587
        }
588

589

590
        /**
591
         * Returns all unique validation errors for this control.
592
         * @return list<string|Stringable>
593
         */
594
        public function getErrors(): array
595
        {
596
                return array_values(array_unique($this->errors));
1 ✔
597
        }
598

599

600
        public function hasErrors(): bool
601
        {
602
                return (bool) $this->errors;
1 ✔
603
        }
604

605

606
        public function cleanErrors(): void
607
        {
608
                $this->errors = [];
1 ✔
609
        }
1 ✔
610

611

612
        /********************* user data ****************d*g**/
613

614

615
        /**
616
         * Sets a rendering or user-specific option (e.g. 'description', 'class', 'id').
617
         */
618
        public function setOption(string $key, mixed $value): static
619
        {
620
                if ($value === null) {
1 ✔
621
                        unset($this->options[$key]);
×
622
                } else {
623
                        $this->options[$key] = $value;
1 ✔
624
                }
625

626
                return $this;
1 ✔
627
        }
628

629

630
        /**
631
         * Returns a rendering or user-specific option value.
632
         */
633
        public function getOption(string $key): mixed
634
        {
635
                return $this->options[$key] ?? null;
1 ✔
636
        }
637

638

639
        /**
640
         * Returns all rendering and user-specific options.
641
         * @return array<string, mixed>
642
         */
643
        public function getOptions(): array
644
        {
645
                return $this->options;
×
646
        }
647

648

649
        /********************* extension methods ****************d*g**/
650

651

652
        /** @param  mixed[]  $args */
653
        public function __call(string $name, array $args): mixed
654
        {
655
                $class = static::class;
1 ✔
656
                do {
657
                        if (isset(self::$extMethods[$name][$class])) {
1 ✔
658
                                /** @var never[] $args */
659
                                return (self::$extMethods[$name][$class])($this, ...$args);
1 ✔
660
                        }
661

662
                        $class = get_parent_class($class);
1 ✔
663
                } while ($class);
1 ✔
664

665
                return $this->callEvent($name, $args);
1 ✔
666
        }
667

668

669
        /** @param callable(static, never, never, never, never, never, never, never, never, never): mixed  $callback */
670
        public static function extensionMethod(string $name, callable $callback): void
671
        {
672
                if (str_contains($name, '::')) { // back compatibility
1 ✔
673
                        [, $name] = explode('::', $name);
×
674
                }
675

676
                self::$extMethods[$name][static::class] = $callback;
1 ✔
677
        }
1 ✔
678
}
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