Momololo
Momololo

Reputation: 17

How to cache user input in form

I'm trying to cache the user input in my form. My code is:

    echo '
<form method="POST">
    Name:<br /><input class="contact_name" type="text" name="contact_name" maxlength="32" placeholder="Enter Name" /><br />
    Email:<br /><input class="contact_email" type="text" name="contact_email" maxlength="50" placeholder="Email Address" /><br />
    Subject:<br /><input class="contact_subject" type="text" name="contact_subject" maxlength="50" placeholder="Subject Line" /><br />
    Message:<br /><textarea class="message_area" name="contact_message" rows="10" cols="50" maxlength="1000" placeholder="Message ..." /></textarea><br />
    <input class="submit_button" name="submit_button" type="submit" value="Send" />
</form>
';

I tried searching for the answer and the only thing I found was adding:

<?php if(isset($contact_name)) { echo $contact_name; } ?>

This however does not work for me as my form is within a PHP echo and I'm trying to make a basic wordpress plugin. Whenever I bring the form outside the echo and , the style messes up and the form style itself breaks. So I was wondering if I can keep my form inside my echo along with a placeholder and be able to cache user inputs so when an error displays cause they didn't fill one of the spots out, it won't erase everything.

Thank you.

Upvotes: 0

Views: 913

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173642

Then, just drop the echo and switch to HTML mode:

?>
<form method="post">
Name:<br /><input ... value="<?php echo (isset($contact_name) ? htmlspecialchars($contact_name, ENT_QUOTES, 'UTF-8') : ''; ?>" />
...
<?php

If you need this as a string, you could use output buffering:

ob_start();
?>
<input ... />
<?php

echo ob_get_clean();

Upvotes: 1

Related Questions