/
Form.php
executable file
·1301 lines (1129 loc) · 37.9 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
/**
* Base class for all forms.
* The form class is an extensible base for all forms on a sapphire application. It can be used
* either by extending it, and creating processor methods on the subclass, or by creating instances
* of form whose actions are handled by the parent controller.
*
* In either case, if you want to get a form to do anything, it must be inextricably tied to a
* controller. The constructor is passed a controller and a method on that controller. This method
* should return the form object, and it shouldn't require any arguments. Parameters, if necessary,
* can be passed using the URL or get variables. These restrictions are in place so that we can
* recreate the form object upon form submission, without the use of a session, which would be too
* resource-intensive.
*
* You will need to create at least one method for processing the submission (through {@link FormAction}).
* This method will be passed two parameters: the raw request data, and the form object.
* Usually you want to save data into a {@link DataObject} by using {@link saveInto()}.
* If you want to process the submitted data in any way, please use {@link getData()} rather than
* the raw request data.
*
* <h2>Validation</h2>
* Each form needs some form of {@link Validator} to trigger the {@link FormField->validate()} methods for each field.
* You can't disable validator for security reasons, because crucial behaviour like extension checks for file uploads depend on it.
* The default validator is an instance of {@link RequiredFields}.
* If you want to enforce serverside-validation to be ignored for a specific {@link FormField},
* you need to subclass it.
*
* <h2>URL Handling</h2>
* The form class extends {@link RequestHandler}, which means it can
* be accessed directly through a URL. This can be handy for refreshing
* a form by ajax, or even just displaying a single form field.
* You can find out the base URL for your form by looking at the
* <form action="..."> value. For example, the edit form in the CMS would be located at
* "admin/EditForm". This URL will render the form without its surrounding
* template when called through GET instead of POST.
*
* By appending to this URL, you can render invidual form elements
* through the {@link FormField->FieldHolder()} method.
* For example, the "URLSegment" field in a standard CMS form would be
* accessible through "admin/EditForm/field/URLSegment/FieldHolder".
*
* @package forms
* @subpackage core
*/
class Form extends RequestHandler {
/**
* @var boolean $includeFormTag Accessed by Form.ss; modified by {@link formHtmlContent()}.
* A performance enhancement over the generate-the-form-tag-and-then-remove-it code that was there previously
*/
public $IncludeFormTag = true;
protected $fields;
protected $actions;
protected $controller;
protected $name;
protected $validator;
protected $formMethod = "post";
protected static $current_action;
/**
* @var Dataobject $record Populated by {@link loadDataFrom()}.
*/
protected $record;
/**
* Keeps track of whether this form has a default action or not.
* Set to false by $this->disableDefaultAction();
*/
protected $hasDefaultAction = true;
/**
* Target attribute of form-tag.
* Useful to open a new window upon
* form submission.
*
* @var string
*/
protected $target;
/**
* Legend value, to be inserted into the
* <legend> element before the <fieldset>
* in Form.ss template.
*
* @var string
*/
protected $legend;
/**
* The SS template to render this form HTML into.
* Default is "Form", but this can be changed to
* another template for customisation.
*
* @see Form->setTemplate()
* @var string
*/
protected $template;
protected $buttonClickedFunc;
protected $message;
protected $messageType;
/**
* Should we redirect the user back down to the
* the form on validation errors rather then just the page
*
* @var bool
*/
protected $redirectToFormOnValidationError = false;
protected $security = true;
/**
* HACK This is a temporary hack to allow multiple calls to includeJavascriptValidation on
* the validator (if one is present).
*
* @var boolean
*/
public $jsValidationIncluded = false;
/**
* @var $extraClasses array Extra CSS-classes for the formfield-container
*/
protected $extraClasses = array();
/**
* Create a new form, with the given fields an action buttons.
*
* @param Controller $controller The parent controller, necessary to create the appropriate form action tag.
* @param String $name The method on the controller that will return this form object.
* @param FieldSet $fields All of the fields in the form - a {@link FieldSet} of {@link FormField} objects.
* @param FieldSet $actions All of the action buttons in the form - a {@link FieldSet} of {@link FormAction} objects
* @param Validator $validator Override the default validator instance (Default: {@link RequiredFields})
*/
function __construct($controller, $name, FieldSet $fields, FieldSet $actions, $validator = null) {
parent::__construct();
$fields->setForm($this);
$actions->setForm($this);
$this->fields = $fields;
$this->actions = $actions;
$this->controller = $controller;
$this->name = $name;
if(!$this->controller) user_error("$this->class form created without a controller", E_USER_ERROR);
// Form validation
$this->validator = ($validator) ? $validator : new RequiredFields();
$this->validator->setForm($this);
// Form error controls
$this->setupFormErrors();
// Check if CSRF protection is enabled, either on the parent controller or from the default setting. Note that
// method_exists() is used as some controllers (e.g. GroupTest) do not always extend from Object.
if(method_exists($controller, 'securityTokenEnabled')) {
$this->security = $controller->securityTokenEnabled();
} else {
$this->security = self::$default_security;
}
}
static $url_handlers = array(
'field/$FieldName!' => 'handleField',
'$Action!' => 'handleAction',
'POST ' => 'httpSubmission',
'GET ' => 'httpSubmission',
);
/**
* Set up current form errors in session to
* the current form if appropriate.
*/
function setupFormErrors() {
$errorInfo = Session::get("FormInfo.{$this->FormName()}");
if(isset($errorInfo['errors']) && is_array($errorInfo['errors'])) {
foreach($errorInfo['errors'] as $error) {
$field = $this->fields->dataFieldByName($error['fieldName']);
if(!$field) {
$errorInfo['message'] = $error['message'];
$errorInfo['type'] = $error['messageType'];
} else {
$field->setError($error['message'], $error['messageType']);
}
}
// load data in from previous submission upon error
if(isset($errorInfo['data'])) $this->loadDataFrom($errorInfo['data']);
}
if(isset($errorInfo['message']) && isset($errorInfo['type'])) {
$this->setMessage($errorInfo['message'], $errorInfo['type']);
}
}
/**
* Handle a form submission. GET and POST requests behave identically.
* Populates the form with {@link loadDataFrom()}, calls {@link validate()},
* and only triggers the requested form action/method
* if the form is valid.
*/
function httpSubmission($request) {
$vars = $request->requestVars();
if(isset($funcName)) {
Form::set_current_action($funcName);
}
// Populate the form
$this->loadDataFrom($vars, true);
// Protection against CSRF attacks
if($this->securityTokenEnabled()) {
$securityID = Session::get('SecurityID');
if(!$securityID || !isset($vars['SecurityID']) || $securityID != $vars['SecurityID']) {
$this->httpError(400, "SecurityID doesn't match, possible CSRF attack.");
}
}
// Determine the action button clicked
$funcName = null;
foreach($vars as $paramName => $paramVal) {
if(substr($paramName,0,7) == 'action_') {
// Break off querystring arguments included in the action
if(strpos($paramName,'?') !== false) {
list($paramName, $paramVars) = explode('?', $paramName, 2);
$newRequestParams = array();
parse_str($paramVars, $newRequestParams);
$vars = array_merge((array)$vars, (array)$newRequestParams);
}
// Cleanup action_, _x and _y from image fields
$funcName = preg_replace(array('/^action_/','/_x$|_y$/'),'',$paramName);
break;
}
}
// If the action wasnt' set, choose the default on the form.
if(!isset($funcName) && $defaultAction = $this->defaultAction()){
$funcName = $defaultAction->actionName();
}
if(isset($funcName)) {
$this->setButtonClicked($funcName);
}
// Validate the form
if(!$this->validate()) {
if(Director::is_ajax()) {
// Special case for legacy Validator.js implementation (assumes eval'ed javascript collected through FormResponse)
if($this->validator->getJavascriptValidationHandler() == 'prototype') {
return FormResponse::respond();
} else {
$acceptType = $request->getHeader('Accept');
if(strpos($acceptType, 'application/json') !== FALSE) {
// Send validation errors back as JSON with a flag at the start
$response = new SS_HTTPResponse(Convert::array2json($this->validator->getErrors()));
$response->addHeader('Content-Type', 'application/json');
} else {
$this->setupFormErrors();
// Send the newly rendered form tag as HTML
$response = new SS_HTTPResponse($this->forTemplate());
$response->addHeader('Content-Type', 'text/html');
}
return $response;
}
} else {
if($this->getRedirectToFormOnValidationError()) {
if($pageURL = $request->getHeader('Referer')) {
return Director::redirect($pageURL . '#' . $this->FormName());
}
}
return Director::redirectBack();
}
}
// First, try a handler method on the controller
if($this->controller->hasMethod($funcName)) {
return $this->controller->$funcName($vars, $this, $request);
// Otherwise, try a handler method on the form object
} else {
if($this->hasMethod($funcName)) {
return $this->$funcName($vars, $this, $request);
}
}
}
/**
* Handle a field request.
* Uses {@link Form->dataFieldByName()} to find a matching field,
* and falls back to {@link FieldSet->fieldByName()} to look
* for tabs instead. This means that if you have a tab and a
* formfield with the same name, this method gives priority
* to the formfield.
*
* @param SS_HTTPRequest $request
* @return FormField
*/
function handleField($request) {
$field = $this->dataFieldByName($request->param('FieldName'));
if($field) {
return $field;
} else {
// falling back to fieldByName, e.g. for getting tabs
return $this->Fields()->fieldByName($request->param('FieldName'));
}
}
/**
* Convert this form into a readonly form
*/
function makeReadonly() {
$this->transform(new ReadonlyTransformation());
}
/**
* Set whether the user should be redirected back down to the
* form on the page upon validation errors in the form or if
* they just need to redirect back to the page
*
* @param bool Redirect to the form
*/
public function setRedirectToFormOnValidationError($bool) {
$this->redirectToFormOnValidationError = $bool;
}
/**
* Get whether the user should be redirected back down to the
* form on the page upon validation errors
*
* @return bool
*/
public function getRedirectToFormOnValidationError() {
return $this->redirectToFormOnValidationError;
}
/**
* Add an error message to a field on this form. It will be saved into the session
* and used the next time this form is displayed.
*/
function addErrorMessage($fieldName, $message, $messageType) {
Session::addToArray("FormInfo.{$this->FormName()}.errors", array(
'fieldName' => $fieldName,
'message' => $message,
'messageType' => $messageType,
));
}
function transform(FormTransformation $trans) {
$newFields = new FieldSet();
foreach($this->fields as $field) {
$newFields->push($field->transform($trans));
}
$this->fields = $newFields;
$newActions = new FieldSet();
foreach($this->actions as $action) {
$newActions->push($action->transform($trans));
}
$this->actions = $newActions;
// We have to remove validation, if the fields are not editable ;-)
if($this->validator)
$this->validator->removeValidation();
}
/**
* Get the {@link Validator} attached to this form.
* @return Validator
*/
function getValidator() {
return $this->validator;
}
/**
* Set the {@link Validator} on this form.
*/
function setValidator( Validator $validator ) {
if($validator) {
$this->validator = $validator;
$this->validator->setForm($this);
}
}
/**
* Remove the {@link Validator} from this from.
*/
function unsetValidator(){
$this->validator = null;
}
/**
* Convert this form to another format.
*/
function transformTo(FormTransformation $format) {
$newFields = new FieldSet();
foreach($this->fields as $field) {
$newFields->push($field->transformTo($format));
}
$this->fields = $newFields;
// We have to remove validation, if the fields are not editable ;-)
if($this->validator)
$this->validator->removeValidation();
}
/**
* Generate extra special fields - namely the SecurityID field
*
* @return FieldSet
*/
public function getExtraFields() {
$extraFields = new FieldSet();
if(!$this->fields->fieldByName('SecurityID') && $this->securityTokenEnabled()) {
if(Session::get('SecurityID')) {
$securityID = Session::get('SecurityID');
} else {
$securityID = rand();
Session::set('SecurityID', $securityID);
}
$securityField = new HiddenField('SecurityID', '', $securityID);
$securityField->setForm($this);
$extraFields->push($securityField);
$this->securityTokenAdded = true;
}
// add the "real" HTTP method if necessary (for PUT, DELETE and HEAD)
if($this->FormMethod() != $this->FormHttpMethod()) {
$methodField = new HiddenField('_method', '', $this->FormHttpMethod());
$methodField->setForm($this);
$extraFields->push($methodField);
}
return $extraFields;
}
/**
* Return the form's fields - used by the templates
*
* @return FieldSet The form fields
*/
function Fields() {
foreach($this->getExtraFields() as $field) {
if(!$this->fields->fieldByName($field->Name())) $this->fields->push($field);
}
return $this->fields;
}
/**
* Return all <input type="hidden"> fields
* in a form - including fields nested in {@link CompositeFields}.
* Useful when doing custom field layouts.
*
* @return FieldSet
*/
function HiddenFields() {
return $this->fields->HiddenFields();
}
/**
* Setter for the form fields.
*
* @param FieldSet $fields
*/
function setFields($fields) {
$this->fields = $fields;
}
/**
* Get a named field from this form's fields.
* It will traverse into composite fields for you, to find the field you want.
* It will only return a data field.
*
* @return FormField
*/
function dataFieldByName($name) {
foreach($this->getExtraFields() as $field) {
if(!$this->fields->dataFieldByName($field->Name())) $this->fields->push($field);
}
return $this->fields->dataFieldByName($name);
}
/**
* Return the form's action buttons - used by the templates
*
* @return FieldSet The action list
*/
function Actions() {
return $this->actions;
}
/**
* Setter for the form actions.
*
* @param FieldSet $actions
*/
function setActions($actions) {
$this->actions = $actions;
}
/**
* Unset all form actions
*/
function unsetAllActions(){
$this->actions = new FieldSet();
}
/**
* Unset the form's action button by its name.
*
* @param string $name
*/
function unsetActionByName($name) {
$this->actions->removeByName($name);
}
/**
* Unset the form's dataField by its name
*/
function unsetDataFieldByName($fieldName){
foreach($this->Fields()->dataFields() as $child) {
if(is_object($child) && ($child->Name() == $fieldName || $child->Title() == $fieldName)) {
$child = null;
}
}
}
/**
* Remove a field from the given tab.
*/
public function unsetFieldFromTab($tabName, $fieldName) {
// Find the tab
$tab = $this->Fields()->findOrMakeTab($tabName);
$tab->removeByName($fieldName);
}
/**
* Return the attributes of the form tag - used by the templates.
*
* @return string The attribute string
*/
function FormAttributes() {
$attributes = array();
// Forms shouldn't be cached, cos their error messages won't be shown
HTTP::set_cache_age(0);
// workaround to include javascript validation
if($this->validator && !$this->jsValidationIncluded) $this->validator->includeJavascriptValidation();
// compile attributes
$attributes['id'] = $this->FormName();
$attributes['action'] = $this->FormAction();
$attributes['method'] = $this->FormMethod();
$attributes['enctype'] = $this->FormEncType();
if($this->target) $attributes['target'] = $this->target;
if($this->extraClass()) $attributes['class'] = $this->extraClass();
if($this->validator && $this->validator->getErrors()) {
if(!isset($attributes['class'])) $attributes['class'] = '';
$attributes['class'] .= ' validationerror';
}
// implode attributes into string
$preparedAttributes = '';
foreach($attributes as $k => $v) {
// Note: as indicated by the $k == value item here; the decisions over what to include in the attributes can sometimes get finicky
if(!empty($v) || $v === '0' || $k == 'value') $preparedAttributes .= " $k=\"" . Convert::raw2att($v) . "\"";
}
return $preparedAttributes;
}
/**
* Set the target of this form to any value - useful for opening the form contents in a new window or refreshing another frame
*
* @param target The value of the target
*/
function setTarget($target) {
$this->target = $target;
}
/**
* Set the legend value to be inserted into
* the <legend> element in the Form.ss template.
*/
function setLegend($legend) {
$this->legend = $legend;
}
/**
* Set the SS template that this form should use
* to render with. The default is "Form".
*
* @param string $template The name of the template (without the .ss extension)
*/
function setTemplate($template) {
$this->template = $template;
}
/**
* Return the template to render this form with.
* If the template isn't set, then default to the
* form class name e.g "Form".
*
* @return string
*/
function getTemplate() {
if($this->template) return $this->template;
else return $this->class;
}
/**
* Returns the encoding type of the form.
* This will be either "multipart/form-data"" if there are any {@link FileField} instances,
* otherwise "application/x-www-form-urlencoded"
*
* @return string The encoding mime type
*/
function FormEncType() {
if(is_array($this->fields->dataFields())){
foreach($this->fields->dataFields() as $field) {
if(is_a($field, "FileField")) return "multipart/form-data";
}
}
return "application/x-www-form-urlencoded";
}
/**
* Returns the real HTTP method for the form:
* GET, POST, PUT, DELETE or HEAD.
* As most browsers only support GET and POST in
* form submissions, all other HTTP methods are
* added as a hidden field "_method" that
* gets evaluated in {@link Director::direct()}.
* See {@link FormMethod()} to get a HTTP method
* for safe insertion into a <form> tag.
*
* @return string HTTP method
*/
function FormHttpMethod() {
return $this->formMethod;
}
/**
* Returns the form method to be used in the <form> tag.
* See {@link FormHttpMethod()} to get the "real" method.
*
* @return string Form tag compatbile HTTP method: 'get' or 'post'
*/
function FormMethod() {
if(in_array($this->formMethod,array('get','post'))) {
return $this->formMethod;
} else {
return 'post';
}
}
/**
* Set the form method: GET, POST, PUT, DELETE.
*
* @param $method string
*/
function setFormMethod($method) {
$this->formMethod = strtolower($method);
}
/**
* Return the form's action attribute.
* This is build by adding an executeForm get variable to the parent controller's Link() value
*
* @return string
*/
function FormAction() {
if ($this->formActionPath) {
return $this->formActionPath;
} elseif($this->controller->hasMethod("FormObjectLink")) {
return $this->controller->FormObjectLink($this->name);
} else {
return Controller::join_links($this->controller->Link(), $this->name);
}
}
/** @ignore */
private $formActionPath = false;
/**
* Set the form action attribute to a custom URL.
*
* Note: For "normal" forms, you shouldn't need to use this method. It is recommended only for situations where you have
* two relatively distinct parts of the system trying to communicate via a form post.
*/
function setFormAction($path) {
$this->formActionPath = $path;
}
/**
* @ignore
*/
private $htmlID = null;
/**
* Returns the name of the form
*/
function FormName() {
if($this->htmlID) return $this->htmlID;
else return $this->class . '_' . str_replace(array('.','/'),'',$this->name);
}
/**
* Set the HTML ID attribute of the form
*/
function setHTMLID($id) {
$this->htmlID = $id;
}
/**
* Returns this form's controller
*/
function Controller() {
return $this->controller;
}
/**
* @return string
*/
function Name() {
return $this->name;
}
/**
* Returns an object where there is a method with the same name as each data field on the form.
* That method will return the field itself.
* It means that you can execute $firstNameField = $form->FieldMap()->FirstName(), which can be handy
*/
function FieldMap() {
return new Form_FieldMap($this);
}
/**
* The next functions store and modify the forms
* message attributes. messages are stored in session under
* $_SESSION[formname][message];
*
* @return string
*/
function Message() {
$this->getMessageFromSession();
$message = $this->message;
$this->clearMessage();
return $message;
}
/**
* @return string
*/
function MessageType() {
$this->getMessageFromSession();
return $this->messageType;
}
protected function getMessageFromSession() {
if($this->message || $this->messageType) {
return $this->message;
}else{
$this->message = Session::get("FormInfo.{$this->FormName()}.formError.message");
$this->messageType = Session::get("FormInfo.{$this->FormName()}.formError.type");
Session::clear("FormInfo.{$this->FormName()}");
}
}
/**
* Set a status message for the form.
*
* @param message the text of the message
* @param type Should be set to good, bad, or warning.
*/
function setMessage($message, $type) {
$this->message = $message;
$this->messageType = $type;
}
/**
* Set a message to the session, for display next time this form is shown.
*
* @param message the text of the message
* @param type Should be set to good, bad, or warning.
*/
function sessionMessage($message, $type) {
Session::set("FormInfo.{$this->FormName()}.formError.message", $message);
Session::set("FormInfo.{$this->FormName()}.formError.type", $type);
}
static function messageForForm( $formName, $message, $type ) {
Session::set("FormInfo.{$formName}.formError.message", $message);
Session::set("FormInfo.{$formName}.formError.type", $type);
}
function clearMessage() {
$this->message = null;
Session::clear("FormInfo.{$this->FormName()}.errors");
Session::clear("FormInfo.{$this->FormName()}.formError");
}
function resetValidation() {
Session::clear("FormInfo.{$this->FormName()}.errors");
}
/**
* Returns the DataObject that has given this form its data
* through {@link loadDataFrom()}.
*
* @return DataObject
*/
function getRecord() {
return $this->record;
}
/**
* Get the legend value to be inserted into the
* <legend> element in Form.ss
*
* @return string
*/
function getLegend() {
return $this->legend;
}
/**
* Processing that occurs before a form is executed.
* This includes form validation, if it fails, we redirect back
* to the form with appropriate error messages.
* Triggered through {@link httpSubmission()} which is triggered
*/
function validate(){
if($this->validator){
$errors = $this->validator->validate();
if($errors){
if(Director::is_ajax() && $this->validator->getJavascriptValidationHandler() == 'prototype') {
FormResponse::status_message(_t('Form.VALIDATIONFAILED', 'Validation failed'), 'bad');
foreach($errors as $error) {
FormResponse::add(sprintf(
"validationError('%s', '%s', '%s');\n",
Convert::raw2js($error['fieldName']),
Convert::raw2js($error['message']),
Convert::raw2js($error['messageType'])
));
}
} else {
$data = $this->getData();
// Load errors into session and post back
Session::set("FormInfo.{$this->FormName()}", array(
'errors' => $errors,
'data' => $data,
));
}
return false;
}
}
return true;
}
/**
* Load data from the given DataObject or array.
* It will call $object->MyField to get the value of MyField.
* If you passed an array, it will call $object[MyField].
* Doesn't save into dataless FormFields ({@link DatalessField}),
* as determined by {@link FieldSet->dataFields()}.
*
* By default, if a field isn't set (as determined by isset()),
* its value will not be saved to the field, retaining
* potential existing values.
*
* Passed data should not be escaped, and is saved to the FormField instances unescaped.
* Escaping happens automatically on saving the data through {@link saveInto()}.
*
* @uses FieldSet->dataFields()
* @uses FormField->setValue()
*
* @param array|DataObject $data
* @param boolean $clearMissingFields By default, fields which don't match
* a property or array-key of the passed {@link $data} argument are "left alone",
* meaning they retain any previous values (if present). If this flag is set to true,
* those fields are overwritten with null regardless if they have a match in {@link $data}.
* @param $fieldList An optional list of fields to process. This can be useful when you have a
* form that has some fields that save to one object, and some that save to another.
*/
function loadDataFrom($data, $clearMissingFields = false, $fieldList = null) {
if(!is_object($data) && !is_array($data)) {
user_error("Form::loadDataFrom() not passed an array or an object", E_USER_WARNING);
return false;
}
// if an object is passed, save it for historical reference through {@link getRecord()}
if(is_object($data)) $this->record = $data;
// dont include fields without data
$dataFields = $this->fields->dataFields();
if($dataFields) foreach($dataFields as $field) {
$name = $field->Name();
// Skip fields that have been exlcuded
if($fieldList && !in_array($name, $fieldList)) continue;
// First check looks for (fieldname)_unchanged, an indicator that we shouldn't overwrite the field value
if(is_array($data) && isset($data[$name . '_unchanged'])) continue;
// get value in different formats
$hasObjectValue = false;
if(
is_object($data)
&& (
isset($data->$name)
|| $data->hasMethod($name)
|| ($data->hasMethod('hasField') && $data->hasField($name))
)
) {
// We don't actually call the method because it might be slow.
// In a later release, relation methods will just return references to the query that should be executed,
// and so we will be able to safely pass the return value of the
// relation method to the first argument of setValue
$val = $data->__get($name);
$hasObjectValue = true;
} else if(strpos($name,'[') && is_array($data) && !isset($data[$name])) {
// if field is in array-notation, we need to resolve the array-structure PHP creates from query-strings
preg_match('/' . addcslashes($name,'[]') . '=([^&]*)/', urldecode(http_build_query($data)), $matches);
$val = isset($matches[1]) ? $matches[1] : null;
} elseif(is_array($data) && array_key_exists($name, $data)) {
// else we assume its a simple keyed array
$val = $data[$name];
} else {
$val = null;
}
// save to the field if either a value is given, or loading of blank/undefined values is forced
if(isset($val) || $hasObjectValue || $clearMissingFields) {
// pass original data as well so composite fields can act on the additional information
$field->setValue($val, $data);
}
}
}
/**
* Save the contents of this form into the given data object.
* It will make use of setCastedField() to do this.
*
* @param $dataObject The object to save data into
* @param $fieldList An optional list of fields to process. This can be useful when you have a
* form that has some fields that save to one object, and some that save to another.
*/
function saveInto(DataObjectInterface $dataObject, $fieldList = null) {
$dataFields = $this->fields->saveableFields();
$lastField = null;
if($dataFields) foreach($dataFields as $field) {
// Skip fields that have been exlcuded
if($fieldList && is_array($fieldList) && !in_array($field->Name(), $fieldList)) continue;
$saveMethod = "save{$field->Name()}";
if($field->Name() == "ClassName"){
$lastField = $field;
}else if( $dataObject->hasMethod( $saveMethod ) ){
$dataObject->$saveMethod( $field->dataValue());
} else if($field->Name() != "ID"){
$field->saveInto($dataObject);
}
}
if($lastField) $lastField->saveInto($dataObject);
}
/**
* Get the submitted data from this form through
* {@link FieldSet->dataFields()}, which filters out
* any form-specific data like form-actions.
* Calls {@link FormField->dataValue()} on each field,