user1883050 user1883050 - 1 month ago 21
PHP Question

Simple PHP Form Templating

You have a PHP form with the following field in it:

(code block 1)

City: <input type="text" name="city"><br>


The form's
action attribute
is set to
itself
. When
submitted
to the server, the page validates the field, and if it's invalid it returns the same page with:


  1. An error message

  2. A red border around the form text input box

  3. The value the user originally inputted inside the form input text box



I could use an
if then else
construct and return
code block 2
if invalid.

(code block 2)

<?php echo "The form field with red border has an invalid entry"; ?>
City: <input type="text" name="city"
style="border-color:red" value="<?php echo $record->city ?>"><br>


My question is, if you were to add some templating to
code block 1
so that you wouldn't need
code block 2
, how would you do it?

Please narrow your answer set to:


  1. pure PHP answers (without any external templating libraries or PHP frameworks).

  2. suitable for someone for whom PHP is the only server side scripting they know (and they are relatively inexperienced with it).


Answer

Instead of using an if/else you could create an $has_error associated array and integrate that directly into your original form like so:

City: 
<input type="text" name="city" class="<?= $has_error['city']['class'] ?>" value="<?= $record->city ?>">
<span><?= $has_error['city']['message'] ?></span>
<br>

and structure your validation errors like so:

$has_error = [
  'city' = [
    'class' => '',
    'message'=> ''
  ]
]

Then apply an error class and message on the validation side (where ever you submit your form). So when the city input field doesn't pass validation your $has_error array would look like this:

$has_error = [
  'city' = [
    'class' => 'error',
    'message'=> 'This field has an error'
  ]
]

Your error class would look something like this:

.error{
  border: 2px solid red;
}