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

nette / forms / 40630690772

28 Oct 2026 03:26AM UTC coverage: 92.436% (-0.5%) from 92.983%
40630690772

push

github

dg
netteForms: a form whose repeater starts empty validates on submit

Removing a repeater item refreshes the toggles.

2774 of 3001 relevant lines covered (92.44%)

0.92 hits per line

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

93.94
/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

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

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

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

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

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

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

63

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

78

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

85

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

91

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

101

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

110

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

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

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

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

140

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

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

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

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

168

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

178

179
        /********************* interface Control ****************d*g**/
180

181

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

189

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

195

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

205

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

216
                return $this;
1 ✔
217
        }
218

219

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

232
                return $this;
1 ✔
233
        }
234

235

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

244

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

254

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

263

264
        /********************* rendering ****************d*g**/
265

266

267
        /**
268
         * Generates control's HTML element.
269
         */
270
        public function getControl(): Html|string
271
        {
272
                $this->setOption('rendered', true);
1 ✔
273
                $el = clone $this->control;
1 ✔
274
                $attrs = [
1 ✔
275
                        'name' => $this->getHtmlName(),
1 ✔
276
                        'id' => $this->getHtmlId(),
1 ✔
277
                        'required' => $this->isRequired(),
1 ✔
278
                        'disabled' => $this->isDisabled(),
1 ✔
279
                ];
280
                if ($names = $this->getRuleAttributeNames()) {
1 ✔
281
                        $declared = $this->rules->getHtmlAttributes();
1 ✔
282
                        foreach ($names as $name) {
1 ✔
283
                                $value = $declared[$name] ?? null;
1 ✔
284
                                if (!is_scalar($value)) {
1 ✔
285
                                        // a non-scalar bound (e.g. DateTimeInterface) is applied by the control that understands it
286
                                        continue;
1 ✔
287
                                }
288

289
                                if (!isset($el->attrs[$name])) {
1 ✔
290
                                        $attrs[$name] = $value;
1 ✔
291
                                } elseif (is_scalar($el->attrs[$name])) {
1 ✔
292
                                        $attrs[$name] = Rules::mergeAttribute($name, $el->attrs[$name], $value);
1 ✔
293
                                }
294
                                // a manually set non-scalar attribute always wins
295
                        }
296
                }
297

298
                $attrs['data-nette-rules'] = Nette\Forms\ClientRuleExporter::export($this->rules) ?: null;
1 ✔
299
                return $el->addAttributes($attrs);
1 ✔
300
        }
301

302

303
        /**
304
         * HTML validation attributes this control renders from the attributes declared
305
         * by its rules' validator objects (the validator offers, the control decides).
306
         * @return list<string>
307
         */
308
        protected function getRuleAttributeNames(): array
309
        {
310
                return [];
1 ✔
311
        }
312

313

314
        /**
315
         * Generates label's HTML element.
316
         */
317
        public function getLabel(string|Stringable|null $caption = null): Html|string|null
318
        {
319
                $label = clone $this->label;
1 ✔
320
                $label->for = $this->getHtmlId();
1 ✔
321
                $caption ??= $this->caption;
1 ✔
322
                $translator = $this->getForm()->getTranslator();
1 ✔
323
                $label->setText(
1 ✔
324
                        $translator && $caption !== null && !$caption instanceof Nette\HtmlStringable ? $translator->translate($caption) : $caption,
1 ✔
325
                );
326
                return $label;
1 ✔
327
        }
328

329

330
        public function getControlPart(): ?Html
331
        {
332
                $control = $this->getControl();
1 ✔
333
                return $control instanceof Html ? $control : null;
1 ✔
334
        }
335

336

337
        public function getLabelPart(): ?Html
338
        {
339
                $label = $this->getLabel();
1 ✔
340
                return $label instanceof Html ? $label : null;
1 ✔
341
        }
342

343

344
        /**
345
         * Returns control's HTML element template.
346
         */
347
        public function getControlPrototype(): Html
348
        {
349
                return $this->control;
1 ✔
350
        }
351

352

353
        /**
354
         * Returns label's HTML element template.
355
         */
356
        public function getLabelPrototype(): Html
357
        {
358
                return $this->label;
×
359
        }
360

361

362
        /**
363
         * Changes control's HTML id.
364
         */
365
        public function setHtmlId(string|bool|null $id): static
366
        {
367
                $this->control->id = $id;
1 ✔
368
                return $this;
1 ✔
369
        }
