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

nette / forms / 21851792823

10 Feb 2026 04:31AM UTC coverage: 93.412% (-0.07%) from 93.481%
21851792823

push

github

dg
component/model 4 WIP

2070 of 2216 relevant lines covered (93.41%)

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 string[] $errors
23
 * @property-read array<string|Stringable> $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, mixed[]|object): void | callable(mixed[]|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

212
        /** @var mixed[] */
213
        private array $httpData;
214
        private Html $element;
215
        private FormRenderer $renderer;
216
        private ?Nette\Localization\Translator $translator = null;
217

218
        /** @var ControlGroup[] */
219
        private array $groups = [];
220

221
        /** @var list<string|Stringable> */
222
        private array $errors = [];
223
        private bool $beforeRenderCalled = false;
224

225

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

236
                $this->monitor(self::class, function (): void {
1✔
237
                        throw new Nette\InvalidStateException('Nested forms are forbidden.');
238
                });
1✔
239
        }
1✔
240

241

242
        /**
243
         * Returns self.
244
         */
245
        public function getForm(bool $throw = true): static
1✔
246
        {
247
                return $this;
1✔
248
        }
249

250

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

260

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

269

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

279
                $this->getElementPrototype()->method = strtolower($method);
1✔
280
                return $this;
1✔
281
        }
282

283

284
        /**
285
         * Returns form's method.
286
         */
287
        public function getMethod(): string
288
        {
289
                return $this->getElementPrototype()->method;
1✔
290
        }
291

292

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

301

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

311

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

320

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

333

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

343
                if ($setAsCurrent) {
1✔
344
                        $this->setCurrentGroup($group);
1✔
345
                }
346

347
                return !is_scalar($caption) || isset($this->groups[$caption])
1✔
348
                        ? $this->groups[] = $group
1✔
349
                        : $this->groups[$caption] = $group;
1✔
350
        }
351

352

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

361
                } elseif ($name instanceof ControlGroup && in_array($name, $this->groups, strict: true)) {
×
362
                        $group = $name;
×
363
                        $name = array_search($group, $this->groups, strict: true);
×
364

365
                } else {
366
                        throw new Nette\InvalidArgumentException("Group not found in form '{$this->getName()}'");
×
367
                }
368

369
                foreach ($group->getControls() as $control) {
×
370
                        $control->getParent()->removeComponent($control);
×
371
                }
372

373
                unset($this->groups[$name]);
×
374
        }
375

376

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

386

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

395

396
        /********************* translator ****************d*g**/
397

398

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

408

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

417

418
        /********************* submission ****************d*g**/
419

420

421
        /**
422
         * Tells if the form is anchored.
423
         */
424
        public function isAnchored(): bool
425
        {
426
                return true;
1✔
427
        }
428

429

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

439
                return $this->submittedBy;
1✔
440
        }
441

442

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

451

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

462

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

474
                        $data = $this->receiveHttpData();
1✔
475
                        $this->httpData = (array) $data;
1✔
476
                        $this->submittedBy = is_array($data);
1✔
477
                }
478

479
                return $htmlName === null
1✔
480
                        ? $this->httpData
1✔
481
                        : Helpers::extractHttpData($this->httpData, $htmlName, $type);
1✔
482
        }
483

484

485
        /**
486
         * Fires submit/click events.
487
         */
488
        public function fireEvents(): void
489
        {
490
                if (!$this->isSubmitted()) {
1✔
491
                        return;
1✔
492

493
                } elseif (!$this->getErrors()) {
1✔
494
                        $this->validate();
1✔
495
                }
496

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

499
                if ($this->submittedBy instanceof Controls\SubmitButton) {
1✔
500
                        $handled = $handled || count($this->submittedBy->onClick ?? []);
1✔
501
                        if ($this->isValid()) {
1✔
502
                                $this->invokeHandlers($this->submittedBy->onClick, $this->submittedBy);
1✔
503
                        } else {
504
                                Arrays::invoke($this->submittedBy->onInvalidClick, $this->submittedBy);
1✔
505
                        }
506
                }
507

508
                if ($this->isValid()) {
1✔
509
                        $this->invokeHandlers($this->onSuccess);
1✔
510
                }
511

512
                if (!$this->isValid()) {
1✔
513
                        Arrays::invoke($this->onError, $this);
1✔
514
                }
515

516
                Arrays::invoke($this->onSubmit, $this);
1✔
517

518
                if (!$handled) {
1✔
519
                        trigger_error("Form was submitted but there are no associated handlers (form '{$this->getName()}').", E_USER_WARNING);
1✔
520
                }
521
        }
