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

nette / forms / 20561735615

29 Dec 2025 12:27AM UTC coverage: 93.481% (+0.2%) from 93.237%
20561735615

push

github

dg
Container::setValues() and setDefaults() accepts array|Traversable|stdClass (BC break)

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

21 existing lines in 2 files now uncovered.

2065 of 2209 relevant lines covered (93.48%)

0.93 hits per line

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

92.63
/src/Forms/Form.php
1
<?php
2

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

8
declare(strict_types=1);
9

10
namespace Nette\Forms;
11

12
use Nette;
13
use Nette\Utils\Arrays;
14
use Nette\Utils\Html;
15
use Stringable;
16
use function array_key_first, array_merge, array_search, array_unique, count, headers_sent, in_array, is_array, is_scalar, is_string, sprintf, strcasecmp, strtolower;
17

18

19
/**
20
 * Creates, validates and renders HTML forms.
21
 *
22
 * @property-read array $errors
23
 * @property-read array $ownErrors
24
 * @property-read Html $elementPrototype
25
 * @property-deprecated FormRenderer $renderer
26
 * @property-deprecated string $action
27
 * @property-deprecated string $method
28
 */
29
class Form extends Container implements Nette\HtmlStringable
30
{
31
        /** validator */
32
        public const
33
                Equal = ':equal',
34
                IsIn = self::Equal,
35
                NotEqual = ':notEqual',
36
                IsNotIn = self::NotEqual,
37
                Filled = ':filled',
38
                Blank = ':blank',
39
                Required = self::Filled,
40
                Valid = ':valid',
41

42
                // button
43
                Submitted = ':submitted',
44

45
                // text
46
                MinLength = ':minLength',
47
                MaxLength = ':maxLength',
48
                Length = ':length',
49
                Email = ':email',
50
                URL = ':url',
51
                Pattern = ':pattern',
52
                PatternInsensitive = ':patternCaseInsensitive',
53
                Integer = ':integer',
54
                Numeric = ':numeric',
55
                Float = ':float',
56
                Min = ':min',
57
                Max = ':max',
58
                Range = ':range',
59

60
                // multiselect
61
                Count = self::Length,
62

63
                // file upload
64
                MaxFileSize = ':fileSize',
65
                MimeType = ':mimeType',
66
                Image = ':image',
67
                MaxPostSize = ':maxPostSize';
68

69
        /** method */
70
        public const
71
                Get = 'get',
72
                Post = 'post';
73

74
        /** submitted data types */
75
        public const
76
                DataText = 1,
77
                DataLine = 2,
78
                DataFile = 3,
79
                DataKeys = 8;
80

81
        /** @internal tracker ID */
82
        public const TrackerId = '_form_';
83

84
        /** @internal protection token ID */
85
        public const ProtectorId = '_token_';
86

87
        /** @deprecated use Form::Equal */
88
        public const EQUAL = self::Equal;
89

90
        /** @deprecated use Form::IsIn */
91
        public const IS_IN = self::IsIn;
92

93
        /** @deprecated use Form::NotEqual */
94
        public const NOT_EQUAL = self::NotEqual;
95

96
        /** @deprecated use Form::IsNotIn */
97
        public const IS_NOT_IN = self::IsNotIn;
98

99
        /** @deprecated use Form::Filled */
100
        public const FILLED = self::Filled;
101

102
        /** @deprecated use Form::Blank */
103
        public const BLANK = self::Blank;
104

105
        /** @deprecated use Form::Required */
106
        public const REQUIRED = self::Required;
107

108
        /** @deprecated use Form::Valid */
109
        public const VALID = self::Valid;
110

111
        /** @deprecated use Form::Submitted */
112
        public const SUBMITTED = self::Submitted;
113

114
        /** @deprecated use Form::MinLength */
115
        public const MIN_LENGTH = self::MinLength;
116

117
        /** @deprecated use Form::MaxLength */
118
        public const MAX_LENGTH = self::MaxLength;
119

120
        /** @deprecated use Form::Length */
121
        public const LENGTH = self::Length;
122

123
        /** @deprecated use Form::Email */
124
        public const EMAIL = self::Email;
125

126
        /** @deprecated use Form::Pattern */
127
        public const PATTERN = self::Pattern;
128

129
        /** @deprecated use Form::PatternCI */
130
        public const PATTERN_ICASE = self::PatternInsensitive;
131

132
        /** @deprecated use Form::Integer */
133
        public const INTEGER = self::Integer;
134

135
        /** @deprecated use Form::Numeric */
136
        public const NUMERIC = self::Numeric;
137

138
        /** @deprecated use Form::Float */
139
        public const FLOAT = self::Float;
140

141
        /** @deprecated use Form::Min */
142
        public const MIN = self::Min;
143

144
        /** @deprecated use Form::Max */
145
        public const MAX = self::Max;
146

147
        /** @deprecated use Form::Range */
148
        public const RANGE = self::Range;
149

150
        /** @deprecated use Form::Count */
151
        public const COUNT = self::Count;
152

153
        /** @deprecated use Form::MaxFileSize */
154
        public const MAX_FILE_SIZE = self::MaxFileSize;
155

156
        /** @deprecated use Form::MimeType */
157
        public const MIME_TYPE = self::MimeType;
158

159
        /** @deprecated use Form::Image */
160
        public const IMAGE = self::Image;
161

162
        /** @deprecated use Form::MaxPostSize */
163
        public const MAX_POST_SIZE = self::MaxPostSize;
164

165
        /** @deprecated use Form::Get */
166
        public const GET = self::Get;
167

168
        /** @deprecated use Form::Post */
169
        public const POST = self::Post;
170

171
        /** @deprecated use Form::DataText */
172
        public const DATA_TEXT = self::DataText;
173

174
        /** @deprecated use Form::DataLine */
175
        public const DATA_LINE = self::DataLine;
176

177
        /** @deprecated use Form::DataFile */
178
        public const DATA_FILE = self::DataFile;
179

180
        /** @deprecated use Form::DataKeys */
181
        public const DATA_KEYS = self::DataKeys;
182

183
        /** @deprecated use Form::TrackerId */
184
        public const TRACKER_ID = self::TrackerId;
185

186
        /** @deprecated use Form::ProtectorId */
187
        public const PROTECTOR_ID = self::ProtectorId;
188

189
        /**
190
         * Occurs when the form is submitted and successfully validated
191
         * @var array<callable(self, array|object): void|callable(array|object): void>
192
         */
193
        public array $onSuccess = [];
194

195
        /** @var array<callable(self): void>  Occurs when the form is submitted and is not valid */
196
        public array $onError = [];
197

198
        /** @var array<callable(self): void>  Occurs when the form is submitted */
199
        public array $onSubmit = [];
200

201
        /** @var array<callable(self): void>  Occurs before the form is rendered */
202
        public array $onRender = [];
203

204
        /** @internal used only by standalone form */
205
        public Nette\Http\IRequest $httpRequest;
206

207
        /** @var bool */
208
        protected $crossOrigin = false;
209
        private static ?Nette\Http\IRequest $defaultHttpRequest = null;
210
        private SubmitterControl|bool $submittedBy = false;
211
        private array $httpData;
212
        private Html $element;
213
        private FormRenderer $renderer;
214
        private ?Nette\Localization\Translator $translator = null;
215

216
        /** @var ControlGroup[] */
217
        private array $groups = [];
218
        private array $errors = [];
219
        private bool $beforeRenderCalled = false;
220

221

222
        public function __construct(?string $name = null)
1✔
223
        {
224
                if ($name !== null) {
1✔
225
                        $this->getElementPrototype()->id = 'frm-' . $name;
1✔
226
                        $tracker = new Controls\HiddenField($name);
1✔
227
                        $tracker->setOmitted();
1✔
228
                        $this[self::TrackerId] = $tracker;
1✔
229
                        $this->setParent(null, $name);
1✔
230
                }
231

232
                $this->monitor(self::class, function (): void {
1✔
233
                        throw new Nette\InvalidStateException('Nested forms are forbidden.');
234
                });
1✔
235
        }
1✔
236

237

238
        /**
239
         * Returns self.
240
         */
241
        public function getForm(bool $throw = true): static
1✔
242
        {
243
                return $this;
1✔
244
        }
245

246

247
        /**
248
         * Sets form's action.
249
         */
250
        public function setAction(string|Stringable $url): static
1✔
251
        {
252
                $this->getElementPrototype()->action = $url;
1✔
253
                return $this;
1✔
254
        }
255

256

257
        /**
258
         * Returns form's action.
259
         */
260
        public function getAction(): string|Stringable
261
        {
262
                return $this->getElementPrototype()->action;
1✔
263
        }
264

265

266
        /**
267
         * Sets form's method GET or POST.
268
         */
269
        public function setMethod(string $method): static
1✔
270
        {
271
                if (isset($this->httpData)) {
1✔
UNCOV
272
                        throw new Nette\InvalidStateException(__METHOD__ . '() must be called until the form is empty.');
×
273
                }
274

275
                $this->getElementPrototype()->method = strtolower($method);
1✔
276
                return $this;
1✔
277
        }
278

279

280
        /**
281
         * Returns form's method.
282
         */
283
        public function getMethod(): string
284
        {
285
                return $this->getElementPrototype()->method;
1✔
286
        }
287

288

289
        /**
290
         * Checks if the request method is the given one.
291
         */
292
        public function isMethod(string $method): bool
1✔
293
        {
294
                return strcasecmp($this->getElementPrototype()->method, $method) === 0;
1✔
295
        }
296

297

298
        /**
299
         * Changes forms's HTML attribute.
300
         */
301
        public function setHtmlAttribute(string $name, mixed $value = true): static
302
        {
UNCOV
303
                $this->getElementPrototype()->$name = $value;
×
304
                return $this;
×
305
        }
306

307

308
        /**
309
         * Disables CSRF protection using a SameSite cookie.
310
         */
311
        public function allowCrossOrigin(): void
312
        {
313
                $this->crossOrigin = true;
1✔
314
        }
1✔
315

316

317
        /**
318
         * @deprecated default protection is sufficient
319
         */
320
        public function addProtection(?string $errorMessage = null): Controls\CsrfProtection
1✔
321
        {
322
                $control = new Controls\CsrfProtection($errorMessage);
1✔
323
                $children = $this->getComponents();
1✔
324
                $first = $children ? (string) array_key_first($children) : null;
1✔
325
                $this->addComponent($control, self::ProtectorId, $first);
1✔
326
                return $control;
1✔
327
        }
328

329

330
        /**
331
         * Adds fieldset group to the form.
332
         */
333
        public function addGroup(string|Stringable|null $caption = null, bool $setAsCurrent = true): ControlGroup
1✔
334
        {
335
                $group = new ControlGroup;
1✔
336
                $group->setOption('label', $caption);
1✔
337
                $group->setOption('visual', true);
1✔
338

339
                if ($setAsCurrent) {
1✔
340
                        $this->setCurrentGroup($group);
1✔
341
                }
342

343
                return !is_scalar($caption) || isset($this->groups[$caption])
1✔
344
                        ? $this->groups[] = $group
1✔
345
                        : $this->groups[$caption] = $group;
1✔
346
        }
347

348

349
        /**
350
         * Removes fieldset group from form.
351
         */
352
        public function removeGroup(string|ControlGroup $name): void
353
        {
UNCOV
354
                if (is_string($name) && isset($this->groups[$name])) {
×
355
                        $group = $this->groups[$name];
×
356

UNCOV
357
                } elseif ($name instanceof ControlGroup && in_array($name, $this->groups, strict: true)) {
×
358
                        $group = $name;
×
359
                        $name = array_search($group, $this->groups, strict: true);
×
360

361
                } else {
UNCOV
362
                        throw new Nette\InvalidArgumentException("Group not found in form '{$this->getName()}'");
×
363
                }
364

UNCOV
365
                foreach ($group->getControls() as $control) {
×
366
                        $control->getParent()->removeComponent($control);
×
367
                }
368

UNCOV
369
                unset($this->groups[$name]);
×
370
        }
371

372

373
        /**
374
         * Returns all defined groups.
375
         * @return ControlGroup[]
376
         */
377
        public function getGroups(): array
378
        {
379
                return $this->groups;
1✔
380
        }
381

382

383
        /**
384
         * Returns the specified group.
385
         */
386
        public function getGroup(string|int $name): ?ControlGroup
1✔
387
        {
388
                return $this->groups[$name] ?? null;
1✔
389
        }
390

391

392
        /********************* translator ****************d*g**/
393

394

395
        /**
396
         * Sets translate adapter.
397
         */
398
        public function setTranslator(?Nette\Localization\Translator $translator): static
1✔
399
        {
400
                $this->translator = $translator;
1✔
401
                return $this;
1✔
402
        }
403

404

405
        /**
406
         * Returns translate adapter.
407
         */
408
        public function getTranslator(): ?Nette\Localization\Translator
409
        {
410
                return $this->translator;
1✔
411
        }
412

413

414
        /********************* submission ****************d*g**/
415

416

417
        /**
418
         * Tells if the form is anchored.
419
         */
420
        public function isAnchored(): bool
421
        {
422
                return true;
1✔
423
        }
424

425

426
        /**
427
         * Tells if the form was submitted.
428
         */
429
        public function isSubmitted(): SubmitterControl|bool
430
        {
431
                if (!isset($this->httpData)) {
1✔
432
                        $this->getHttpData();
1✔
433
                }
434

435
                return $this->submittedBy;
1✔
436
        }
437

438

439
        /**
440
         * Tells if the form was submitted and successfully validated.
441
         */
442
        public function isSuccess(): bool
443
        {
444
                return $this->isSubmitted() && $this->isValid();
1✔
445
        }
446

447

448
        /**
449
         * Sets the submittor control.
450
         * @internal
451
         */
452
        public function setSubmittedBy(?SubmitterControl $by): static
1✔
453
        {
454
                $this->submittedBy = $by ?? false;
1✔
455
                return $this;
1✔
456
        }
457

458

459
        /**
460
         * Returns submitted HTTP data.
461
         */
462
        public function getHttpData(?int $type = null, ?string $htmlName = null): string|array|Nette\Http\FileUpload|null
1✔
463
        {
464
                if (!isset($this->httpData)) {
1✔
465
                        if (!$this->isAnchored()) {
1✔
UNCOV
466
                                throw new Nette\InvalidStateException('Form is not anchored and therefore can not determine whether it was submitted.');
×
467
                        }
468

469
                        $data = $this->receiveHttpData();
1✔
470
                        $this->httpData = (array) $data;
1✔
471
                        $this->submittedBy = is_array($data);
1✔
472
                }
473

474
                return $htmlName === null
1✔
475
                        ? $this->httpData
1✔
476
                        : Helpers::extractHttpData($this->httpData, $htmlName, $type);
1✔
477
        }
478

479

480
        /**
481
         * Fires submit/click events.
482
         */
483
        public function fireEvents(): void
484
        {
485
                if (!$this->isSubmitted()) {
1✔
486
                        return;
1✔
487

488
                } elseif (!$this->getErrors()) {
1✔
489
                        $this->validate();
1✔
490
                }
491

492
                $handled = count($this->onSuccess ?? []) || count($this->onSubmit ?? []) || $this->submittedBy === true;
1✔
493

494
                if ($this->submittedBy instanceof Controls\SubmitButton) {
1✔
495
                        $handled = $handled || count($this->submittedBy->onClick ?? []);
1✔
496
                        if ($this->isValid()) {
1✔
497
                                $this->invokeHandlers($this->submittedBy->onClick, $this->submittedBy);
1✔
498
                        } else {
499
                                Arrays::invoke($this->submittedBy->onInvalidClick, $this->submittedBy);
1✔
500
                        }
501
                }
502

503
                if ($this->isValid()) {
1✔
504
                        $this->invokeHandlers($this->onSuccess);
1✔
505
                }
506

507
                if (!$this->isValid()) {
1✔
508
                        Arrays::invoke($this->onError, $this);
1✔
509
                }
510

511
                Arrays::invoke($this->onSubmit, $this);
1✔
512

513
                if (!$handled) {
1✔
514
                        trigger_error("Form was submitted but there are no associated handlers (form '{$this->getName()}').", E_USER_WARNING);
1✔
515
                }
516
        }
1✔
517

518

519
        private function invokeHandlers(iterable $handlers, $button = null): void
1✔
520
        {
521
                foreach ($handlers as $handler) {
1✔
522
                        $params = Nette\Utils\Callback::toReflection($handler)->getParameters();
1✔
523
                        $args = [];
1✔
524
                        if ($params) {
1✔
525
                                $type = Helpers::getSingleType($params[0]);
1✔
526
                                $args[] = match (true) {
1✔
527
                                        !$type => $button ?? $this,
1✔
528
                                        $this instanceof $type => $this,
1✔
529
                                        $button instanceof $type => $button,
1✔
530
                                        default => $this->getValues($type),
1✔
531
                                };
532
                                if (isset($params[1])) {
1✔
533
                                        $args[] = $this->getValues(Helpers::getSingleType($params[1]));
1✔
534
                                }
535
                        }
536

537
                        $handler(...$args);
1✔
538

539
                        if (!$this->isValid()) {
1✔
540
                                return;
1✔
541
                        }
542
                }
543
        }
1✔
544

545

546
        /**
547
         * Resets form.
548
         */
549
        public function reset(): static
550
        {
551
                $this->setSubmittedBy(null);
1✔
552
                $this->setValues([], erase: true);
1✔
553
                return $this;
1✔
554
        }
555

556

557
        /**
558
         * Internal: returns submitted HTTP data or null when form was not submitted.
559
         */
560
        protected function receiveHttpData(): ?array
561
        {
562
                $httpRequest = $this->getHttpRequest();
1✔
563
                if (strcasecmp($this->getMethod(), $httpRequest->getMethod())) {
1✔
564
                        return null;
1✔
565
                }
566

567
                if ($httpRequest->isMethod('post')) {
1✔
568
                        if (!$this->crossOrigin && !$httpRequest->isFrom('same-origin')) {
1✔
569
                                return null;
1✔
570
                        }
571

572
                        $data = Nette\Utils\Arrays::mergeTree($httpRequest->getPost(), $httpRequest->getFiles());
1✔
573
                } else {
574
                        $data = $httpRequest->getQuery();
1✔
575
                        if (!$data) {
1✔
576
                                return null;
1✔
577
                        }
578
                }
579

580
                if ($tracker = $this->getComponent(self::TrackerId, throw: false)) {
1✔
581
                        if (!isset($data[self::TrackerId]) || $data[self::TrackerId] !== $tracker->getValue()) {
1✔
UNCOV
582
                                return null;
×
583
                        }
584
                }
585

586
                return $data;
1✔
587
        }
588

589

590
        /********************* validation ****************d*g**/
591

592

593
        public function validate(?array $controls = null): void
1✔
594
        {
595
                $this->cleanErrors();
1✔
596
                if ($controls === null && $this->submittedBy instanceof SubmitterControl) {
1✔
597
                        $controls = $this->submittedBy->getValidationScope();
1✔
598
                }
599

600
                $this->validateMaxPostSize();
1✔
601
                parent::validate($controls);
1✔
602
        }
1✔
603

604

605
        /** @internal */
606
        public function validateMaxPostSize(): void
607
        {
608
                if (!$this->submittedBy || !$this->isMethod('post') || empty($_SERVER['CONTENT_LENGTH'])) {
1✔
609
                        return;
1✔
610
                }
611

612
                $maxSize = Helpers::iniGetSize('post_max_size');
1✔
613
                if ($maxSize > 0 && $maxSize < $_SERVER['CONTENT_LENGTH']) {
1✔
614
                        $this->addError(sprintf(Validator::$messages[self::MaxFileSize], $maxSize));
1✔
615
                }
616
        }
1✔
617

618

619
        /**
620
         * Adds global error message.
621
         */
622
        public function addError(string|Stringable $message, bool $translate = true): void
1✔
623
        {
624
                if ($translate && $this->translator) {
1✔
625
                        $message = $this->translator->translate($message);
1✔
626
                }
627

628
                $this->errors[] = $message;
1✔
629
        }
1✔
630

631

632
        /**
633
         * Returns global validation errors.
634
         */
635
        public function getErrors(): array
636
        {
637
                return array_unique(array_merge($this->errors, parent::getErrors()));
1✔
638
        }
639

640

641
        public function hasErrors(): bool
642
        {
643
                return (bool) $this->getErrors();
1✔
644
        }
645

646

647
        public function cleanErrors(): void
648
        {
649
                $this->errors = [];
1✔
650
        }
1✔
651

652

653
        /**
654
         * Returns form's validation errors.
655
         */
656
        public function getOwnErrors(): array
657
        {
658
                return array_unique($this->errors);
1✔
659
        }
660

661

662
        /********************* rendering ****************d*g**/
663

664

665
        /**
666
         * Returns form's HTML element template.
667
         */
668
        public function getElementPrototype(): Html
669
        {
670
                if (!isset($this->element)) {
1✔
671
                        $this->element = Html::el('form');
1✔
672
                        $this->element->action = ''; // RFC 1808 -> empty uri means 'this'
1✔
673
                        $this->element->method = self::Post;
1✔
674
                }
675

676
                return $this->element;
1✔
677
        }
678

679

680
        /**
681
         * Sets form renderer.
682
         */
683
        public function setRenderer(?FormRenderer $renderer): static
1✔
684
        {
685
                $this->renderer = $renderer;
1✔
686
                return $this;
1✔
687
        }
688

689

690
        /**
691
         * Returns form renderer.
692
         */
693
        public function getRenderer(): FormRenderer
694
        {
695
                if (!isset($this->renderer)) {
1✔
696
                        $this->renderer = new Rendering\DefaultFormRenderer;
1✔
697
                }
698

699
                return $this->renderer;
1✔
700
        }
701

702

703
        protected function beforeRender()
704
        {
705
        }
1✔
706

707

708
        /**
709
         * Must be called before form is rendered and render() is not used.
710
         */
711
        public function fireRenderEvents(): void
712
        {
713
                if (!$this->beforeRenderCalled) {
1✔
714
                        $this->beforeRenderCalled = true;
1✔
715
                        $this->beforeRender();
1✔
716
                        Arrays::invoke($this->onRender, $this);
1✔
717
                }
718
        }
1✔
719

720

721
        /**
722
         * Renders form.
723
         */
724
        public function render(...$args): void
1✔
725
        {
726
                $this->fireRenderEvents();
1✔
727
                echo $this->getRenderer()->render($this, ...$args);
1✔
728
        }
1✔
729

730

731
        /**
732
         * Renders form to string.
733
         */
734
        public function __toString(): string
735
        {
736
                $this->fireRenderEvents();
1✔
737
                return $this->getRenderer()->render($this);
1✔
738
        }
739

740

741
        public function getToggles(): array
742
        {
743
                $toggles = [];
1✔
744
                foreach ($this->getComponentTree() as $control) {
1✔
745
                        if ($control instanceof Controls\BaseControl) {
1✔
746
                                $toggles = $control->getRules()->getToggleStates($toggles);
1✔
747
                        }
748
                }
749

750
                return $toggles;
1✔
751
        }
752

753

754
        /********************* backend ****************d*g**/
755

756

757
        /**
758
         * Initialize standalone forms.
759
         */
760
        public static function initialize(bool|Nette\Http\IRequest $reinit = false): void
1✔
761
        {
762
                self::$defaultHttpRequest = match ($reinit) {
1✔
763
                        true => null,
1✔
764
                        false => self::$defaultHttpRequest ?? (new Nette\Http\RequestFactory)->fromGlobals(),
1✔
765
                        default => $reinit,
1✔
766
                };
767
        }
1✔
768

769

770
        private function getHttpRequest(): Nette\Http\IRequest
771
        {
772
                if (!isset($this->httpRequest)) {
1✔
773
                        self::initialize();
1✔
774
                        $this->httpRequest = self::$defaultHttpRequest;
1✔
775
                }
776

777
                return $this->httpRequest;
1✔
778
        }
779
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc