-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
FormHelper.php
executable file
·2540 lines (2334 loc) · 78.7 KB
/
FormHelper.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
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 0.10.0.1076
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\View\Helper;
use Cake\Core\Configure;
use Cake\Error;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
use Cake\Utility\Inflector;
use Cake\Utility\Security;
use Cake\View\Form\ArrayContext;
use Cake\View\Form\ContextInterface;
use Cake\View\Form\EntityContext;
use Cake\View\Form\NullContext;
use Cake\View\Helper;
use Cake\View\Helper\StringTemplateTrait;
use Cake\View\StringTemplate;
use Cake\View\View;
use Cake\View\Widget\WidgetRegistry;
use DateTime;
use Traversable;
/**
* Form helper library.
*
* Automatic generation of HTML FORMs from given data.
*
* @property HtmlHelper $Html
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
*/
class FormHelper extends Helper {
use StringTemplateTrait;
/**
* Other helpers used by FormHelper
*
* @var array
*/
public $helpers = array('Html');
/**
* Options used by DateTime fields
*
* @var array
*/
protected $_options = array(
'day' => array(), 'minute' => array(), 'hour' => array(),
'month' => array(), 'year' => array(), 'meridian' => array()
);
/**
* The various pickers that make up a datetime picker.
*
* @var array
*/
protected $_datetimeParts = ['year', 'month', 'day', 'hour', 'minute', 'second', 'meridian'];
/**
* Settings for the helper.
*
* @var array
*/
public $settings = [
'errorClass' => 'form-error'
];
/**
* List of fields created, used with secure forms.
*
* @var array
*/
public $fields = array();
/**
* Constant used internally to skip the securing process,
* and neither add the field to the hash or to the unlocked fields.
*
* @var string
*/
const SECURE_SKIP = 'skip';
/**
* Defines the type of form being created. Set by FormHelper::create().
*
* @var string
*/
public $requestType = null;
/**
* Persistent default options used by input(). Set by FormHelper::create().
*
* @var array
*/
protected $_inputDefaults = array();
/**
* An array of field names that have been excluded from
* the Token hash used by SecurityComponent's validatePost method
*
* @see FormHelper::_secure()
* @see SecurityComponent::validatePost()
* @var array
*/
protected $_unlockedFields = array();
/**
* Registry for input widgets.
*
* @var \Cake\View\Widget\WidgetRegistry
*/
protected $_registry;
/**
* Context for the current form.
*
* @var \Cake\View\Form\Context
*/
protected $_context;
/**
* Context provider methods.
*
* @var array
* @see addContextProvider
*/
protected $_contextProviders;
/**
* Default templates the FormHelper uses.
*
* @var array
*/
protected $_defaultTemplates = [
'button' => '<button{{attrs}}>{{text}}</button>',
'checkbox' => '<input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>',
'checkboxContainer' => '<div class="checkbox">{{input}}{{label}}</div>',
'dateWidget' => '{{month}}{{day}}{{year}}{{hour}}{{minute}}{{second}}{{meridian}}',
'error' => '<div class="error-message">{{content}}</div>',
'errorList' => '<ul>{{content}}</ul>',
'errorItem' => '<li>{{text}}</li>',
'file' => '<input type="file" name="{{name}}"{{attrs}}>',
'formstart' => '<form{{attrs}}>',
'formend' => '</form>',
'hiddenblock' => '<div style="display:none;">{{content}}</div>',
'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}>',
'label' => '<label{{attrs}}>{{text}}</label>',
'option' => '<option value="{{value}}"{{attrs}}>{{text}}</option>',
'optgroup' => '<optgroup label="{{label}}"{{attrs}}>{{content}}</optgroup>',
'select' => '<select name="{{name}}"{{attrs}}>{{content}}</select>',
'selectMultiple' => '<select name="{{name}}[]" multiple="multiple"{{attrs}}>{{content}}</select>',
'radio' => '<input type="radio" name="{{name}}" value="{{value}}"{{attrs}}>',
'radioContainer' => '{{input}}{{label}}',
'textarea' => '<textarea name="{{name}}"{{attrs}}>{{value}}</textarea>',
];
/**
* Copies the validationErrors variable from the View object into this instance
*
* @param \Cake\View\View $View The View this helper is being attached to.
* @param array $settings Configuration settings for the helper.
*/
public function __construct(View $View, $settings = array()) {
$settings += ['widgets' => [], 'templates' => null, 'registry' => null];
parent::__construct($View, $settings);
$this->initStringTemplates($this->_defaultTemplates);
$this->widgetRegistry($settings['registry'], $settings['widgets']);
unset($this->settings['widgets'], $this->settings['registry']);
$this->_addDefaultContextProviders();
}
/**
* Set the input registry the helper will use.
*
* @param \Cake\View\Widget\WidgetRegistry $instance The registry instance to set.
* @param array $widgets An array of widgets
* @return \Cake\View\Widget\WidgetRegistry
*/
public function widgetRegistry(WidgetRegistry $instance = null, $widgets = []) {
if ($instance === null) {
if ($this->_registry === null) {
$this->_registry = new WidgetRegistry($this->_templater, $widgets);
}
return $this->_registry;
}
$this->_registry = $instance;
return $this->_registry;
}
/**
* Add the default suite of context providers provided by CakePHP.
*
* @return void
*/
protected function _addDefaultContextProviders() {
$this->addContextProvider('array', function ($request, $data) {
if (is_array($data['entity']) && isset($data['entity']['schema'])) {
return new ArrayContext($request, $data['entity']);
}
});
$this->addContextProvider('orm', function ($request, $data) {
if (
$data['entity'] instanceof Entity ||
$data['entity'] instanceof Traversable ||
(is_array($data['entity']) && !isset($data['entity']['schema']))
) {
return new EntityContext($request, $data);
}
});
}
/**
* Returns if a field is required to be filled based on validation properties from the validating object.
*
* @param \Cake\Validation\ValidationSet $validationRules
* @return boolean true if field is required to be filled, false otherwise
*/
protected function _isRequiredField($validationRules) {
if (empty($validationRules) || count($validationRules) === 0) {
return false;
}
$validationRules->isUpdate($this->requestType === 'put');
foreach ($validationRules as $rule) {
if ($rule->skip()) {
continue;
}
return !$validationRules->isEmptyAllowed();
}
return false;
}
/**
* Returns an HTML FORM element.
*
* ### Options:
*
* - `type` Form method defaults to autodetecting based on the form context. If
* the form context's isCreate() method returns false, a PUT request will be done.
* - `action` The controller action the form submits to, (optional). Use this option if you
* don't need to change the controller from the current request's controller.
* - `url` The URL the form submits to. Can be a string or a URL array. If you use 'url'
* you should leave 'action' undefined.
* - `default` Allows for the creation of Ajax forms. Set this to false to prevent the default event handler.
* Will create an onsubmit attribute if it doesn't not exist. If it does, default action suppression
* will be appended.
* - `onsubmit` Used in conjunction with 'default' to create ajax forms.
* - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
* - `context` Additional options for the context class. For example the EntityContext accepts a 'table'
* option that allows you to set the specific Table class the form should be based on.
*
* @param mixed $model The context for which the form is being defined. Can
* be an ORM entity, ORM resultset, or an array of meta data. You can use false or null
* to make a model-less form.
* @param array $options An array of html attributes and options.
* @return string An formatted opening FORM tag.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create
*/
public function create($model = null, $options = []) {
$append = '';
if (empty($options['context'])) {
$options['context'] = [];
}
$options['context']['entity'] = $model;
$context = $this->_getContext($options['context']);
unset($options['context']);
$isCreate = $context->isCreate();
$options = $options + [
'type' => $isCreate ? 'post' : 'put',
'action' => null,
'url' => null,
'default' => true,
'encoding' => strtolower(Configure::read('App.encoding')),
];
$action = $this->url($this->_formUrl($context, $options));
unset($options['url'], $options['action']);
$htmlAttributes = [];
switch (strtolower($options['type'])) {
case 'get':
$htmlAttributes['method'] = 'get';
break;
case 'file':
$htmlAttributes['enctype'] = 'multipart/form-data';
$options['type'] = ($isCreate) ? 'post' : 'put';
case 'post':
case 'put':
case 'delete':
case 'patch':
$append .= $this->hidden('_method', array(
'name' => '_method',
'value' => strtoupper($options['type']),
'secure' => static::SECURE_SKIP
));
default:
$htmlAttributes['method'] = 'post';
}
$this->requestType = strtolower($options['type']);
if (!$options['default']) {
if (!isset($options['onsubmit'])) {
$options['onsubmit'] = '';
}
$htmlAttributes['onsubmit'] = $options['onsubmit'] . 'event.returnValue = false; return false;';
}
if (!empty($options['encoding'])) {
$htmlAttributes['accept-charset'] = $options['encoding'];
}
unset($options['type'], $options['encoding'], $options['default']);
$htmlAttributes = array_merge($options, $htmlAttributes);
$this->fields = array();
if ($this->requestType !== 'get') {
$append .= $this->_csrfField();
}
if (!empty($append)) {
$append = $this->formatTemplate('hiddenblock', ['content' => $append]);
}
$actionAttr = $this->_templater->formatAttributes(['action' => $action, 'escape' => false]);
return $this->formatTemplate('formstart', [
'attrs' => $this->_templater->formatAttributes($htmlAttributes) . $actionAttr
]) . $append;
}
/**
* Create the URL for a form based on the options.
*
* @param \Cake\View\Form\ContextInterface $context The context object to use.
* @param array $options An array of options from create()
* @return string The action attribute for the form.
*/
protected function _formUrl($context, $options) {
if ($options['action'] === null && $options['url'] === null) {
return $this->request->here(false);
}
if (empty($options['url']) || is_array($options['url'])) {
if (isset($options['action']) && empty($options['url']['action'])) {
$options['url']['action'] = $options['action'];
}
$plugin = $this->plugin ? Inflector::underscore($this->plugin) : null;
$actionDefaults = [
'plugin' => $plugin,
'controller' => Inflector::underscore($this->request->params['controller']),
'action' => $this->request->params['action'],
];
$action = (array)$options['url'] + $actionDefaults;
$pk = $context->primaryKey();
if (count($pk)) {
$id = $context->val($pk[0]);
}
if (empty($action[0]) && isset($id)) {
$action[0] = $id;
}
return $action;
}
if (is_string($options['url'])) {
return $options['url'];
}
}
/**
* Return a CSRF input if the request data is present.
* Used to secure forms in conjunction with CsrfComponent &
* SecurityComponent
*
* @return string
*/
protected function _csrfField() {
if (!empty($this->request['_Token']['unlockedFields'])) {
foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) {
$this->_unlockedFields[] = $unlocked;
}
}
if (empty($this->request->params['_csrfToken'])) {
return '';
}
return $this->hidden('_csrfToken', array(
'value' => $this->request->params['_csrfToken'],
'secure' => static::SECURE_SKIP
));
}
/**
* Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
* input fields where appropriate.
*
* @param array $secureAttributes will be passed as html attributes into the hidden input elements generated for the
* Security Component.
* @return string A closing FORM tag.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-form
*/
public function end($secureAttributes = []) {
$out = '';
if (
$this->requestType !== 'get' &&
!empty($this->request['_Token'])
) {
$out .= $this->secure($this->fields, $secureAttributes);
$this->fields = array();
}
$out .= $this->formatTemplate('formend', []);
$this->requestType = null;
$this->_context = null;
return $out;
}
/**
* Generates a hidden field with a security hash based on the fields used in
* the form.
*
* If $secureAttributes is set, these html attributes will be merged into
* the hidden input tags generated for the Security Component. This is
* especially useful to set HTML5 attributes like 'form'.
*
* @param array|null $fields If set specifies the list of fields to use when
* generating the hash, else $this->fields is being used.
* @param array $secureAttributes will be passed as html attributes into the hidden
* input elements generated for the Security Component.
* @return string A hidden input field with a security hash
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::secure
*/
public function secure($fields = array(), $secureAttributes = array()) {
if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
return;
}
$locked = array();
$unlockedFields = $this->_unlockedFields;
foreach ($fields as $key => $value) {
if (!is_int($key)) {
$locked[$key] = $value;
unset($fields[$key]);
}
}
sort($unlockedFields, SORT_STRING);
sort($fields, SORT_STRING);
ksort($locked, SORT_STRING);
$fields += $locked;
$locked = implode(array_keys($locked), '|');
$unlocked = implode($unlockedFields, '|');
$fields = Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt'), 'sha1');
$tokenFields = array_merge($secureAttributes, array(
'value' => urlencode($fields . ':' . $locked),
));
$out = $this->hidden('_Token.fields', $tokenFields);
$tokenUnlocked = array_merge($secureAttributes, array(
'value' => urlencode($unlocked),
));
$out .= $this->hidden('_Token.unlocked', $tokenUnlocked);
return $this->formatTemplate('hiddenblock', ['content' => $out]);
}
/**
* Add to or get the list of fields that are currently unlocked.
* Unlocked fields are not included in the field hash used by SecurityComponent
* unlocking a field once its been added to the list of secured fields will remove
* it from the list of fields.
*
* @param string $name The dot separated name for the field.
* @return mixed Either null, or the list of fields.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::unlockField
*/
public function unlockField($name = null) {
if ($name === null) {
return $this->_unlockedFields;
}
if (!in_array($name, $this->_unlockedFields)) {
$this->_unlockedFields[] = $name;
}
$index = array_search($name, $this->fields);
if ($index !== false) {
unset($this->fields[$index]);
}
unset($this->fields[$name]);
}
/**
* Determine which fields of a form should be used for hash.
* Populates $this->fields
*
* @param boolean $lock Whether this field should be part of the validation
* or excluded as part of the unlockedFields.
* @param string|array $field Reference to field to be secured. Can be dot
* separated string to indicate nesting or array of fieldname parts.
* @param mixed $value Field value, if value should not be tampered with.
* @return mixed|null Not used yet
*/
protected function _secure($lock, $field, $value = null) {
if (is_string($field)) {
$field = Hash::filter(explode('.', $field));
}
foreach ($this->_unlockedFields as $unlockField) {
$unlockParts = explode('.', $unlockField);
if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
return;
}
}
$field = implode('.', $field);
$field = preg_replace('/(\.\d+)+$/', '', $field);
if ($lock) {
if (!in_array($field, $this->fields)) {
if ($value !== null) {
return $this->fields[$field] = $value;
}
$this->fields[] = $field;
}
} else {
$this->unlockField($field);
}
}
/**
* Returns true if there is an error for the given field, otherwise false
*
* @param string $field This should be "Modelname.fieldname"
* @return boolean If there are errors this method returns true, else false.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
*/
public function isFieldError($field) {
return $this->_getContext()->hasError($field);
}
/**
* Returns a formatted error message for given form field, '' if no errors.
*
* Uses the `error`, `errorList` and `errorItem` templates. The `errorList` and
* `errorItem` templates are used to format multiple error messages per field.
*
* ### Options:
*
* - `escape` boolean - Whether or not to html escape the contents of the error.
*
* @param string $field A field name, like "Modelname.fieldname"
* @param string|array $text Error message as string or array of messages. If an array,
* it should be a hash of key names => messages.
* @param array $options See above.
* @return string Formatted errors or ''.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
*/
public function error($field, $text = null, $options = []) {
$options += ['escape' => true];
$context = $this->_getContext();
if (!$context->hasError($field)) {
return '';
}
$error = (array)$context->error($field);
if (is_array($text)) {
$tmp = [];
foreach ($error as $e) {
if (isset($text[$e])) {
$tmp[] = $text[$e];
} else {
$tmp[] = $e;
}
}
$text = $tmp;
}
if ($text !== null) {
$error = $text;
}
if ($options['escape']) {
$error = h($error);
unset($options['escape']);
}
if (is_array($error)) {
if (count($error) > 1) {
$errorText = [];
foreach ($error as $err) {
$errorText[] = $this->formatTemplate('errorItem', ['text' => $err]);
}
$error = $this->formatTemplate('errorList', [
'content' => implode('', $errorText)
]);
} else {
$error = array_pop($error);
}
}
return $this->formatTemplate('error', ['content' => $error]);
}
/**
* Returns a formatted LABEL element for HTML forms.
*
* Will automatically generate a `for` attribute if one is not provided.
*
* ### Options
*
* - `for` - Set the for attribute, if its not defined the for attribute
* will be generated from the $fieldName parameter using
* FormHelper::_domId().
*
* Examples:
*
* The text and for attribute are generated off of the fieldname
*
* {{{
* echo $this->Form->label('Post.published');
* <label for="PostPublished">Published</label>
* }}}
*
* Custom text:
*
* {{{
* echo $this->Form->label('Post.published', 'Publish');
* <label for="PostPublished">Publish</label>
* }}}
*
* Custom class name:
*
* {{{
* echo $this->Form->label('Post.published', 'Publish', 'required');
* <label for="PostPublished" class="required">Publish</label>
* }}}
*
* Custom attributes:
*
* {{{
* echo $this->Form->label('Post.published', 'Publish', array(
* 'for' => 'post-publish'
* ));
* <label for="post-publish">Publish</label>
* }}}
*
* @param string $fieldName This should be "Modelname.fieldname"
* @param string $text Text that will appear in the label field. If
* $text is left undefined the text will be inflected from the
* fieldName.
* @param array|string $options An array of HTML attributes, or a string, to be used as a class name.
* @return string The formatted LABEL element
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label
*/
public function label($fieldName, $text = null, $options = array()) {
if ($text === null) {
if (strpos($fieldName, '.') !== false) {
$fieldElements = explode('.', $fieldName);
$text = array_pop($fieldElements);
} else {
$text = $fieldName;
}
if (substr($text, -3) === '_id') {
$text = substr($text, 0, -3);
}
$text = __(Inflector::humanize(Inflector::underscore($text)));
}
if (is_string($options)) {
$options = array('class' => $options);
}
if (isset($options['for'])) {
$labelFor = $options['for'];
unset($options['for']);
} else {
$labelFor = $this->_domId($fieldName);
}
$attrs = $options + [
'for' => $labelFor,
'text' => $text,
];
return $this->widget('label', $attrs);
}
/**
* Generate an ID suitable for use in an ID attribute.
*
* @param string $value The value to convert into an ID.
* @return string The generated id.
*/
protected function _domId($value) {
return mb_strtolower(Inflector::slug($value, '-'));
}
/**
* Generate a set of inputs for `$fields`. If $fields is null the fields of current model
* will be used.
*
* You can customize individual inputs through `$fields`.
* {{{
* $this->Form->inputs(array(
* 'name' => array('label' => 'custom label')
* ));
* }}}
*
* In addition to controller fields output, `$fields` can be used to control legend
* and fieldset rendering.
* `$this->Form->inputs('My legend');` Would generate an input set with a custom legend.
* Passing `fieldset` and `legend` key in `$fields` array has been deprecated since 2.3,
* for more fine grained control use the `fieldset` and `legend` keys in `$options` param.
*
* @param array $fields An array of fields to generate inputs for, or null.
* @param array $blacklist A simple array of fields to not create inputs for.
* @param array $options Options array. Valid keys are:
* - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
* the class name for the fieldset element.
* - `legend` Set to false to disable the legend for the generated input set. Or supply a string
* to customize the legend text.
* @return string Completed form inputs.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
*/
public function inputs($fields = null, $blacklist = null, $options = array()) {
$fieldset = $legend = true;
$modelFields = array();
$model = $this->model();
if ($model) {
$modelFields = array_keys((array)$this->_introspectModel($model, 'fields'));
}
if (is_array($fields)) {
if (array_key_exists('legend', $fields) && !in_array('legend', $modelFields)) {
$legend = $fields['legend'];
unset($fields['legend']);
}
if (isset($fields['fieldset']) && !in_array('fieldset', $modelFields)) {
$fieldset = $fields['fieldset'];
unset($fields['fieldset']);
}
} elseif ($fields !== null) {
$fieldset = $legend = $fields;
if (!is_bool($fieldset)) {
$fieldset = true;
}
$fields = array();
}
if (isset($options['legend'])) {
$legend = $options['legend'];
}
if (isset($options['fieldset'])) {
$fieldset = $options['fieldset'];
}
if (empty($fields)) {
$fields = $modelFields;
}
if ($legend === true) {
$actionName = __d('cake', 'New %s');
$isEdit = (
strpos($this->request->params['action'], 'update') !== false ||
strpos($this->request->params['action'], 'edit') !== false
);
if ($isEdit) {
$actionName = __d('cake', 'Edit %s');
}
$modelName = Inflector::humanize(Inflector::underscore($model));
$legend = sprintf($actionName, __($modelName));
}
$out = null;
foreach ($fields as $name => $options) {
if (is_numeric($name) && !is_array($options)) {
$name = $options;
$options = array();
}
$entity = explode('.', $name);
$blacklisted = (
is_array($blacklist) &&
(in_array($name, $blacklist) || in_array(end($entity), $blacklist))
);
if ($blacklisted) {
continue;
}
$out .= $this->input($name, $options);
}
if (is_string($fieldset)) {
$fieldsetClass = sprintf(' class="%s"', $fieldset);
} else {
$fieldsetClass = '';
}
if ($fieldset) {
if ($legend) {
$out = $this->Html->useTag('legend', $legend) . $out;
}
$out = $this->Html->useTag('fieldset', $fieldsetClass, $out);
}
return $out;
}
/**
* Generates a form input element complete with label and wrapper div
*
* ### Options
*
* See each field type method for more information. Any options that are part of
* $attributes or $options for the different **type** methods can be included in `$options` for input().i
* Additionally, any unknown keys that are not in the list below, or part of the selected type's options
* will be treated as a regular html attribute for the generated input.
*
* - `type` - Force the type of widget you want. e.g. `type => 'select'`
* - `label` - Either a string label, or an array of options for the label. See FormHelper::label().
* - `div` - Either `false` to disable the div, or an array of options for the div.
* See HtmlHelper::div() for more options.
* - `options` - For widgets that take options e.g. radio, select.
* - `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field
* error and error messages).
* - `errorMessage` - Boolean to control rendering error messages (field error will still occur).
* - `empty` - String or boolean to enable empty select box options.
* - `before` - Content to place before the label + input.
* - `after` - Content to place after the label + input.
* - `between` - Content to place between the label + input.
* - `format` - Format template for element order. Any element that is not in the array, will not be in the output.
* - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
* - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
* - Hidden input will not be formatted
* - Radio buttons cannot have the order of input and label elements controlled with these settings.
*
* @param string $fieldName This should be "Modelname.fieldname"
* @param array $options Each type of input takes different options.
* @return string Completed form widget.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
*/
public function input($fieldName, $options = array()) {
$this->setEntity($fieldName);
$options = $this->_parseOptions($options);
$divOptions = $this->_divOptions($options);
unset($options['div']);
if ($options['type'] === 'radio' && isset($options['options'])) {
$radioOptions = (array)$options['options'];
unset($options['options']);
}
$label = $this->_getLabel($fieldName, $options);
if ($options['type'] !== 'radio') {
unset($options['label']);
}
$error = $this->_extractOption('error', $options, null);
unset($options['error']);
$errorMessage = $this->_extractOption('errorMessage', $options, true);
unset($options['errorMessage']);
$selected = $this->_extractOption('selected', $options, null);
unset($options['selected']);
if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
$dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
$timeFormat = $this->_extractOption('timeFormat', $options, 12);
unset($options['dateFormat'], $options['timeFormat']);
}
$type = $options['type'];
$out = array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after']);
$format = $this->_getFormat($options);
unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
$out['error'] = null;
if ($type !== 'hidden' && $error !== false) {
$errMsg = $this->error($fieldName, $error);
if ($errMsg) {
$divOptions = $this->addClass($divOptions, 'error');
if ($errorMessage) {
$out['error'] = $errMsg;
}
}
}
if ($type === 'radio' && isset($out['between'])) {
$options['between'] = $out['between'];
$out['between'] = null;
}
$out['input'] = $this->_getInput(compact('type', 'fieldName', 'options', 'radioOptions', 'selected', 'dateFormat', 'timeFormat'));
$output = '';
foreach ($format as $element) {
$output .= $out[$element];
}
if (!empty($divOptions['tag'])) {
$tag = $divOptions['tag'];
unset($divOptions['tag']);
$output = $this->Html->tag($tag, $output, $divOptions);
}
return $output;
}
/**
* Generates an input element
*
* @param array $args The options for the input element
* @return string The generated input element
*/
protected function _getInput($args) {
extract($args);
switch ($type) {
case 'hidden':
return $this->hidden($fieldName, $options);
case 'checkbox':
return $this->checkbox($fieldName, $options);
case 'radio':
return $this->radio($fieldName, $radioOptions, $options);
case 'file':
return $this->file($fieldName, $options);
case 'select':
$options += array('options' => array(), 'value' => $selected);
$list = $options['options'];
unset($options['options']);
return $this->select($fieldName, $list, $options);
case 'time':
$options['value'] = $selected;
return $this->dateTime($fieldName, null, $timeFormat, $options);
case 'date':
$options['value'] = $selected;
return $this->dateTime($fieldName, $dateFormat, null, $options);
case 'datetime':
$options['value'] = $selected;
return $this->dateTime($fieldName, $dateFormat, $timeFormat, $options);
case 'textarea':
return $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
case 'url':
return $this->text($fieldName, array('type' => 'url') + $options);
default:
return $this->{$type}($fieldName, $options);
}
}
/**
* Generates input options array
*
* @param array $options
* @return array Options
*/
protected function _parseOptions($options) {
$options = array_merge(
array('before' => null, 'between' => null, 'after' => null, 'format' => null),
$this->_inputDefaults,
$options
);
if (!isset($options['type'])) {
$options = $this->_magicOptions($options);
}
if (in_array($options['type'], array('radio', 'select'))) {
$options = $this->_optionsOptions($options);
}
if (isset($options['rows']) || isset($options['cols'])) {
$options['type'] = 'textarea';
}
if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
$options += array('empty' => false);
}
return $options;
}
/**
* Generates list of options for multiple select
*
* @param array $options
* @return array
*/
protected function _optionsOptions($options) {
if (isset($options['options'])) {
return $options;