370

371

372
        /**
373
         * Returns control's HTML id.
374
         */
375
        public function getHtmlId(): string|bool|null
376
        {
377
                if (!isset($this->control->id)) {
1 ✔
378
                        $form = $this->getForm();
1 ✔
379
                        $prefix = $form instanceof Nette\Application\UI\Form || $form->getName() === null
1 ✔
380
                                ? ''
1 ✔
381
                                : $form->getName() . '-';
1 ✔
382
                        $this->control->id = sprintf(self::$idMask, $prefix . $this->lookupPath());
1 ✔
383
                }
384

385
                return $this->control->id;
1 ✔
386
        }
387

388

389
        /**
390
         * Changes control's HTML attribute.
391
         */
392
        public function setHtmlAttribute(string $name, mixed $value = true): static
393
        {
394
                $this->control->$name = $value;
1 ✔
395
                if (
396
                        $name === 'name'
1 ✔
397
                        && ($form = $this->getForm(throw: false))
1 ✔
398
                        && !$this->isDisabled()
1 ✔
399
                        && $form->isAnchored()
1 ✔
400
                        && $form->isSubmitted()
1 ✔
401
                ) {
402
                        $this->loadHttpData();
1 ✔
403
                }
404

405
                return $this;
1 ✔
406
        }
407

408

409
        #[\Deprecated('use setHtmlAttribute()')]
410
        public function setAttribute(string $name, mixed $value = true): static
411
        {
412
                trigger_error(__METHOD__ . '() was renamed to setHtmlAttribute()', E_USER_DEPRECATED);
×
413
                return $this->setHtmlAttribute($name, $value);
×
414
        }
415

416

417
        /********************* translator ****************d*g**/
418

419

420
        public function setTranslator(?Nette\Localization\Translator $translator): static
421
        {
422
                $this->translator = $translator;
1 ✔
423
                return $this;
1 ✔
424
        }
425

426

427
        /**
428
         * Returns the translator, or inherits it from the form when not explicitly set.
429
         */
430
        public function getTranslator(): ?Nette\Localization\Translator
431
        {
432
                if ($this->translator === true) {
1 ✔
433
                        return $this->getForm(throw: false)
1 ✔
434
                                ? $this->getForm()->getTranslator()
1 ✔
435
                                : null;
1 ✔
436
                }
437

438
                return $this->translator ?: null;
1 ✔
439
        }
440

441

442
        /**
443
         * Translates a string or array of strings, or returns the value unchanged without a translator or when it is HtmlStringable.
444
         */
445
        public function translate(mixed $value, mixed ...$parameters): mixed
446
        {
447
                if ($translator = $this->getTranslator()) {
1 ✔
448
                        $tmp = is_array($value) ? [&$value] : [[&$value]];
1 ✔
449
                        foreach ($tmp[0] as &$v) {
1 ✔
450
                                if ($v != null && !$v instanceof Nette\HtmlStringable) { // intentionally ==
1 ✔
451
                                        $v = $translator->translate($v, ...$parameters);
1 ✔
452
                                }
453
                        }
454
                }
455

456
                return $value;
1 ✔
457
        }
458

459

460
        /********************* rules ****************d*g**/
461

462

463
        /**
464
         * Adds a validation rule.
465
         * @param  Validation\Validator|(callable(Control, mixed): bool)|string  $validator
466
         */
467
        public function addRule(
468
                Validation\Validator|callable|string $validator,
469
                string|Stringable|null $errorMessage = null,
470
                mixed $arg = null,
471
        ): static
472
        {
473
                $this->rules->addRule($validator, $errorMessage, $arg);
1 ✔
474
                return $this;
1 ✔
475
        }
476

477

478
        /**
479
         * Adds a validation condition and returns a new branch.
480
         * @param  Validation\Validator|(callable(Control, mixed): bool)|string|bool  $validator
481
         */
482
        public function addCondition(
483
                Validation\Validator|callable|string|bool $validator,
484
                mixed $value = null,
485
        ): Rules
486
        {
487
                return $this->rules->addCondition($validator, $value);
1 ✔
488
        }
489

490

491
        /**
492
         * Adds a validation condition based on another control and returns a new branch.
493
         * @param  Validation\Validator|(callable(Control, mixed): bool)|string  $validator
494
         */
