diff --git a/lib/Lewp/Forms/Torunn.php b/lib/Lewp/Forms/Torunn.php new file mode 100644 index 0000000..d4f9e02 --- /dev/null +++ b/lib/Lewp/Forms/Torunn.php @@ -0,0 +1,70 @@ +childNodes; + $children_count = count($children); + for ($i = 0; $i < $children_count; ++$i) { + $child = $children[$i]; + + if (in_array($child->tagName, self::$direct_inputs)) { + self::fillDirectInput($child, array_shift($data) ?? ''); + continue; + //$child->setAttribute('value', array_shift($data) ?? 'empty'); + } + + if ($child->tagName === 'select') { + self::fillSelectElement($child, array_shift($data) ?? ''); + continue; + } + + if ($recursive) { + self::traverse($child, $data); + } + } + } + + private static function fillDirectInput($node, $value) + { + if ($value === '') { + return; + } + $node->setAttribute('value', $value); + } + + private static function fillSelectElement($node, $value) + { + if ($value === '') { + return; + } + $children = $node->childNodes; + foreach ($children as $child) { + if (($child->tagName === 'option') + && ($child->getAttribute('value') === $value) + ) { + $child->setAttribute('selected', 'selected'); + return; + } + } + } +} diff --git a/module.php b/module.php index d9f6a6a..09fe9a7 100644 --- a/module.php +++ b/module.php @@ -1,12 +1,14 @@ collectFormKeys()) > 0; @@ -193,6 +192,10 @@ return new class extends Module public function run(array $options = []) : bool { + // add default options + $options += [ + self::OPTIONS_DATA => [], + ]; // SETUP FORM ATTRIBUTES $this->setAttribute('method', $options[self::OPTIONS_METHOD] ?? 'POST'); $this->setAttribute( @@ -200,8 +203,13 @@ return new class extends Module $this->processAction($options[self::OPTIONS_ACTION]) ?? '/' ); - $this->setupForm($options[self::OPTIONS_ELEMENTS]); + + // if data is present, filter the correct keys and fill the form + if (!empty($options[self::OPTIONS_DATA])) { + Torunn::fill($this, $options[self::OPTIONS_DATA]); + } + if ($this->isSubmitted()) { return false; }