I’ve a form with select boxes and a value from database which has been chosen before. Yes I need this value which is chosen to be shown as last chosen inside form. I try using php dom but I’ m not getting anywhere.
So here is the html:
<select name="conf_1">
<option value="Y">Yes</option>
<option value="N">No</option>
</select>
<select name="conf_2">
<option value="text">text</option>
<option value="alsotext">alsotext</option>
</select>
And now I would like to show the chosen option which is stored in array like this:
$confs = array([1] => N, [2] => text );
Do some code:
loop{
<option value="$confs[$i]">$confs[$i]</option> has to be appended to <select name="conf_$i">
}
Now I can’t find a way to do this. I’ve tried using php dom but I don’t know how to select element by name attribute and then loop trough so I can’t make a real php example. I just would not know where to start.
If someone just has a way to do this please enlighten me!?
Done it with this code inspired by @Markus I.:
$dom = new DOMDocument();
$dom->loadHTML($form);
$xPath = new DOMXPath($dom);
foreach ($dom->getElementsByTagName('select') as $select) {
$name = $select->getAttribute('name');
$name = str_replace('conf_', '', $name);
foreach($xPath->query('./option', $select) as $option) {
if ($option->getAttribute('value') == $confs[$name]) {
$option->setAttribute('selected', 'selected');
}
}
}
$form = $dom->saveHTML($dom);
echo $form;
I prefer to load the hole template into a DOM and modify it: (Code not tested!)
I wrote a class, which can handle all field-types. Note this is only samplecode. On production you should take care if the key in your data-array exists and so on.
This has a nice Side-effect: Because you set the Value via dom, it protects your form from XSS