Added on_submit parameter that receives a callback with one parameter to access the submitted data.

This commit is contained in:
Lewin Probst 2020-03-21 13:20:56 +01:00
parent 71d1f14618
commit 4fef660d7c

View file

@ -9,6 +9,7 @@ return new class extends Module
const OPTIONS_ELEMENT = 'element';
const OPTIONS_LABEL = 'label';
const OPTIONS_DATA = 'data';
const OPTIONS_CALLBACK_ON_SUBMIT = 'on_submit';
// element specific
const OPTIONS_SHOW_PLACEHOLDER = 'show_placeholder';
@ -167,18 +168,18 @@ return new class extends Module
return count($this->collectFormKeys()) > 0;
}
public function getData()
private function extractData()
{
if (!$this->isSubmitted()) {
return [];
}
$data = [];
$extracted_data = [];
$keys = $this->collectFormKeys();
sort($keys, SORT_NUMERIC);
foreach ($keys as $key) {
$data [] = $_POST[$key];
$extracted_data [] = $_POST[$key];
}
return $data;
return $extracted_data;
}
private function processAction($action)
@ -201,7 +202,20 @@ return new class extends Module
// add default options
$options += [
self::OPTIONS_DATA => [],
self::OPTIONS_CALLBACK_ON_SUBMIT => function ($data) {
return true;
},
];
// extract data that has been submitted
$submitted_data = $this->extractData();
if (// there is data that has been submitted, and callback returns false, stop module
!empty($submitted_data)
&& !$options[self::OPTIONS_CALLBACK_ON_SUBMIT]($submitted_data)
) {
return false;
}
// SETUP FORM ATTRIBUTES
$this->setAttribute('method', $options[self::OPTIONS_METHOD] ?? 'POST');
$this->setAttribute(