How to Make Sticky Form Fields with PHP

Posted on: September 7th, 2015 by BuildMyWeb No Comments

Sticky Form Fields refers to having field Values populate in their respective fields in a form once submitted. So a user does not have to re-type the data if there is an error and the user is asked to correct a field(s).

Sticky Forms with PHP SESSIONs

The way I go about it is to place all $_POST values from a form submission into the SESSION array. I set all POST values to SESSION in my form handler script. So once a form is submitted, all fields with data in them are submitted to the SESSION. Then when we re-read the form, if a particular SESSION var isset(), I use it as that field’s value.

Here it is in action. This form requires, among other things, that we provide a valid email address. Our user typed in a First Name and a Last Name, then clicked the submit button. The form handler script brought us back to the page with the form, and displays a helpful message, letting the user know the email field is required. Normally, the data submitted in the First Name and Last Name fields would be lost. Thanks to Sticky Form Fields, they are saved and pre-populated in our form fields so that our user does not have to re-type them!

PHP Sticky Form Fields

Sticky Functions

I have a couple of functions that I use in my personal library on all projects. I call them from inside the HTML form for each field.


function do_sticky_field( $field_name )
{
    echo'name="' . $field_name . '"';
    
    if( !empty($_SESSION[$field_name]) )
    { echo' value="' . $_SESSION[$field_name] . '"'; }
}

function do_sticky_select( $name, $arr_options )
{
    echo'<select name="' . $name . '"><option value=""></option>';
        
    foreach( $arr_options as $key => $val )
    { 
        echo'<option value="' . $key . '"';
        if( $_SESSION[$name] == $key ){ echo' selected="selected"'; }
        echo'>' . ucwords($val) . '</option>'; 
    }
    
    echo'</select>';
}

Calling the Functions from the HTML Form

I call these functions from inside my HTML form like such:


<?php do_sticky_select( 'select_name', array('tv'=>'Television', 'internet'=>'Internet', 
'friend'=>'Friend or Relative', 'other'=>'Other') ); ?> 

<input type='text' <?php do_sticky_field('input_name'); ?> />

Place POST Vars into SESSION Array in Handler

The final piece of the puzzle is to place all desired field values from the POST array into the SESSION array in our handler script once the form is submitted:


// any POST vars not being stored in SESSION should come after this loop
foreach( $_POST as $key => $val )
{
    if( isset($val) )
    { $_SESSION[$key] = $val; }
}
Tags:

Leave a Reply