495
        public function addConditionOn(
496
                Control $control,
497
                Validation\Validator|callable|string $validator,
498
                mixed $value = null,
499
        ): Rules
500
        {
501
                return $this->rules->addConditionOn($control, $validator, $value);
1 ✔
502
        }
503

504

505
        /**
506
         * Adds an input filter callback.
507
         * @param callable(mixed): mixed  $filter
508
         */
509
        public function addFilter(callable $filter): static
510
        {
511
                $this->getRules()->addFilter($filter);
1 ✔
512
                return $this;
1 ✔
513
        }
514

515

516
        public function getRules(): Rules
517
        {
518
                return $this->rules;
1 ✔
519
        }
520

521

522
        /**
523
         * Makes control mandatory.
524
         */
525
        public function setRequired(string|Stringable|bool $value = true): static
526
        {
527
                $this->rules->setRequired($value);
1 ✔
528
                return $this;
1 ✔
529
        }
530

531

532
        /**
533
         * Is control mandatory?
534
         */
535
        public function isRequired(): bool
536
        {
537
                return $this->rules->isRequired();
1 ✔
538
        }
539

540

541
        /**
542
         * Performs server-side validation against all rules.
543
         */
544
        public function validate(): void
545
        {
546
                if ($this->isDisabled()) {
1 ✔
547
                        return;
1 ✔
548
                }
549

550
                $this->cleanErrors();
1 ✔
551
                $this->rules->validate();
1 ✔
552
        }
1 ✔
553

554

555
        /**
556
         * Adds error message to the list.
557
         */
558
        public function addError(string|Stringable $message, bool $translate = true): void
559
        {
560
                $this->errors[] = $translate ? $this->translate($message) : $message;
1 ✔
561
        }
1 ✔
562

563

564
        /**
565
         * Returns all control errors joined into one string, or null if there are no errors.
566
         */
567
        public function getError(): ?string
568
        {
569
                return $this->errors ? implode(' ', array_unique($this->errors)) : null;
1 ✔
570
        }
571

572

573
        /**
574
         * Returns all unique validation errors for this control.
575
         * @return list<string|Stringable>
576
         */
577
        public function getErrors(): array
578
        {
579
                return array_values(array_unique($this->errors));
1 ✔
580
        }
581

582

583
        public function hasErrors(): bool
584
        {
585
                return (bool) $this->errors;
1 ✔
586
        }
587

588

589
        public function cleanErrors(): void
590
        {
591
                $this->errors = [];
1 ✔
592
        }
1 ✔
593

594

595
        /********************* user data ****************d*g**/
596

597

598
        /**
599
         * Sets a rendering or user-specific option (e.g. 'description', 'class', 'id').
600
         */
601
        public function setOption(string $key, mixed $value): static
602
        {
603
                if ($value === null) {
1 ✔
604
                        unset($this->options[$key]);
×
605
                } else {
606
                        $this->options[$key] = $value;
1 ✔
607
                }
608

609
                return $this;
1 ✔
610
        }
611

612

613
        /**
614
         * Returns a rendering or user-specific option value.
615
         */
616
        public function getOption(string $key): mixed
617
        {
618
                return $this->options[$key] ?? null;
1 ✔
619
        }
620

621

622
        /**
623
         * Returns all rendering and user-specific options.
624
         * @return array<string, mixed>
625
         */
626
        public function getOptions(): array
627
        {
628
                return $this->options;
×
629
        }
630

631

632
        /********************* extension methods ****************d*g**/
633

634

635
        /** @param  mixed[]  $args */
636
        public function __call(string $name, array $args): mixed
637
        {
638
                $class = static::class;
1 ✔
639
                do {
640
                        if (isset(self::$extMethods[$name][$class])) {
1 ✔
641
                                return (self::$extMethods[$name][$class])($this, ...$args);
1 ✔
642
                        }
643

644
                        $class = get_parent_class($class);
1 ✔
645
                } while ($class);
1 ✔
646

647
                Nette\Utils\ObjectHelpers::strictCall(static::class, $name);
1 ✔
648
        }
×
649

650

651
        /** @param callable(static): mixed  $callback */
652
        public static function extensionMethod(string $name, callable $callback): void
653
        {
654
                if (str_contains($name, '::')) { // back compatibility
1 ✔
655
                        [, $name] = explode('::', $name);
×
656
                }
657

658
                self::$extMethods[$name][static::class] = $callback;
1 ✔
659
        }
1 ✔
660
}
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