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

nette / forms / 40739665947

28 Oct 2026 05:35PM UTC coverage: 92.656% (+0.2%) from 92.436%
40739665947

push

github

dg
BaseControl: added setFixedValue() for a value the user cannot change

3 of 3 new or added lines in 1 file covered. (100.0%)

39 existing lines in 4 files now uncovered.

2801 of 3023 relevant lines covered (92.66%)

0.93 hits per line

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

94.74
/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
        {
UNCOV
83
                $this->caption = $caption;
×
UNCOV
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->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()')]
148
        protected function getHttpData(int $type, ?string $htmlTail = null): mixed
149
        {
150
                trigger_error(__METHOD__ . '() is deprecated, use getSubmittedValue()', E_USER_DEPRECATED);
1 ✔
151
                if ($htmlTail === null || $htmlTail === '') {
1 ✔
UNCOV
152
                        return $this->getSubmittedValue($type);
×
153
                }
154

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

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

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

170

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

180

181
        /********************* interface Control ****************d*g**/
182

183

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

191

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

197

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

207

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

218
                return $this;
1 ✔
219
        }
220

221

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

234
                return $this;
1 ✔
235
        }
236

237

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

246

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

256

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

265

266
        /**
267
         * Sets a value the user cannot change: the control is disabled, ignores submitted data
268
         * and its value stays among the form values.
269
         */
270
        public function setFixedValue(mixed $value): static
271
        {
272
                return $this->setDisabled()
1 ✔
273
                        ->setOmitted(false)
1 ✔
274
                        ->setValue($value);
1 ✔
275
        }
276

277

278
        /********************* rendering ****************d*g**/
279

280

281
        /**
282
         * Generates control's HTML element.
283
         */
284
        public function getControl(): Html|string
285
        {
286
                $this->setOption('rendered', true);
1 ✔
287
                $el = clone $this->control;
1 ✔
288
                $attrs = [
1 ✔
289
                        'name' => $this->getHtmlName(),
1 ✔
290
                        'id' => $this->getHtmlId(),
1 ✔
291
                        'required' => $this->isRequired(),
1 ✔
292
                        'disabled' => $this->isDisabled(),
1 ✔
293
                ];
294
                if ($names = $this->getRuleAttributeNames()) {
1 ✔
295
                        $declared = $this->rules->getHtmlAttributes();
1 ✔
296
                        foreach ($names as $name) {
1 ✔
297
                                $value = $declared[$name] ?? null;
1 ✔
298
                                if (!is_scalar($value)) {
1 ✔
299
                                        // a non-scalar bound (e.g. DateTimeInterface) is applied by the control that understands it
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
        {
UNCOV
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()')]
428
        public function setAttribute(string $name, mixed $value = true): static
429
        {
UNCOV
430
                trigger_error(__METHOD__ . '() was renamed to setHtmlAttribute()', E_USER_DEPRECATED);
×
UNCOV
431
                return $this->setHtmlAttribute($name, $value);
×
432
        }
433

434

435
        /********************* translator ****************d*g**/
436

437

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

444

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

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

459

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

474
                return $value;
1 ✔
475
        }
476

477

478
        /********************* rules ****************d*g**/
479

480

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

495

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

508

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

522

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

533

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

539

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

549

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

558

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

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

572

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

581

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

590

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

600

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

606

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

612

613
        /********************* user data ****************d*g**/
614

615

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

627
                return $this;
1 ✔
628
        }
629

630

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

639

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

649

650
        /********************* extension methods ****************d*g**/
651

652

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

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

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

669

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

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