-
Notifications
You must be signed in to change notification settings - Fork 0
/
FieldtypeDynamicOptions.module
336 lines (312 loc) · 10.4 KB
/
FieldtypeDynamicOptions.module
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
<?php namespace ProcessWire;
class FieldtypeDynamicOptions extends FieldtypeMulti implements Module {
/**
* Module information
*
* @return array
*/
public static function getModuleInfo() {
return array(
'title' => 'Dynamic Options',
'summary' => 'Fieldtype for dynamic options that are generated at runtime.',
'version' => '0.1.8',
'author' => 'Robin Sallis',
'href' => 'https://github.com/Toutouwai/FieldtypeDynamicOptions',
'icon' => 'list',
'requires' => 'ProcessWire>=3.0.0, PHP>=5.4.0',
);
}
/**
* Return class name of the Inputfield type for a Dynamic Options field
*
* @param Field $field Dynamic Options field
* @return string
*/
protected function getInputfieldClass(Field $field) {
return $field->inputfield_class ?: 'InputfieldSelect';
}
/**
* Get instances of InputfieldSelect
*
* @return array
*/
protected function getInputfieldSelects() {
$selects = [];
$inputfield_modules = $this->wire()->modules->find('name^=Inputfield');
foreach($inputfield_modules as $module) {
if($module instanceof ModulePlaceholder) $module = $inputfield_modules->getModule($module->className(), ['noInit' => true]);
if($module instanceof InputfieldSelect) {
$label = str_replace('Inputfield', '', $module->className());
$selects[$module->className()] = [
'label' => $label,
'single' => $module instanceof InputfieldSelectMultiple ? false : true,
];
}
}
return $selects;
}
/**
* Does this field allow only a single item?
*
* @param Field $field Dynamic Options field
* @return boolean
*/
protected function isSingle(Field $field, Page $page) {
if($field->max_items === 1) {
return true;
} else {
$selects = $this->getInputfieldSelects();
$inputfield_class = $this->getInputfieldClass($field);
return $selects[$inputfield_class]['single'];
}
}
/**
* Get options for this field (intended to be hooked)
*
* @param Page $page
* @param Field $field
* @return array
*/
public function ___getSelectableOptions(Page $page, Field $field) {
return [];
}
/**
* Get the Inputfield that provides input for this Fieldtype
*
* @param Page $page
* @param Field $field
* @return Inputfield
*/
public function getInputfield(Page $page, Field $field) {
// Don't call hookable method when the process is ProcessField
// because it supplies the home page as a dummy page instead of the expected edited page
if($this->wire()->process instanceof ProcessField) {
$options = [];
} else {
$options = $this->getSelectableOptions($page, $field);
}
$inputfield = $this->wire()->modules->get($this->getInputfieldClass($field));
$inputfield->name = $field->name;
foreach($options as $value => $label) {
if(is_array($label)) {
// Must include 'label' key
if(!isset($label['label'])) continue;
// Get attributes if any
$attributes = [];
if(isset($label['attributes']) && is_array($label['attributes'])) $attributes = $label['attributes'];
$inputfield->addOption($value, $label['label'], $attributes);
} else {
$inputfield->addOption($value, $label);
}
}
// If there is a max items limit
if($this->wire()->process instanceof WirePageEditor && $field->max_items) {
// Add limit as a data attribute (may be used by inputfield, e.g. InputfieldSelectImages)
$inputfield->wrapAttr('data-max-items', $field->max_items);
// Show warning if number of items exceeds maximum, but not when form is submitted
if(!$this->wire()->input->is('post')) {
$value = $page->getUnformatted($field->name);
if($value) {
$count = count($value);
if($count > $field->max_items) {
$field_context = $field->getContext($page);
$inputfield->warning(sprintf($this->_('The number of items in field "%s" exceeds the limit of %d - please remove %d item(s).'), $field_context->label, $field->max_items, $count - $field->max_items));
}
}
}
}
return $inputfield;
}
/**
* Per Fieldtype interface, return a blank value of this Fieldtype
*
* @param Page $page
* @param Field $field
* @return array
*/
public function getBlankValue(Page $page, Field $field) {
return [];
}
/**
* Sanitize value for storage in a page
*
* @param Page $page
* @param Field $field
* @param mixed $value
* @return array
*/
public function sanitizeValue(Page $page, Field $field, $value) {
$value = (array) $value;
$allowed_options = $this->getSelectableOptions($page, $field);
foreach($value as $key => $item) {
if(!isset($allowed_options[$item])) unset($value[$key]);
}
return $value;
}
/**
* Given an 'awake' value, as set by wakeupValue(), convert the value back to a basic type for storage in database.
*
* @param Page $page
* @param Field $field
* @param array $value
* @return array
*/
public function ___sleepValue(Page $page, Field $field, $value) {
// Apply max items limit if any
if($field->max_items && count($value) > $field->max_items) {
$value = array_slice($value, 0, $field->max_items);
// Show warning notice in admin
$field_context = $field->getContext($page);
$this->wire()->warning(sprintf($this->_('Field "%s" was truncated to its limit of %d items.'), $field_context->label, $field->max_items));
}
return $value;
}
/**
* Format the given value for output
*
* @param Page $page Page that the value lives on
* @param Field $field Field that represents the value
* @param array $value The value to format
* @return string|array
*/
public function ___formatValue(Page $page, Field $field, $value) {
if($field->format_as_pagefiles) {
// Get PagefilesManager for home page
$pm = $this->wire()->pages->get(1)->filesManager;
foreach($value as $key => $item) {
$pagefile = $pm->getFile($item);
// Remove any invalid values that don't convert to a Pagefile
if(!$pagefile) {
unset($value[$key]);
continue;
}
$value[$key] = $pagefile;
}
}
// Apply max items limit if any
if($field->max_items && count($value) > $field->max_items) {
$value = array_slice($value, 0, $field->max_items);
}
// If field is "single" then the formatted value is a string
if($this->isSingle($field, $page)) $value = reset($value);
return $value;
}
/**
* Get Fieldtypes that are known compatible with this one
*
* @param Field $field
* @return Fieldtypes
*/
public function ___getCompatibleFieldtypes(Field $field) {
$fieldtypes = $this->wire(new Fieldtypes());
foreach($this->fieldtypes as $fieldtype) {
if($fieldtype instanceof FieldtypeDynamicOptions) $fieldtypes->add($fieldtype);
}
return $fieldtypes;
}
/**
* Return database schema
*
* @param Field $field
* @return array
*/
public function getDatabaseSchema(Field $field) {
$schema = parent::getDatabaseSchema($field);
$schema['data'] = 'TEXT NOT NULL';
$schema['keys']['data'] = 'FULLTEXT KEY data (data)';
return $schema;
}
/**
* Method called when the field is database-queried from a selector
*
* @param DatabaseQuerySelect $query
* @param string $table
* @param string $subfield
* @param string $operator
* @param mixed $value
* @return DatabaseQuery|DatabaseQuerySelect
*
*/
public function getMatchQuery($query, $table, $subfield, $operator, $value) {
if(empty($subfield) || $subfield === 'data') {
/** @var DatabaseQuerySelectFulltext $ft */
$ft = $this->wire(new DatabaseQuerySelectFulltext($query));
$ft->match($table, $subfield, $operator, $value);
return $query;
}
return parent::getMatchQuery($query, $table, $subfield, $operator, $value);
}
/**
* Get Inputfields needed to configure this Fieldtype
*
* @param Field $field
* @return InputfieldWrapper
*/
public function ___getConfigInputfields(Field $field) {
/* @var InputfieldWrapper $inputfields */
$inputfields = parent::___getConfigInputfields($field);
$modules = $this->wire()->modules;
/** @var InputfieldSelect $f */
$f = $modules->get('InputfieldSelect');
$f->name = 'inputfield_class';
$f->label = $this->_('Inputfield type');
$f->description = $this->_('The type of input field (Inputfield module) that will be used to select option(s) for this field.');
$f->icon = 'plug';
$singles = [];
$multiples = [];
foreach($this->getInputfieldSelects() as $class => $info) {
if($info['single']) {
$singles[$class] = $info['label'];
} else {
$multiples[$class] = $info['label'];
}
}
$f->addOption($this->_('Single item selection'), $singles);
$f->addOption($this->_('Multiple item selection'), $multiples);
$f->value = $this->getInputfieldClass($field);
$inputfields->add($f);
/** @var InputfieldInteger $f */
$f = $modules->get('InputfieldInteger');
$f_name = 'max_items';
$f->name = $f_name;
$f->label = $this->_('Maximum number of items');
$f->appendMarkup = " <span class='description'>" . $this->_('(a value of 0 means no limit)') . "</span>";
$f->inputType = 'number';
$f->defaultValue = 0;
if($field->$f_name) {
$f->value = $field->$f_name;
} else {
$f->collapsed = Inputfield::collapsedYes;
}
$inputfields->add($f);
/** @var InputfieldCheckbox $f */
$f = $modules->get('InputfieldCheckbox');
$f_name = 'format_as_pagefiles';
$f->name = $f_name;
$f->label = $this->_('Format as Pagefile/Pageimage object(s)');
$f->description = $this->_('If this field stores paths/URLs to Pagefiles/Pageimages then you can enable this option to have the formatted value be a Pagefile/Pageimage object for "single" fields or an array of Pagefile/Pageimage objects for "multiple" fields.');
$f->collapsed = Inputfield::collapsedBlank;
$f->checked = $field->$f_name === 1 ? 'checked' : '';
$inputfields->add($f);
/* @var InputfieldMarkup */
$f = $modules->get('InputfieldMarkup');
$f->label = $this->_('Selectable options');
$f->description = sprintf($this->_("Add the following hook to a %s file and modify according to your needs. The hook should return an array of options as 'value' => 'label'."), '**/site/ready.php**');
$f->value = "<pre><code>\$wire->addHookAfter('FieldtypeDynamicOptions::getSelectableOptions', function(HookEvent \$event) {
// The page being edited
\$page = \$event->arguments(0);
// The Dynamic Options field
\$field = \$event->arguments(1);
if(\$field->name === '$field->name') {
// Your selectable options as 'value' => 'label'
\$event->return = [
'red' => 'Red',
'green' => 'Green',
'blue' => 'Blue',
];
}
});</code></pre>";
$inputfields->add($f);
return $inputfields;
}
}