From 4fef660d7c28e421b3c1db4621c272a842b5d38f Mon Sep 17 00:00:00 2001 From: Lewin Probst Date: Sat, 21 Mar 2020 13:20:56 +0100 Subject: [PATCH] Added on_submit parameter that receives a callback with one parameter to access the submitted data. --- module.php | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/module.php b/module.php index 5626fe2..c651f0e 100644 --- a/module.php +++ b/module.php @@ -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(