forked from symfony/form
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForm.php
1031 lines (888 loc) · 26.8 KB
/
Form.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form;
use Symfony\Component\Form\Event\DataEvent;
use Symfony\Component\Form\Event\FilterDataEvent;
use Symfony\Component\Form\Exception\FormException;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Form represents a form.
*
* A form is composed of a validator schema and a widget form schema.
*
* To implement your own form fields, you need to have a thorough understanding
* of the data flow within a form field. A form field stores its data in three
* different representations:
*
* (1) the format required by the form's object
* (2) a normalized format for internal processing
* (3) the format used for display
*
* A date field, for example, may store a date as "Y-m-d" string (1) in the
* object. To facilitate processing in the field, this value is normalized
* to a DateTime object (2). In the HTML representation of your form, a
* localized string (3) is presented to and modified by the user.
*
* In most cases, format (1) and format (2) will be the same. For example,
* a checkbox field uses a Boolean value both for internal processing as for
* storage in the object. In these cases you simply need to set a value
* transformer to convert between formats (2) and (3). You can do this by
* calling appendClientTransformer() in the configure() method.
*
* In some cases though it makes sense to make format (1) configurable. To
* demonstrate this, let's extend our above date field to store the value
* either as "Y-m-d" string or as timestamp. Internally we still want to
* use a DateTime object for processing. To convert the data from string/integer
* to DateTime you can set a normalization transformer by calling
* appendNormTransformer() in configure(). The normalized data is then
* converted to the displayed data as described before.
*
* @author Fabien Potencier <[email protected]>
* @author Bernhard Schussek <[email protected]>
*/
class Form implements \IteratorAggregate, FormInterface
{
/**
* The name of this form
* @var string
*/
private $name;
/**
* The parent of this form
* @var FormInterface
*/
private $parent;
/**
* The children of this form
* @var array An array of FormInterface instances
*/
private $children = array();
/**
* The mapper for mapping data to children and back
* @var DataMapper\DataMapperInterface
*/
private $dataMapper;
/**
* The errors of this form
* @var array An array of FromError instances
*/
private $errors = array();
/**
* Whether added errors should bubble up to the parent
* @var Boolean
*/
private $errorBubbling;
/**
* Whether this form is bound
* @var Boolean
*/
private $bound = false;
/**
* Whether this form may not be empty
* @var Boolean
*/
private $required;
/**
* The form data in application format
* @var mixed
*/
private $appData;
/**
* The form data in normalized format
* @var mixed
*/
private $normData;
/**
* The form data in client format
* @var mixed
*/
private $clientData;
/**
* Data used for the client data when no value is bound
* @var mixed
*/
private $emptyData = '';
/**
* The bound values that don't belong to any children
* @var array
*/
private $extraData = array();
/**
* The transformers for transforming from application to normalized format
* and back
* @var array An array of DataTransformerInterface
*/
private $normTransformers;
/**
* The transformers for transforming from normalized to client format and
* back
* @var array An array of DataTransformerInterface
*/
private $clientTransformers;
/**
* Whether the data in application, normalized and client format is
* synchronized. Data may not be synchronized if transformation errors
* occur.
* @var Boolean
*/
private $synchronized = true;
/**
* The validators attached to this form
* @var array An array of FormValidatorInterface instances
*/
private $validators;
/**
* Whether this form may only be read, but not bound
* @var Boolean
*/
private $readOnly = false;
/**
* The dispatcher for distributing events of this form
* @var Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
private $dispatcher;
/**
* Key-value store for arbitrary attributes attached to this form
* @var array
*/
private $attributes;
/**
* The FormTypeInterface instances used to create this form
* @var array An array of FormTypeInterface
*/
private $types;
public function __construct($name, EventDispatcherInterface $dispatcher,
array $types = array(), array $clientTransformers = array(),
array $normTransformers = array(),
DataMapperInterface $dataMapper = null, array $validators = array(),
$required = false, $readOnly = false, $errorBubbling = false,
$emptyData = null, array $attributes = array())
{
foreach ($clientTransformers as $transformer) {
if (!$transformer instanceof DataTransformerInterface) {
throw new UnexpectedTypeException($transformer, 'Symfony\Component\Form\DataTransformerInterface');
}
}
foreach ($normTransformers as $transformer) {
if (!$transformer instanceof DataTransformerInterface) {
throw new UnexpectedTypeException($transformer, 'Symfony\Component\Form\DataTransformerInterface');
}
}
foreach ($validators as $validator) {
if (!$validator instanceof FormValidatorInterface) {
throw new UnexpectedTypeException($validator, 'Symfony\Component\Form\FormValidatorInterface');
}
}
$this->name = (string) $name;
$this->dispatcher = $dispatcher;
$this->types = $types;
$this->clientTransformers = $clientTransformers;
$this->normTransformers = $normTransformers;
$this->dataMapper = $dataMapper;
$this->validators = $validators;
$this->required = (Boolean) $required;
$this->readOnly = (Boolean) $readOnly;
$this->errorBubbling = (Boolean) $errorBubbling;
$this->emptyData = $emptyData;
$this->attributes = $attributes;
$this->setData(null);
}
public function __clone()
{
foreach ($this->children as $key => $child) {
$this->children[$key] = clone $child;
}
}
/**
* Returns the name by which the form is identified in forms.
*
* @return string The name of the form.
*/
public function getName()
{
return $this->name;
}
/**
* Returns the types used by this form.
*
* @return array An array of FormTypeInterface
*/
public function getTypes()
{
return $this->types;
}
/**
* Returns whether the form is required to be filled out.
*
* If the form has a parent and the parent is not required, this method
* will always return false. Otherwise the value set with setRequired()
* is returned.
*
* @return Boolean
*/
public function isRequired()
{
if (null === $this->parent || $this->parent->isRequired()) {
return $this->required;
}
return false;
}
/**
* Returns whether this form is read only.
*
* The content of a read-only form is displayed, but not allowed to be
* modified. The validation of modified read-only forms should fail.
*
* Fields whose parents are read-only are considered read-only regardless of
* their own state.
*
* @return Boolean
*/
public function isReadOnly()
{
if (null === $this->parent || !$this->parent->isReadOnly()) {
return $this->readOnly;
}
return true;
}
/**
* Sets the parent form.
*
* @param FormInterface $parent The parent form
*
* @return Form The current form
*/
public function setParent(FormInterface $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Returns the parent field.
*
* @return FormInterface The parent field
*/
public function getParent()
{
return $this->parent;
}
/**
* Returns whether the form has a parent.
*
* @return Boolean
*/
public function hasParent()
{
return null !== $this->parent;
}
/**
* Returns the root of the form tree.
*
* @return FormInterface The root of the tree
*/
public function getRoot()
{
return $this->parent ? $this->parent->getRoot() : $this;
}
/**
* Returns whether the field is the root of the form tree.
*
* @return Boolean
*/
public function isRoot()
{
return !$this->hasParent();
}
/**
* Returns whether the form has an attribute with the given name.
*
* @param string $name The name of the attribute
*/
public function hasAttribute($name)
{
return isset($this->attributes[$name]);
}
/**
* Returns the value of the attributes with the given name.
*
* @param string $name The name of the attribute
*/
public function getAttribute($name)
{
return $this->attributes[$name];
}
/**
* Updates the field with default data.
*
* @param array $appData The data formatted as expected for the underlying object
*
* @return Form The current form
*/
public function setData($appData)
{
$event = new DataEvent($this, $appData);
$this->dispatcher->dispatch(FormEvents::PRE_SET_DATA, $event);
// Hook to change content of the data
$event = new FilterDataEvent($this, $appData);
$this->dispatcher->dispatch(FormEvents::SET_DATA, $event);
$appData = $event->getData();
// Treat data as strings unless a value transformer exists
if (!$this->clientTransformers && !$this->normTransformers && is_scalar($appData)) {
$appData = (string) $appData;
}
// Synchronize representations - must not change the content!
$normData = $this->appToNorm($appData);
$clientData = $this->normToClient($normData);
$this->appData = $appData;
$this->normData = $normData;
$this->clientData = $clientData;
$this->synchronized = true;
if ($this->dataMapper) {
// Update child forms from the data
$this->dataMapper->mapDataToForms($clientData, $this->children);
}
$event = new DataEvent($this, $appData);
$this->dispatcher->dispatch(FormEvents::POST_SET_DATA, $event);
return $this;
}
/**
* Returns the data in the format needed for the underlying object.
*
* @return mixed
*/
public function getData()
{
return $this->appData;
}
/**
* Returns the data transformed by the value transformer.
*
* @return string
*/
public function getClientData()
{
return $this->clientData;
}
/**
* Returns the extra data.
*
* @return array The bound data which do not belong to a child
*/
public function getExtraData()
{
return $this->extraData;
}
/**
* Binds data to the field, transforms and validates it.
*
* @param string|array $clientData The data
*
* @return Form The current form
*
* @throws UnexpectedTypeException
*/
public function bind($clientData)
{
if ($this->readOnly) {
$this->bound = true;
return $this;
}
if (is_scalar($clientData) || null === $clientData) {
$clientData = (string) $clientData;
}
// Initialize errors in the very beginning so that we don't lose any
// errors added during listeners
$this->errors = array();
$event = new DataEvent($this, $clientData);
$this->dispatcher->dispatch(FormEvents::PRE_BIND, $event);
$appData = null;
$normData = null;
$extraData = array();
$synchronized = false;
// Hook to change content of the data bound by the browser
$event = new FilterDataEvent($this, $clientData);
$this->dispatcher->dispatch(FormEvents::BIND_CLIENT_DATA, $event);
$clientData = $event->getData();
if (count($this->children) > 0) {
if (null === $clientData || '' === $clientData) {
$clientData = array();
}
if (!is_array($clientData)) {
throw new UnexpectedTypeException($clientData, 'array');
}
foreach ($clientData as $name => $value) {
if ($this->has($name)) {
$this->children[$name]->bind($value);
} else {
$extraData[$name] = $value;
}
}
// If we have a data mapper, use old client data and merge
// data from the children into it later
if ($this->dataMapper) {
$clientData = $this->getClientData();
}
}
if (null === $clientData || '' === $clientData) {
$clientData = $this->emptyData;
if ($clientData instanceof \Closure) {
$clientData = $clientData($this);
}
}
// Merge form data from children into existing client data
if (count($this->children) > 0 && $this->dataMapper) {
$this->dataMapper->mapFormsToData($this->children, $clientData);
}
try {
// Normalize data to unified representation
$normData = $this->clientToNorm($clientData);
$synchronized = true;
} catch (TransformationFailedException $e) {
}
if ($synchronized) {
// Hook to change content of the data in the normalized
// representation
$event = new FilterDataEvent($this, $normData);
$this->dispatcher->dispatch(FormEvents::BIND_NORM_DATA, $event);
$normData = $event->getData();
// Synchronize representations - must not change the content!
$appData = $this->normToApp($normData);
$clientData = $this->normToClient($normData);
}
$this->bound = true;
$this->appData = $appData;
$this->normData = $normData;
$this->clientData = $clientData;
$this->extraData = $extraData;
$this->synchronized = $synchronized;
$event = new DataEvent($this, $clientData);
$this->dispatcher->dispatch(FormEvents::POST_BIND, $event);
return $this;
}
/**
* Binds a request to the form.
*
* If the request method is POST, PUT or GET, the data is bound to the form,
* transformed and written into the form data (an object or an array).
*
* @param Request $request The request to bind to the form
*
* @return Form This form
*
* @throws FormException if the method of the request is not one of GET, POST or PUT
*/
public function bindRequest(Request $request)
{
// Store the bound data in case of a post request
switch ($request->getMethod()) {
case 'POST':
case 'PUT':
$data = array_replace_recursive(
$request->request->get($this->getName(), array()),
$request->files->get($this->getName(), array())
);
break;
case 'GET':
$data = $request->query->get($this->getName(), array());
break;
default:
throw new FormException(sprintf('The request method "%s" is not supported', $request->getMethod()));
}
return $this->bind($data);
}
/**
* Returns the normalized data of the field.
*
* @return mixed When the field is not bound, the default data is returned.
* When the field is bound, the normalized bound data is
* returned if the field is valid, null otherwise.
*/
public function getNormData()
{
return $this->normData;
}
/**
* Adds an error to this form.
*
* @param FormError $error
*
* @return Form The current form
*/
public function addError($error, array $messageParameters = array())
{
if (! $error instanceof FormError) {
$error = new FormError($error, $messageParameters);
}
if ($this->parent && $this->errorBubbling) {
$this->parent->addError($error);
} else {
$this->errors[] = $error;
}
return $this;
}
/**
* Returns whether errors bubble up to the parent.
*
* @return Boolean
*/
public function getErrorBubbling()
{
return $this->errorBubbling;
}
/**
* Returns whether the field is bound.
*
* @return Boolean true if the form is bound to input values, false otherwise
*/
public function isBound()
{
return $this->bound;
}
/**
* Returns whether the data in the different formats is synchronized.
*
* @return Boolean
*/
public function isSynchronized()
{
return $this->synchronized;
}
/**
* Returns whether the form is empty.
*
* @return Boolean
*/
public function isEmpty()
{
foreach ($this->children as $child) {
if (!$child->isEmpty()) {
return false;
}
}
return array() === $this->appData || null === $this->appData || '' === $this->appData;
}
/**
* Returns whether the field is valid.
*
* @return Boolean
*/
public function isValid()
{
$this->validate();
if ($this->hasErrors()) {
return false;
}
if (!$this->readOnly) {
foreach ($this->children as $child) {
if (!$child->isValid()) {
return false;
}
}
}
return true;
}
/**
* Validates the form
*
* @return Form the current form
*/
public function validate()
{
foreach ($this->validators as $validator) {
$validator->validate($this);
}
return $this;
}
/**
* Returns whether or not there are errors.
*
* @return Boolean true if form is bound and not valid
*/
public function hasErrors()
{
// Don't call isValid() here, as its semantics are slightly different
// Field groups are not valid if their children are invalid, but
// hasErrors() returns only true if a field/field group itself has
// errors
return count($this->errors) > 0;
}
/**
* Returns all errors.
*
* @return array An array of FormError instances that occurred during binding
*/
public function getErrors()
{
return $this->errors;
}
/**
* Returns the DataTransformers.
*
* @return array An array of DataTransformerInterface
*/
public function getNormTransformers()
{
return $this->normTransformers;
}
/**
* Returns the DataTransformers.
*
* @return array An array of DataTransformerInterface
*/
public function getClientTransformers()
{
return $this->clientTransformers;
}
/**
* Returns all children in this group.
*
* @return array
*/
public function getChildren()
{
return $this->children;
}
/**
* Return whether the form has children.
*
* @return Boolean
*/
public function hasChildren()
{
return count($this->children) > 0;
}
/**
* Adds a child to the form.
*
* @param FormInterface $child The FormInterface to add as a child
*
* @return Form the current form
*/
public function add(FormInterface $child)
{
$this->children[$child->getName()] = $child;
$child->setParent($this);
if ($this->dataMapper) {
$this->dataMapper->mapDataToForm($this->getClientData(), $child);
}
return $this;
}
/**
* Removes a child from the form.
*
* @param string $name The name of the child to remove
*
* @return Form the current form
*/
public function remove($name)
{
if (isset($this->children[$name])) {
$this->children[$name]->setParent(null);
unset($this->children[$name]);
}
return $this;
}
/**
* Returns whether a child with the given name exists.
*
* @param string $name
*
* @return Boolean
*/
public function has($name)
{
return isset($this->children[$name]);
}
/**
* Returns the child with the given name.
*
* @param string $name
*
* @return FormInterface
*
* @throws \InvalidArgumentException if the child does not exist
*/
public function get($name)
{
if (isset($this->children[$name])) {
return $this->children[$name];
}
throw new \InvalidArgumentException(sprintf('Field "%s" does not exist.', $name));
}
/**
* Returns true if the child exists (implements the \ArrayAccess interface).
*
* @param string $name The name of the child
*
* @return Boolean true if the widget exists, false otherwise
*/
public function offsetExists($name)
{
return $this->has($name);
}
/**
* Returns the form child associated with the name (implements the \ArrayAccess interface).
*
* @param string $name The offset of the value to get
*
* @return FormInterface A form instance
*/
public function offsetGet($name)
{
return $this->get($name);
}
/**
* Adds a child to the form (implements the \ArrayAccess interface).
*
* @param string $name Ignored. The name of the child is used.
* @param FormInterface $child The child to be added
*/
public function offsetSet($name, $child)
{
$this->add($child);
}
/**
* Removes the child with the given name from the form (implements the \ArrayAccess interface).
*
* @param string $name The name of the child to be removed
*/
public function offsetUnset($name)
{
$this->remove($name);
}
/**
* Returns the iterator for this group.
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new \ArrayIterator($this->children);
}
/**
* Returns the number of form children (implements the \Countable interface).
*
* @return integer The number of embedded form children
*/
public function count()
{
return count($this->children);
}
/**
* Creates a view.
*
* @param FormView $parent The parent view
*
* @return FormView The view
*/
public function createView(FormView $parent = null)
{
if (null === $parent && $this->parent) {
$parent = $this->parent->createView();
}
$view = new FormView();
$view->setParent($parent);
$types = (array) $this->types;
foreach ($types as $type) {
$type->buildView($view, $this);
foreach ($type->getExtensions() as $typeExtension) {
$typeExtension->buildView($view, $this);
}
}
$childViews = array();
foreach ($this->children as $key => $child) {
$childViews[$key] = $child->createView($view);
}
if (null !== $prototype = $view->get('prototype')) {
$protoView = $prototype->getForm()->createView($view);
$protoTypes = $protoView->get('types');
$protoTypes[] = 'prototype';
$childViews[$prototype->getName()] = $protoView
->set('types', $protoTypes)
->set('proto_id', $view->get('id').'_prototype');
;
}
$view->setChildren($childViews);
foreach ($types as $type) {
$type->buildViewBottomUp($view, $this);
foreach ($type->getExtensions() as $typeExtension) {
$typeExtension->buildViewBottomUp($view, $this);
}
}
return $view;
}
/**
* Normalizes the value if a normalization transformer is set.
*
* @param mixed $value The value to transform
*
* @return string
*/
private function appToNorm($value)
{
foreach ($this->normTransformers as $transformer) {
$value = $transformer->transform($value);
}
return $value;
}
/**
* Reverse transforms a value if a normalization transformer is set.
*
* @param string $value The value to reverse transform
*
* @return mixed
*/
private function normToApp($value)
{
for ($i = count($this->normTransformers) - 1; $i >= 0; --$i) {
$value = $this->normTransformers[$i]->reverseTransform($value);
}
return $value;
}
/**
* Transforms the value if a value transformer is set.
*
* @param mixed $value The value to transform
*
* @return string
*/
private function normToClient($value)
{
if (!$this->clientTransformers) {
// Scalar values should always be converted to strings to