I'm not sure if I'm being clever or making things more difficult. I'm working within a custom MVC framework, and within some of my "views" which contain forms I'm preserving input and styling errors as follows:
<form action="submit" method="POST">
<label for="name" class="italic">Name:</label>
<input <?php if (in_array('name', $error)) { echo 'class="form-error"'; } ?> type="text" name="name" value="<?php if (isset($name)) { echo $name; } elseif (isset($valid_user)) { echo $valid_user['name']; } ?>" maxlength="20" required="required" />
<br /><input type="submit" class="submit" value="Update" />
In this example, $valid_user['name']
would be the default value for existing data (when the form is first loaded), and $name
would be the posted value being displayed here again in case there was a user error that needs to be fixed.
Embedding all of these values is very time consuming when creating new forms, so I'm trying to make things easier on myself. I want to stick with a server-side solution since I believe websites should be complimented by Javascript, not dependent on it. I figure I could probably do all of this dynamically using PHP's DOMDocument:
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHTMLFile($view);
$forms = $dom->getElementsByTagName('form');
$total_forms = $forms->length;
for ($i = 0; $i < $total_forms; $i++) {
$inputs = $forms->item($i)->getElementsByTagName('input');
$total_inputs = $inputs->length;
if ($total_inputs > 0) {
foreach ($inputs as $input) {
$type = $input->getAttribute('type');
switch ($type) {
case 'text':
// check for errors
$attr_name = $input->getAttribute('name');
if (in_array($attr_name, $error)) {
$input->setAttribute('class', 'form-error');
}
// check for default / posted values
if (isset($$attr_name)) {
$input->setAttribute('value', $$attr_name);
} elseif (isset($_POST[$attr_name])) {
$input->setAttribute('value', $_POST[$attr_name]);
}
break;
}
}
}
}
echo $header;
// remove unwanted tags that are being automatically added
echo preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
echo $footer;
Going with this approach will obviously require writing a lot of extra code, so before going any further I'm just curious what your opinions are or if there are any potential downfalls I'm maybe not thinking of? Would it be better to stick with my original approach or are there other solutions to make this less tedious?