-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPWModuleConfigHelper.php
81 lines (63 loc) · 2.48 KB
/
PWModuleConfigHelper.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
<?php
/**
* Module Config Helper for ProcessWire
*
* @author Christian Raunitschka (owzim)
* @copyright Christian Raunitschka
* @version 0.0.1
* <https://github.com/owzim/PWModuleConfigHelper>
*
* See README.md for usage
*
*/
class PWModuleConfigHelper {
const DEFAULT_FIELDTYPE = 'InputfieldText';
const DEFAULT_OPTIONS_FIELDTYPE = 'InputfieldRadios';
public static function apply($module, $config) {
foreach ($config as $key => $value) {
$module->set($key, $value['value']); // set default value in construct
}
}
public static function renderForm($data, $config) {
$modules = wire('modules');
$data = (object) $data; // cast to object, because it's prettier to acces keys
$config = (object) $config; // cast to object, because it's prettier to acces keys
foreach ($config as $key => $valueData) {
$valueData = (object) $valueData; // cast to object, because it's prettier to acces keys
if(!isset($data->$key)) {
$data->$key = $valueData->value;
}
}
$form = new InputfieldWrapper();
foreach ($config as $key => $valueData) {
$valueData = (object) $valueData; // cast to object, because it's prettier to acces keys
$value = $valueData->value;
$label = isset($valueData->label) ? $valueData->label : $key;
if (isset($valueData->options)) {
$inputfieldType = isset($valueData->inputFieldtype) ? $valueData->inputFieldtype : self::DEFAULT_OPTIONS_FIELDTYPE;
} else {
$inputfieldType = isset($valueData->inputFieldtype) ? $valueData->inputFieldtype : self::DEFAULT_FIELDTYPE;
}
$f = $modules->get($inputfieldType);
$f->name = $key;
$f->label = $label;
if (isset($valueData->options)) {
foreach ($valueData->options as $optionLabel => $optionValue) {
$f->addOption($optionValue, $optionLabel);
}
}
if (isset($valueData->attributes)) {
foreach ($valueData->attributes as $attributeKey => $attributeValue) {
$f->set($attributeKey, $attributeValue);
}
}
if(isset($data->$key)) {
$f->value = $data->$key;
} else {
$f->value = $value;
}
$form->add($f);
}
return $form;
}
}