Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Keep entered values after validation error

I have a simple form that needed validation.
I did this with the empty() function. If the validation doesn't pass it gives the user an alert. As soon as this alert is created all entered values are gone.

I would like to keep them.

This is what I did:

<form id="" name="" action="<?php echo get_permalink(); ?>" method="post">
    <table>
        <tr>
            <td>
                Name:<input type="text" id="name" name="name">
            </td>
        </tr>
        <tr>
            <td>
                <input class="submit-button" type="submit" value="Send" name="submit">
            </td>
        </tr>
    </table>
</form>
<?php
    if($_POST["submit"]){
        if (!empty ($_POST["name"])){
          // do something
        }else{
            ?>
            <script type="text/javascript">
                alert('U heeft niet alle velden ingevuld. Graag een volledig ingevuld formulier versturen');
            </script>
            <?php
        }
?>  
like image 682
Interactive Avatar asked Oct 22 '15 08:10

Interactive


1 Answers

Bizarrely I happen to be working on a similar thing and have been using the following to ensre that form data is available after submission of the form. It uses a session variable to store the results of the POST and is used as the value in the form field.

/* Store form values in session var */
if( $_SERVER['REQUEST_METHOD']=='POST' ){
    foreach( $_POST as $field => $value ) $_SESSION[ 'formfields' ][ $field ]=$value;
}

/* Function used in html - provides previous value or empty string */
function fieldvalue( $field=false ){
        return ( $field && !empty( $field ) && isset( $_SESSION[ 'formfields' ] ) && array_key_exists( $field, $_SESSION[ 'formfields' ] ) ) ? $_SESSION[ 'formfields' ][ $field ] : '';
}

/* example */
echo "<input type='text' id='username' name='username' value='".fieldvalue('username')."' />";
like image 124
Professor Abronsius Avatar answered Sep 28 '22 21:09

Professor Abronsius