-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFormBuilderMultiplier.module
More file actions
412 lines (331 loc) · 14.3 KB
/
Copy pathFormBuilderMultiplier.module
File metadata and controls
412 lines (331 loc) · 14.3 KB
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
<?php namespace ProcessWire;
/**
* Dynamically multiply Fieldsets in FormBuilder forms.
*
* Adds a configuration option to fieldsets in FormBuilder that allows
* users in the form to multiply the fields inside the fieldset, like
* a lightweight repeater.
*
* You can optionally configure a limit too.
*
* Technical description:
* The original field names are suffixed with _NUM, where NUM is a number
* starting from 1. The labels are suffixed accordingly too.
*
* (C) 2018 by BitPoet
*
* Licensed under MPL v2
*
*/
class FormBuilderMultiplier extends WireData implements Module, ConfigurableModule {
public static function getModuleInfo() {
return [
'title' => __("FormBuilder Fieldset Multiplier", __FILE__),
'summary' => __("Allows Repeater-like multiplying of fieldsets in FormBuilder forms in the frontend", __FILE__),
'version' => '0.0.11',
'requires' => array("FormBuilder"),
'autoload' => true,
];
}
public function _construct() {
parent::_construct();
$this->set("editingField", false);
}
public function init() {
$this->addHookBefore("ProcessFormBuilder::buildEditField", $this, "rememberEditingField");
$this->addHookAfter("ProcessFormBuilder::buildEditField", $this, "forgetEditingField");
$this->addHookAfter("InputfieldFieldset::getConfigInputfields", $this, "addMultiplierConfig");
$this->addHookBefore("FormBuilderProcessor::renderReady", $this, "addMultipliedFieldsToProcessor");
$this->addHookBefore("FormBuilderProcessor::populate", $this, "addMultipliedFieldsToPopulate");
$this->addHookAfter("FormBuilderProcessor::processInputReady", $this, "addMultipliedFieldsToProcessInput");
$this->addHookAfter("FormBuilderProcessor::render", $this, "appendJSConfig");
$this->addHookAfter("FormBuilderProcessor::savePageDone", $this, "addMultipliedFieldsToPage");
$this->addHookAfter('Page::render', $this, 'addScripts');
}
public function addScripts($event) {
$page = $event->object;
if(!empty($this->excludeTemplates) && in_array($page->template->name, $this->excludeTemplates))
return;
if($page->template == 'admin')
return;
$additionalHeadScripts = '<script type="text/javascript" src="' . wire('config')->urls->{$this->className()} . 'FormBuilderMultiplier.js"></script>';
$event->return = str_replace("</head>", $additionalHeadScripts.'</head>', $event->return);
}
/**
* Hook after FormBuilderProcessor::render
* Appends configuration for the module script (mainly translations)
*/
public function appendJSConfig(HookEvent $event) {
$jsconf = [
"config" => [
"messages" => [
"rowlimit" => $this->_("Maximum number of rows ({0}) reached.")
]
]
];
$out = "<script>var FBMultiplier = " . json_encode($jsconf) . ";</script>\n";
$event->return .= $out;
}
/**
* Hook before ProcessFormBuilder::buildEditField, saves the currently
* editing field in the instance so the hook to InputfieldFieldset::getConfigInputfields
* can retrieve the configuration data from it.
*/
public function rememberEditingField(HookEvent $event) {
$this->editingField = $event->arguments(0);
}
/**
* Hook after ProcessFormBuilder::buildEditField, removes the reference
* to the field being edited from the instance after config fields have
* been added.
*/
public function forgetEditingField(HookEvent $event) {
$this->editingField = false;
}
/**
* Add config options for multiplier to fieldsets in the form editor
*/
public function addMultiplierConfig(HookEvent $event) {
if($event->page->process == 'ProcessFormBuilder') {
$f = $this->modules->get("InputfieldCheckbox");
$f->attr('name', 'multiplyGroup');
$f->label = $this->_("Multiply fields in this set");
if($this->editingField->multiplyGroup) $f->attr('checked', 'checked');
$f->description = $this->_("If this box is checked, the user will be presented with a button that adds another set of the fields in this field group.") . " " .
$this->_("The field names for each set will get a numeric suffix (e.g. surname_1, surname_2, givenname_1, givenname_2 ...)")
;
$event->return->append($f);
$f = $this->modules->get("InputfieldInteger");
$f->attr('name', 'multiplyLimit');
$f->label = $this->_("Multiplication limit");
$f->attr('value', $this->editingField->multiplyLimit ?: 0);
$f->description = $this->_("Limit the number of possibile multiplications of this fieldset's fields. 0 (default) means unlimited.");
$f->columnWidth = 25;
$f->showIf = "multiplyGroup=1";
$event->return->append($f);
$f = $this->modules->get("InputfieldText");
$f->attr('name', 'rowHead');
$f->label = $this->_("Headline for rows");
$f->attr('value', $this->editingField->rowHead ?: 'Row');
$f->description = $this->_("Headline for single rows.");
$f->columnWidth = 25;
$f->showIf = "multiplyGroup=1";
$f->useLanguages = true;
$event->return->append($f);
$f = $this->modules->get("InputfieldText");
$f->attr('name', 'multiplyLabel');
$f->label = $this->_("Label \"Add row\"");
$f->attr('value', $this->editingField->multiplyLabel ?: 'Add row');
$f->description = $this->_("Label of button to add a new row.");
$f->columnWidth = 25;
$f->showIf = "multiplyGroup=1";
$f->useLanguages = true;
$event->return->append($f);
$f = $this->modules->get("InputfieldText");
$f->attr('name', 'removeLabel');
$f->label = $this->_("Label \"Delete last row\"");
$f->attr('value', $this->editingField->removeLabel ?: 'Delete last row');
$f->description = $this->_("Label of button to delete the last row.");
$f->columnWidth = 25;
$f->showIf = "multiplyGroup=1";
$f->useLanguages = true;
$event->return->append($f);
}
}
/**
* Hook before FormBuilderProcessor::renderReady to add the necessary
* fiels and buttons to the form (used in frontend and for processing
* the form input.
*/
public function addMultipliedFieldsToProcessor(HookEvent $event) {
// Multi Language Support
if ($this->wire('languages')) {
$userLanguage = $this->wire('user')->language;
$lang = $userLanguage->isDefault() ? '' : "$userLanguage->id";
} else {
$lang = '';
}
$this->log->save('fbmultiplier', "addMultipliedFieldsToProcessor");
//echo wire('config')->scripts->append(wire('config')->urls->FormBuilderMultiplier . "FormBuilderMultiplier.js?ts=" . strftime('%Y%m%d%H%M%S'));
$this->log->save('fbmultiplier', "test");
$form = $event->arguments(0);
$multis = $form->find("className=InputfieldFieldset,multiplyGroup=1"); //FIND THE FIELDSET
foreach($multis as $multi) {
// Skip if form is allready processed
$preventDuplicates = ($multi->hasClass('fb-multiplier-fieldset')) ? true : false;
// Add class for individual styling to the surrounding fieldset
$multi->addClass('fb-multiplier-fieldset');
// Add Headline
$rowHead = $multi->get('rowHead'.$lang);
$info = $this->modules->get("InputfieldMarkup");
$info->attr('name','rowHead');
$info->attr('value','<hr>');
$info->addClass('fb-multiplier-orig-field label fb-multiplier-label uk-margin-remove');
$info->label($rowHead);
$multi->children->prepend($info);
// ADD THE CLASS TO THE INPUT FIELD
// CHANGE THE LABEL TO INCLUDE THE COUNT.
if(!$preventDuplicates) {
$multi->children->each(function($child) {
$child->addClass('fb-multiplier-orig-field');
$child->addClass('label');
if($child->label && $child->attr('name') == "rowHead") $child->label .= " [#1]";
if($child->name) $child->name .= "_1";
});
};
$mname = $multi->name; //NAME OF THE FIELDSET
$multiCount = $this->input->post->{$mname . "__multiplier_rows"} ?: 1; // COUNT THE CURRENT ROWS
$children = $multi->children()->getArray();
if(!$preventDuplicates) {
$hid = $this->modules->get("InputfieldHidden");
$hid->attr('id+name', $mname . "__multiplier_rows");
$hid->attr('data-multiply-limit', $multi->multiplyLimit);
$hid->attr('value', $multiCount);
$multi->insertBefore($hid, $multi->children->first());
}
if($multiCount && $multiCount > 1) {
for($c = 1; $c < $multiCount; $c++) {
$this->cloneFields($children, $multi, $c);
}
// Add class for skipping fieldgroup if it's cloned allready
$multi->addClass('fb-multiplier-cloned');
}
if(! $this->noButtons) {
$mulitplyLabel = $multi->get('multiplyLabel'.$lang);
$removeLabel = $multi->get('removeLabel'.$lang);
$btns = $this->modules->get("InputfieldMarkup");
$btns->columnWidth(100);
$btns->attr('value', "
<button class='uk-button uk-button-small uk-button-primary fb-multiplier-button fb-multiplier-add-row' name='btn_multiy__$mname' data-multiply='$mname' data-multiply-limit='" . intVal($multi->multiplyLimit) . "'>
<span data-uk-icon='icon: plus; ratio: 0.75;'></span> " . $mulitplyLabel . "
</button>
<button class='uk-button uk-button-small uk-button-danger fb-multiplier-button fb-multiplier-remove-row' name='btn_remove__$mname' data-remove='$mname'>
<span data-uk-icon='icon: minus; ratio: 0.75;'></span> " . $removeLabel . "
</button>
");
$multi->append($btns);
}
}
}
/**
* Hook before FormBuilderProcessor::populate to add the necessary fields.
* Used when viewing already submitted data in the backend.
*/
protected function cloneFields($fields, $fieldgroup, $counter) {
foreach($fields as $f) {
// Skip if fieldgroup is cloned allready
if($fieldgroup->hasClass('fb-multiplier-cloned') ) continue;
$fNew = clone($f);
$fNew->removeClass('fb-multiplier-orig-field');
$fNew->wrapClass('fb-multiplier-cloned-field-'.intVal( $counter +1 ));
if($fNew->attr("id")) {
$fNew->attr("id", preg_replace_callback('/^([^"]+_)(\d+)$/', function($match) use($counter) {
$propVal = $match[1] . (intVal($match[2]) + $counter);
return $propVal;
}, $fNew->attr("id")));
}
if($fNew->attr("name")) {
$fNew->attr("name", preg_replace_callback('/^([^"]+_)(\d+)$/', function($match) use($counter) {
$propVal = $match[1] . (intVal($match[2]) + $counter);
return $propVal;
}, $fNew->attr("name")));
}
if($fNew->label) $fNew->label = preg_replace_callback('/ \[#(\d+)\]$/', function($match) use($counter) {
$this->log->save('fbmultiplier', "Incrementing counter for label from " . $match[1] . " by " . $counter);
return " [#" . (intVal($match[1]) + $counter) . "]";
}, $fNew->label);
$fieldgroup->append($fNew);
}
}
public function addMultipliedFieldsToPopulate(HookEvent $event) {
$this->log->save('fbmultiplier', "addMultipliedFieldsToPopulate");
$proc = $event->object;
$form = $proc->getInputfieldsForm();
$data = $event->arguments(0);
$multis = $form->find("className=InputfieldFieldset,multiplyGroup=1");
foreach($multis as $multi) {
// Add class for individual styling to the surrounding fieldset
$multi->addClass('fb-multiplier-fieldset');
$mname = $multi->name;
$multiCount = isset($data[$mname . "__multiplier_rows"]) ? $data[$mname . "__multiplier_rows"] : 1;
$multi->children->each(function($child) {
$child->addClass('fb-multiplier-orig-field');
if($child->label) $child->label .= " [#1]";
if($child->name) $child->name .= "_1";
});
$children = $multi->children()->getArray();
$hid = $this->modules->get("InputfieldHidden");
$hid->attr('id+name', $mname . "__multiplier_rows");
$hid->attr('data-multiplier-limit', $multi->multiplyLimit);
$hid->attr('value', $multiCount);
$hid->label = $this->_("Number of rows");
$multi->insertBefore($hid, $multi->children->first());
if($multiCount && $multiCount > 1) {
for($c = 1; $c < $multiCount; $c++) {
$this->cloneFields($children, $multi, $c);
}
}
}
}
/**
* Hook after FormBuilderProcessor::processInputReady to add the multiplied
* fields before the POST values are processed. Uses the same logic as
* the hook to FormBuilderProcessor::renderReady, with the expception of
* the multiplier button. So a flag is set to skip these buttons.
*/
public function addMultipliedFieldsToProcessInput(HookEvent $event) {
$form = $event->arguments(0);
$this->noButtons = true;
$this->addMultipliedFieldsToProcessor($event);
$this->noButtons = false;
}
public function addMultipliedFieldsToPage(HookEvent $event) {
$form = $event->object->getInputfieldsForm();
$page = $event->arguments(0); // page that was saved
$data = $event->arguments(1); // assoc array of data that was in the form
$multis = $form->find("className=InputfieldFieldset,multiplyGroup=1"); //FIND THE FIELDSET
$sanitizer = $this->wire('sanitizer');
foreach($multis as $multi) {
// Add class for individual styling to the surrounding fieldset
$multi->addClass('fb-multiplier-fieldset');
$mname = $multi->name; //NAME OF THE FIELDSET
$multiCount = $this->input->post->{$mname . "__multiplier_rows"} ?: 1; // COUNT THE CURRENT ROWS
for($c = 1; $c <= $multiCount; $c++) { //ITERATE THROUGH THE REPEATER ROW
${$repFields.'_'.$c} = array();//CREATE AN ARRAY OF 1 REPEATER ROW
foreach ($data as $key => $value) { //ADD THE REPEATER ROW TO THE ARRAY
if(strpos($key,'_'.$c)!==false){
$newkey = str_replace('_'.$c, '', $key);//REMOVE THE _COUNT
${$repFields.'_'.$c}[$newkey] = $sanitizer->entities($value); // ADD TO NEW ARRAY
}
}
//ENTER THEN INTO THE PAGE
$rep = $page->$mname->getNew(); //OPEN THE REPEATER
foreach(${$repFields.'_'.$c} as $k => $v){ //ITTERATE THROUGH THE ARRAY
$rep->$k = $v;
}
$rep->save(); //SAVE THE REPEATER
} //END FOR
}
}
/**
* Config inputfields
*
* @param InputfieldWrapper $inputfields
*/
public function getModuleConfigInputfields(InputfieldWrapper $inputfields) {
$f = $this->modules->get("InputfieldAsmSelect");
$f->label = $this->_('Templates to ignore');
$f->description = $this->_('FormBuilderMultiplier injects a script tag into the page header. If you do not want this to happend in certain templates, select them here.');
$f->attr('name', 'excludeTemplates');
$selTemplates = $this->excludeTemplates ?: [];
foreach($this->templates as $tpl) {
$attrs = [];
if(in_array($tpl->name, $selTemplates))
$attrs['selected'] = 'selected';
$f->addOption($tpl->name, $tpl->name, $attrs);
}
$f->attr('value', $this->exclueTemplates);
$inputfields->append($f);
return $inputfields;
}
}