1✔
522

523

524
        /** @param  iterable<callable>  $handlers */
525
        private function invokeHandlers(iterable $handlers, ?SubmitterControl $button = null): void
1✔
526
        {
527
                foreach ($handlers as $handler) {
1✔
528
                        $params = Nette\Utils\Callback::toReflection($handler)->getParameters();
1✔
529
                        $args = [];
1✔
530
                        if ($params) {
1✔
531
                                $type = Helpers::getSingleType($params[0]);
1✔
532
                                $args[] = match (true) {
1✔
533
                                        !$type => $button ?? $this,
1✔
534
                                        $this instanceof $type => $this,
1✔
535
                                        $button instanceof $type => $button,
1✔
536
                                        default => $this->getValues($type),
1✔
537
                                };
538
                                if (isset($params[1])) {
1✔
539
                                        $args[] = $this->getValues(Helpers::getSingleType($params[1]));
1✔
540
                                }
541
                        }
542

543
                        $handler(...$args);
1✔
544

545
                        if (!$this->isValid()) {
1✔
546
                                return;
1✔
547
                        }
548
                }
549
        }
1✔
550

551

552
        /**
553
         * Resets form.
554
         */
555
        public function reset(): static
556
        {
557
                $this->setSubmittedBy(null);
1✔
558
                $this->setValues([], erase: true);
1✔
559
                return $this;
1✔
560
        }
561

562

563
        /**
564
         * Internal: returns submitted HTTP data or null when form was not submitted.
565
         * @return ?mixed[]
566
         */
567
        protected function receiveHttpData(): ?array
568
        {
569
                $httpRequest = $this->getHttpRequest();
1✔
570
                if (strcasecmp($this->getMethod(), $httpRequest->getMethod())) {
1✔
571
                        return null;
1✔
572
                }
573

574
                if ($httpRequest->isMethod('post')) {
1✔
575
                        if (!$this->crossOrigin && !$httpRequest->isFrom('same-origin')) {
1✔
576
                                return null;
1✔
577
                        }
578

579
                        $data = Nette\Utils\Arrays::mergeTree($httpRequest->getPost(), $httpRequest->getFiles());
1✔
580
                } else {
581
                        $data = $httpRequest->getQuery();
1✔
582
                        if (!$data) {
1✔
583
                                return null;
1✔
584
                        }
585
                }
586

587
                if ($tracker = $this->getComponent(self::TrackerId, throw: false)) {
1✔
588
                        if (!isset($data[self::TrackerId]) || $data[self::TrackerId] !== $tracker->getValue()) {
1✔
589
                                return null;
×
590
                        }
591
                }
592

593
                return $data;
1✔
594
        }
595

596

597
        /********************* validation ****************d*g**/
598

599

600
        /** @param  ?(Control|Container)[]  $controls */
601
        public function validate(?array $controls = null): void
1✔
602
        {
603
                $this->cleanErrors();
1✔
604
                if ($controls === null && $this->submittedBy instanceof SubmitterControl) {
1✔
605
                        $controls = $this->submittedBy->getValidationScope();
1✔
606
                }
607

608
                $this->validateMaxPostSize();
1✔
609
                parent::validate($controls);
1✔
610
        }
1✔
611

612

613
        /** @internal */
614
        public function validateMaxPostSize(): void
615
        {
616
                if (!$this->submittedBy || !$this->isMethod('post') || empty($_SERVER['CONTENT_LENGTH'])) {
1✔
617
                        return;
1✔
618
                }
619

620
                $maxSize = Helpers::iniGetSize('post_max_size');
1✔
621
                if ($maxSize > 0 && $maxSize < $_SERVER['CONTENT_LENGTH']) {
1✔
622
                        $this->addError(sprintf(Validator::$messages[self::MaxFileSize], $maxSize));
1✔
623
                }
624
        }
1✔
625

626

627
        /**
628
         * Adds global error message.
629
         */
630
        public function addError(string|Stringable $message, bool $translate = true): void
