Added option to fill the form by adding the data parameter to the options.
This commit is contained in:
parent
eec70787ef
commit
1fb5d6320d
2 changed files with 82 additions and 4 deletions
70
lib/Lewp/Forms/Torunn.php
Normal file
70
lib/Lewp/Forms/Torunn.php
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Lewp\Forms;
|
||||
|
||||
class Torunn
|
||||
{
|
||||
|
||||
private static $direct_inputs = [
|
||||
'input'
|
||||
];
|
||||
|
||||
private static $indirect_inputs = [
|
||||
'select'
|
||||
];
|
||||
|
||||
public static function fill(\DOMNode $form, array $data_array)
|
||||
{
|
||||
self::traverse($form, $data_array);
|
||||
}
|
||||
|
||||
private static function traverse($node, array &$data, bool $recursive = true)
|
||||
{
|
||||
$children = $node->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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue