-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdminPreSaveValidation.module.php
More file actions
89 lines (74 loc) · 2.59 KB
/
Copy pathAdminPreSaveValidation.module.php
File metadata and controls
89 lines (74 loc) · 2.59 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
<?php namespace ProcessWire;
class AdminPreSaveValidation extends WireData implements Module {
public static function getModuleInfo() {
return array(
'title' => 'Pre-Save Validation',
'version' => '1.1.2',
'summary' => "Forces admin editors to fix all errors before saving a page.",
'author' => 'Mike Spooner (thetuningspoon)',
'href' => 'http://www.solutioninnovators.com',
'singular' => true,
'autoload' => 'template=admin, process=ProcessPageEdit',
'icon' => 'warning',
);
}
public function init() {
$editingPage = $this->wire->pages->get($this->input->id);
$editingPageTemplateName = $editingPage->id ? $editingPage->template->name : null;
if(!$editingPageTemplateName || !$this->enabledOnTemplate($editingPageTemplateName)) return;
$this->config->scripts->add($this->config->urls->$this . "AdminPreSaveValidation.js");
$this->wire()->addHookBefore("ProcessPageEdit::execute", function(HookEvent $event) {
if($event->wire->input->preValidate) {
$event->wire->config->ajax = false; // Turn off ajax flag so ProcessPageEdit's regular ajax processing isn't triggered
}
});
/*
* Example of hook that adds an error to an inputfield
*/
/*
$this->wire()->addHookAfter("Inputfield::processInput", function(HookEvent $event) {
$event->object->error('Invalid input!');
});
*/
$this->wire()->addHookAfter("ProcessPageEdit::processInput", function(HookEvent $event) {
if($event->wire->input->preValidate) {
$form = $event->arguments(0);
$level = $event->arguments(1);
if($level == 0) {
$fieldErrors = [];
// Get all errors from all the inputfields on the page, including repeaters and their inputs
function recurseFields(InputfieldWrapper $form, array &$fieldErrors) {
$fields = $form->getAll();
foreach($fields as $field) {
$errors = $field->getErrors(true);
if(count($errors)) {
$fieldErrors[$field->attr('name')] = implode(', ', $errors);
}
if($field instanceof InputfieldRepeater) {
recurseFields($field->buildForm(), $fieldErrors);
}
}
}
recurseFields($form, $fieldErrors);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($fieldErrors);
exit;
}
}
});
}
public function enabledOnTemplate($templateName) {
$enabled = false;
if($this->applyMode == 'exclude') {
if(!in_array($templateName, $this->selectedTemplates)) {
$enabled = true;
}
}
elseif($this->applyMode == 'include') {
if(in_array($templateName, $this->selectedTemplates)) {
$enabled = true;
}
}
return $enabled;
}
}