1✔
631
        {
632
                if ($translate && $this->translator) {
1✔
633
                        $message = $this->translator->translate($message);
1✔
634
                }
635

636
                $this->errors[] = $message;
1✔
637
        }
1✔
638

639

640
        /**
641
         * Returns global validation errors.
642
         * @return string[]
643
         */
644
        public function getErrors(): array
645
        {
646
                return array_unique(array_merge($this->errors, parent::getErrors()));
1✔
647
        }
648

649

650
        public function hasErrors(): bool
651
        {
652
                return (bool) $this->getErrors();
1✔
653
        }
654

655

656
        public function cleanErrors(): void
657
        {
658
                $this->errors = [];
1✔
659
        }
1✔
660

661

662
        /**
663
         * Returns form's validation errors.
664
         * @return list<string|Stringable>
665
         */
666
        public function getOwnErrors(): array
667
        {
668
                return array_unique($this->errors);
1✔
669
        }
670

671

672
        /********************* rendering ****************d*g**/
673

674

675
        /**
676
         * Returns form's HTML element template.
677
         */
678
        public function getElementPrototype(): Html
679
        {
680
                if (!isset($this->element)) {
1✔
681
                        $this->element = Html::el('form');
1✔
682
                        $this->element->action = ''; // RFC 1808 -> empty uri means 'this'
1✔
683
                        $this->element->method = self::Post;
1✔
684
                }
685

686
                return $this->element;
1✔
687
        }
688

689

690
        /**
691
         * Sets form renderer.
692
         */
693
        public function setRenderer(?FormRenderer $renderer): static
1✔
694
        {
695
                $this->renderer = $renderer;
1✔
696
                return $this;
1✔
697
        }
698

699

700
        /**
701
         * Returns form renderer.
702
         */
703
        public function getRenderer(): FormRenderer
704
        {
705
                if (!isset($this->renderer)) {
1✔
706
                        $this->renderer = new Rendering\DefaultFormRenderer;
1✔
707
                }
708

709
                return $this->renderer;
1✔
710
        }
711

712

713
        protected function beforeRender()
714
        {
715
        }
1✔
716

717

718
        /**
719
         * Must be called before form is rendered and render() is not used.
720
         */
721
        public function fireRenderEvents(): void
722
        {
723
                if (!$this->beforeRenderCalled) {
1✔
724
                        $this->beforeRenderCalled = true;
1✔
725
                        $this->beforeRender();
1✔
726
                        Arrays::invoke($this->onRender, $this);
1✔
727
                }
728
        }
1✔
729

730

731
        /**
732
         * Renders form.
733
         */
734
        public function render(mixed ...$args): void
1✔
735
        {
736
                $this->fireRenderEvents();
1✔
737
                echo $this->getRenderer()->render($this, ...$args);
1✔
738
        }
1✔
739

740

741
        /**
742
         * Renders form to string.
743
         */
744
        public function __toString(): string
745
        {
746
                $this->fireRenderEvents();
1✔
747
                return $this->getRenderer()->render($this);
1✔
748
        }
749

750

751
        /** @return array<string, bool> */
752
        public function getToggles(): array
753
        {
754
                $toggles = [];
1✔
755
                foreach ($this->getComponentTree() as $control) {
1✔
756
                        if ($control instanceof Controls\BaseControl) {
1✔
757
                                $toggles = $control->getRules()->getToggleStates($toggles);
1✔
758
                        }
759
                }
760

761
                return $toggles;
1✔
762
        }
763

764

765
        /********************* backend ****************d*g**/
766

767

768
        /**
769
         * Initialize standalone forms.
770
         */
771
        public static function initialize(bool|Nette\Http\IRequest $reinit = false): void
1✔
772
        {
773
                self::$defaultHttpRequest = match ($reinit) {
1✔
774
                        true => null,
1✔
775
                        false => self::$defaultHttpRequest ?? (new Nette\Http\RequestFactory)->fromGlobals(),
1✔
776
                        default => $reinit,
1✔
777
                };
778
        }
1✔
779

780

781
        private function getHttpRequest(): Nette\Http\IRequest
782
        {
783
                if (!isset($this->httpRequest)) {
1✔
784
                        self::initialize();
1✔
785
                        $this->httpRequest = self::$defaultHttpRequest;
1✔
786
                }
787

788
                return $this->httpRequest;
1✔
789
        }
790
}
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

© 2026 Coveralls, Inc