-
-
Notifications
You must be signed in to change notification settings - Fork 205
/
Copy pathFormField.php
732 lines (624 loc) · 20.1 KB
/
FormField.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
<?php
namespace Backend\Classes;
use BackedEnum;
use Illuminate\Support\Facades\Lang;
use Winter\Storm\Database\Model;
use Winter\Storm\Html\Helper as HtmlHelper;
use Winter\Storm\Support\Facades\Html;
use Winter\Storm\Support\Str;
/**
* Form Field definition
* A translation of the form field configuration
*
* @package winter\wn-backend-module
* @author Alexey Bobkov, Samuel Georges
*/
class FormField
{
/**
* @var int Value returned when the form field should not contribute any save data.
*/
const NO_SAVE_DATA = -1;
/**
* @var string A special character in yaml config files to indicate a field higher in hierarchy
*/
const HIERARCHY_UP = '^';
/**
* @var string Form field name.
*/
public $fieldName;
/**
* @var string If the field element names should be contained in an array. Eg:
*
* <input name="nameArray[fieldName]" />
*/
public $arrayName;
/**
* @var string A prefix to the field identifier so it can be totally unique.
*/
public $idPrefix;
/**
* @var string Form field label.
*/
public $label;
/**
* @var string Form field value.
*/
public $value;
/**
* @var string Model attribute to use for the display value.
*/
public $valueFrom;
/**
* @var string Specifies a default value for supported fields.
*/
public $defaults;
/**
* @var string Model attribute to use for the default value.
*/
public $defaultFrom;
/**
* @var string Specifies if this field belongs to a tab.
*/
public $tab;
/**
* @var string Display mode. Text, textarea
*/
public $type = 'text';
/**
* @var string Field options.
*/
public $options;
/**
* @var string Specifies a side. Possible values: auto, left, right, full.
*/
public $span = 'full';
/**
* @var string Specifies a size. Possible values: tiny, small, large, huge, giant.
*/
public $size = 'large';
/**
* @var string Specifies contextual visibility of this form field.
*/
public $context;
/**
* @var bool Specifies if this field is mandatory.
*/
public $required;
/**
* @var bool Specify if the field is read-only or not.
*/
public $readOnly = false;
/**
* @var bool Specify if the field is disabled or not.
*/
public $disabled = false;
/**
* @var bool Specify if the field is hidden. Hiddens fields are not included in postbacks.
*/
public $hidden = false;
/**
* @var bool Specifies if this field stretch to fit the page height.
*/
public $stretch = false;
/**
* @var string Specifies a comment to accompany the field
*/
public $comment = '';
/**
* @var string Specifies the comment position.
*/
public $commentPosition = 'below';
/**
* @var string Specifies if the comment is in HTML format.
*/
public $commentHtml = false;
/**
* @var string Specifies a message to display when there is no value supplied (placeholder).
*/
public $placeholder = '';
/**
* @var array Contains a list of attributes specified in the field configuration.
*/
public $attributes;
/**
* @var string Specifies a CSS class to attach to the field container.
*/
public $cssClass;
/**
* @var string Specifies a path for partial-type fields.
*/
public $path;
/**
* @var array Raw field configuration.
*/
public $config;
/**
* @var array Other field names this field depends on, when the other fields are modified, this field will update.
*/
public $dependsOn;
/**
* @var array Other field names this field can be triggered by, see the Trigger API documentation.
*/
public $trigger;
/**
* @var array Other field names text is converted in to a URL, slug or file name value in this field.
*/
public $preset;
/**
* Constructor.
* @param string $fieldName The name of the field
* @param string $label The label of the field
*/
public function __construct($fieldName, $label)
{
$this->fieldName = $fieldName;
$this->label = $label;
}
/**
* If this field belongs to a tab.
*/
public function tab($value)
{
$this->tab = $value;
return $this;
}
/**
* Sets a side of the field on a form.
* @param string $value Specifies a side. Possible values: left, right, full
*/
public function span($value = 'full')
{
$this->span = $value;
return $this;
}
/**
* Sets a side of the field on a form.
* @param string $value Specifies a size. Possible values: tiny, small, large, huge, giant
*/
public function size($value = 'large')
{
$this->size = $value;
return $this;
}
/**
* Sets field options, for dropdowns, radio lists and checkbox lists.
* @param array $value
* @return self
*/
public function options($value = null)
{
if ($value === null) {
if (is_array($this->options)) {
return $this->options;
} elseif (is_callable($this->options)) {
$callable = $this->options;
return $callable();
} elseif (is_string($this->options) && is_array($options = Lang::get($this->options))) {
return $options;
}
return [];
}
$this->options = $value;
return $this;
}
/**
* Specifies a field control rendering mode. Supported modes are:
* - text - creates a text field. Default for varchar column types.
* - textarea - creates a textarea control. Default for text column types.
* - dropdown - creates a drop-down list. Default for reference-based columns.
* - radio - creates a set of radio buttons.
* - checkbox - creates a single checkbox.
* - checkboxlist - creates a checkbox list.
* - switch - creates a switch field.
* @param string $type Specifies a render mode as described above
* @param array $config A list of render mode specific config.
*/
public function displayAs($type, $config = [])
{
$this->type = strtolower($type) ?: $this->type;
$this->config = $this->evalConfig($config);
return $this;
}
/**
* Process options and apply them to this object.
* @param array $config
* @return array
*/
protected function evalConfig($config)
{
if ($config === null) {
$config = [];
}
/*
* Standard config:property values
*/
$applyConfigValues = [
'commentHtml',
'placeholder',
'dependsOn',
'required',
'readOnly',
'disabled',
'cssClass',
'stretch',
'context',
'hidden',
'trigger',
'preset',
'path',
];
foreach ($applyConfigValues as $value) {
if (array_key_exists($value, $config)) {
$this->{$value} = $config[$value];
}
}
/*
* Custom applicators
*/
if (isset($config['options'])) {
$this->options($config['options']);
}
if (isset($config['span'])) {
$this->span($config['span']);
}
if (isset($config['size'])) {
$this->size($config['size']);
}
if (isset($config['tab'])) {
$this->tab($config['tab']);
}
if (isset($config['commentAbove'])) {
$this->comment($config['commentAbove'], 'above');
}
if (isset($config['comment'])) {
$this->comment($config['comment']);
}
if (isset($config['default'])) {
$this->defaults = $config['default'];
}
if (isset($config['defaultFrom'])) {
$this->defaultFrom = $config['defaultFrom'];
}
if (isset($config['attributes'])) {
$this->attributes($config['attributes']);
}
if (isset($config['containerAttributes'])) {
$this->attributes($config['containerAttributes'], 'container');
}
if (isset($config['valueFrom'])) {
$this->valueFrom = $config['valueFrom'];
}
else {
$this->valueFrom = $this->fieldName;
}
return $config;
}
/**
* Adds a text comment above or below the field.
* @param string $text Specifies a comment text.
* @param string $position Specifies a comment position.
* @param bool $isHtml Set to true if you use HTML formatting in the comment
* Supported values are 'below' and 'above'
*/
public function comment($text, $position = 'below', $isHtml = null)
{
$this->comment = $text;
$this->commentPosition = $position;
if ($isHtml !== null) {
$this->commentHtml = $isHtml;
}
return $this;
}
/**
* Determine if the provided value matches this field's value.
* @param string $value
* @return bool
*/
public function isSelected($value = true)
{
if ($this->value === null) {
return false;
}
$value = ($value instanceof BackedEnum) ? $value->value : $value;
$currentValue = ($this->value instanceof BackedEnum) ? $this->value->value : $this->value;
return (string) $value === (string) $currentValue;
}
/**
* Sets the attributes for this field in a given position.
* - field: Attributes are added to the form field element (input, select, textarea, etc)
* - container: Attributes are added to the form field container (div.form-group)
* @param array $items
* @param string $position
* @return void
*/
public function attributes($items, $position = 'field')
{
if (!is_array($items)) {
return;
}
$multiArray = array_filter($items, 'is_array');
if (!$multiArray) {
$this->attributes[$position] = $items;
return;
}
foreach ($items as $_position => $_items) {
$this->attributes($_items, $_position);
}
return $this;
}
/**
* Checks if the field has the supplied [unfiltered] attribute.
* @param string $name
* @param string $position
* @return bool
*/
public function hasAttribute($name, $position = 'field')
{
if (!isset($this->attributes[$position])) {
return false;
}
return array_key_exists($name, $this->attributes[$position]);
}
/**
* Returns the attributes for this field at a given position.
* @param string $position
* @return array
*/
public function getAttributes($position = 'field', $htmlBuild = true)
{
$result = array_get($this->attributes, $position, []);
$result = $this->filterAttributes($result, $position);
// Field is required, so add the "required" attribute
if ($position === 'field' && $this->required && (!isset($result['required']) || $result['required'])) {
$result['required'] = '';
} elseif ($position === 'field' && isset($result['required']) && !$result['required']) {
// The "required" attribute is set and falsy, so unset it
unset($result['required']);
}
return $htmlBuild ? Html::attributes($result) : $result;
}
/**
* Adds any circumstantial attributes to the field based on other
* settings, such as the 'disabled' option.
* @param array $attributes
* @param string $position
* @return array
*/
protected function filterAttributes($attributes, $position = 'field')
{
$position = strtolower($position);
$attributes = $this->filterTriggerAttributes($attributes, $position);
$attributes = $this->filterPresetAttributes($attributes, $position);
if ($position == 'field' && $this->disabled) {
$attributes = $attributes + ['disabled' => 'disabled'];
}
if ($position == 'field' && $this->readOnly) {
$attributes = $attributes + ['readonly' => 'readonly'];
if ($this->type == 'checkbox' || $this->type == 'switch') {
$attributes = $attributes + ['onclick' => 'return false;'];
}
}
return $attributes;
}
/**
* Adds attributes used specifically by the Trigger API
* @param array $attributes
* @param string $position
* @return array
*/
protected function filterTriggerAttributes($attributes, $position = 'field')
{
if (!$this->trigger || !is_array($this->trigger)) {
return $attributes;
}
$triggerAction = array_get($this->trigger, 'action');
$triggerField = array_get($this->trigger, 'field');
$triggerCondition = array_get($this->trigger, 'condition');
$triggerForm = $this->arrayName;
$triggerMulti = '';
// Apply these to container
if (in_array($triggerAction, ['hide', 'show']) && $position != 'container') {
return $attributes;
}
// Apply these to field/input
if (in_array($triggerAction, ['enable', 'disable', 'empty']) && $position != 'field') {
return $attributes;
}
// Reduce the field reference for the trigger condition field
$triggerFieldParentLevel = Str::getPrecedingSymbols($triggerField, self::HIERARCHY_UP);
if ($triggerFieldParentLevel > 0) {
// Remove the preceding symbols from the trigger field name
$triggerField = substr($triggerField, $triggerFieldParentLevel);
$triggerForm = HtmlHelper::reduceNameHierarchy($triggerForm, $triggerFieldParentLevel);
}
// Preserve multi field types
if (Str::endsWith($triggerField, '[]')) {
$triggerField = substr($triggerField, 0, -2);
$triggerMulti = '[]';
}
// Final compilation
if ($this->arrayName) {
$fullTriggerField = $triggerForm.'['.implode('][', HtmlHelper::nameToArray($triggerField)).']'.$triggerMulti;
}
else {
$fullTriggerField = $triggerField.$triggerMulti;
}
$newAttributes = [
'data-trigger' => '[name="'.$fullTriggerField.'"]',
'data-trigger-action' => $triggerAction,
'data-trigger-condition' => $triggerCondition,
'data-trigger-closest-parent' => 'form, div[data-control="formwidget"]'
];
return $attributes + $newAttributes;
}
/**
* Adds attributes used specifically by the Input Preset API
* @param array $attributes
* @param string $position
* @return array
*/
protected function filterPresetAttributes($attributes, $position = 'field')
{
if (!$this->preset || $position != 'field') {
return $attributes;
}
if (!is_array($this->preset)) {
$this->preset = ['field' => $this->preset, 'type' => 'slug'];
}
$presetField = array_get($this->preset, 'field');
$presetType = array_get($this->preset, 'type');
if ($this->arrayName) {
$fullPresetField = $this->arrayName.'['.implode('][', HtmlHelper::nameToArray($presetField)).']';
}
else {
$fullPresetField = $presetField;
}
$newAttributes = [
'data-input-preset' => '[name="'.$fullPresetField.'"]',
'data-input-preset-type' => $presetType,
'data-input-preset-closest-parent' => 'form'
];
if ($prefixInput = array_get($this->preset, 'prefixInput')) {
$newAttributes['data-input-preset-prefix-input'] = $prefixInput;
}
return $attributes + $newAttributes;
}
/**
* Returns a value suitable for the field name property.
* @param string $arrayName Specify a custom array name
* @return string
*/
public function getName($arrayName = null)
{
if ($arrayName === null) {
$arrayName = $this->arrayName;
}
if ($arrayName) {
return $arrayName.'['.implode('][', HtmlHelper::nameToArray($this->fieldName)).']';
}
return $this->fieldName;
}
/**
* Returns a value suitable for the field id property.
* @param string $suffix Specify a suffix string
* @return string
*/
public function getId($suffix = null)
{
$id = 'field';
if ($this->arrayName) {
$id .= '-'.$this->arrayName;
}
$id .= '-'.$this->fieldName;
if ($suffix) {
$id .= '-'.$suffix;
}
if ($this->idPrefix) {
$id = $this->idPrefix . '-' . $id;
}
return HtmlHelper::nameToId($id);
}
/**
* Returns a raw config item value.
* @param string $value
* @param string $default
* @return mixed
*/
public function getConfig($value, $default = null)
{
return array_get($this->config, $value, $default);
}
/**
* Returns this fields value from a supplied data set, which can be
* an array or a model or another generic collection.
* @param mixed $data
* @param mixed $default
* @return mixed
*/
public function getValueFromData($data, $default = null)
{
$fieldName = $this->valueFrom ?: $this->fieldName;
return $this->getFieldNameFromData($fieldName, $data, $default);
}
/**
* Returns the default value for this field, the supplied data is used
* to source data when defaultFrom is specified.
* @param mixed $data
* @return mixed
*/
public function getDefaultFromData($data)
{
if ($this->defaultFrom) {
return $this->getFieldNameFromData($this->defaultFrom, $data);
}
if ($this->defaults !== '') {
return $this->defaults;
}
return null;
}
/**
* Returns the final model and attribute name of a nested attribute. Eg:
*
* list($model, $attribute) = $this->resolveAttribute('person[phone]');
*
* @param string $attribute.
* @return array
*/
public function resolveModelAttribute($model, $attribute = null)
{
if ($attribute === null) {
$attribute = $this->valueFrom ?: $this->fieldName;
}
$parts = is_array($attribute) ? $attribute : HtmlHelper::nameToArray($attribute);
$last = array_pop($parts);
foreach ($parts as $part) {
$model = $model->{$part};
}
return [$model, $last];
}
/**
* Internal method to extract the value of a field name from a data set.
* @param string $fieldName
* @param mixed $data
* @param mixed $default
* @return mixed
*/
protected function getFieldNameFromData($fieldName, $data, $default = null)
{
/*
* Array field name, eg: field[key][key2][key3]
*/
$keyParts = HtmlHelper::nameToArray($fieldName);
$lastField = end($keyParts);
$result = $data;
/*
* Loop the field key parts and build a value.
* To support relations only the last field should return the
* relation value, all others will look up the relation object as normal.
*/
foreach ($keyParts as $key) {
if ($result instanceof Model && $result->hasRelation($key)) {
if ($key == $lastField) {
$result = $result->getRelationValue($key) ?: $default;
} else {
$result = $result->{$key};
}
} elseif (is_array($result)) {
if (!array_key_exists($key, $result)) {
return $default;
}
$result = $result[$key];
} else {
if (!isset($result->{$key})) {
return $default;
}
$result = $result->{$key};
}
}
if ($result instanceof BackedEnum) {
$result = $result->value;
}
return $result;
}
}