Jump to content

NOOB nees help making php remember what user selects from a form select box


sigkill-9

Recommended Posts

I'm currently taking an "Intro to PHP" class in college and working ahead in homework and I'm trying to figure out how to keep an array item selected inside a <select> form element if/when a form returns with an error, but I cant seem to figure it out....  Take the below form for example:

 

<html>
<head>
<title>Select an Actor</title>
</head>
<body>
<h2>Select an Actor</h2>
<form action="process_form.php">
<input type="text" name="name">
<?php
    if (strlen($_POST['name']) == 0) {
        echo = 'Name required';
    }
?>
<select name="character">
<?php
$cast = array('Carol' => 'Natalie Wood',
              'Bob' => 'Robert Culp',
              'Ted' => 'Elliott Gould',
              'Alice' => 'Dyan Cannon');
foreach($cast as $role => $actor) {             
  echo "<option value=\"$role\">$actor</option>\n";
}
?>
</select>
<input type="submit" value="Find Role">
</body>
</html>

 

I put the error check on the name field only so, when it returns an error, I could see if the selection would stay selected if the form refreshes.

 

The form by itself works, but if it returns an error, the selection that the user made in the select box is reset back to "Natalie Wood", instead of remembering what the user selected (so the user doesnt have to keep selecting over and over. 

 

Basically I'm trying to get the form to remember which selection the user made in the select box if the form is refreshed or returns errors.

 

I know that if I was using a form based array such as:

<select name="dropdown">
<option value="bob">Robert Culp</option>
<option value="ted">Elliott Gould</option>
<option value="alice">Dyan Cannon</option>

 

I could simply insert a php snippet into each option line like so:

<select name="dropdown">
<option value="bob"  <?php echo $bob; ?> >Robert Culp</option>
<option value="ted"  <?php echo $ted; ?> >Elliott Gould</option>
<option value="alice"  <?php echo $alice; ?> >Dyan Cannon</option>

 

Then further up in the form, declare:

<?php
$x=$_POST['dropdown'];
$$x="selected";
?>

 

But this wont exactly (or it seems it wont) work with the first example array above...

 

How would I get a form (or php) to remember a multi-dimensional array element that the user selected  and re-select it if the form refreshes?

 

The first form code above is merely an example of what I'm working with. Below, I'll insert the actual code I'm using, it's just quite long because the includes file has allot of error checking stuff and functions in it...

 

Here it goes:

This is the main php file "test.php"

<?php
include "test_includes.php";
$pkgLength = floatval($_POST['pkg_length']);
$pkgWidth = floatval($_POST['pkg_width']);
$pkgHeight = floatval($_POST['pkg_height']);
$pkgWeight = floatval($_POST['pkg_weight']);
$var = process_form();
$css = page_css();
$header = page_header('test.php','Create a shipping form that validates data');
echo $css;
echo $header;
echo '<div class="container">';
if ($_POST['_submit_check']){
    if ($form_errors = validate_form( )) {
        show_form($form_errors);
	}
	else {
        echo $var;
    }
}
else {
	show_form( );
}
echo '</div>';
page_footer();   
print_r($_POST);	
?>

 

And here is the includes file "test_includes.php".

It is a work in progress... The function form(); contains the logic for the remembering of the state selection (but it doesnt work).

See line 127 for the $states array, and line 148 through 158 is what I was playing with to try to get it to remember a state selection :

<?php
function page_css(){
$css  = "<style type='text/css'>";
$css .= "<!--";
$css .= ".inputColor {background-color:#FFF89D;}";
$css .= ".pkg {display:block;width:65px;float:left;}";
$css .= ".pkgDimensions {background-color:#FFF89D;display:block;width:45px}";
$css .= ".inputContainer {display:block;width:250px;height:24px;}";
$css .= ".input {background-color:#FFF89D;display:block;width:175px;height:24px;padding-top:2px;float:right;}";
$css .= ".inputLabel{display:block;width:65px;float:left;text-align:right;padding-top:5px;}";
$css .= ".title {display:block;width:450px;margin-left:auto;margin-right:auto;text-align:center;}";
$css .= ".author {display:block;width:200px;margin-left:auto;margin-right:auto;margin-top:5px;font-size:12px;text-align:center;}";
$css .= ".container {border:2px solid black;width:330px;height:auto;background-color:#7EA9C8;padding:15px;margin-left:auto;margin-right:auto;margin-top:15px;}";
$css .= ".footer {display:block;width:200px;margin-left:auto;margin-right:auto;margin-top:10px;text-align:center;}";
$css .= "-->";
$css .= "</style>";
return $css;
}
function page_header($titleBar='page title',$pageTitle='place title here'){
$header  = '<html><head><title>'.$titleBar.'</title></head>';
$header .= '<body style="background-color:CCCCCC">';
$header .= '<span class="title"><b>'.$pageTitle.'</b></span>';
$header .= '<span class="author">by Sigkill-9</span>';
$header .= '<br />';
return $header;
}
function page_footer() {
echo '<span class="footer"><i>Powered by PHP</i></span></body></html>';
}
function process_form() {
$var .= "<b>Sender Details:</b><br />";
$var .= "<hr />";
$var .= "     ".$_POST['sender_name']."<br />";
$var .= "     ".$_POST['sender_address']."<br />";
$var .= "     ".$_POST['sender_city'].", ".$_POST['sender_state']." ".$_POST['sender_zipcode']."<br /><br /><br />";
$var .= "<b>Recipient Details:</b><br />";
$var .= "<hr />";
$var .= "     ".$_POST['recipient_name']."<br />";
$var .= "     ".$_POST['recipient_address']."<br />";
$var .= "     ".$_POST['recipient_city'].", ".$_POST['recipient_state']." ".$_POST['recipient_zipcode']."<br /><br /><br />";
$var .= "<b>Package Details:</b><br />";
$var .= "<hr />";
$var .= "     Dimensions: ".$GLOBALS['pkgLength']."”L x ".$GLOBALS['pkgWidth']."”W x ".$GLOBALS['pkgHeight']."”H<br />";
$var .= "     Weight: ".$GLOBALS['pkgWeight']." Lbs.<br /><br />";
return $var;
}
function show_form($errors = '') {
    // If errors exist, print them
    if ($errors) {
        echo 'Please correct these errors: <ul><li>';
        echo implode('</li><li>', $errors);
        echo '</li></ul>';
	form();
    }
else {
	form();
}
}	
// VALIDATION
function validate_form( ) {
    $errors = array();
// sender validation:
    if (strlen($_POST['sender_name']) == 0) {
        $errors[ ] = 'Sender name required';
    }
    if (strlen($_POST['sender_address']) == 0) {
$errors[ ] = 'Sender address required';
    }
    if (strlen($_POST['sender_city']) == 0) {
$errors[ ] = 'Sender city required';
    }
    if (strlen($_POST['sender_state']) == 0) {
$errors[ ] = 'Sender state required';
    }
    if($_POST['sender_zipcode'] == null) {$errors[ ] = 'Sender zipcode required';}
    elseif(! preg_match("/^[0-9]{5}$/", $_POST['sender_zipcode'])) { $errors[ ] = 'Sender zipcode = '. $_POST['sender_zipcode'] . '<br />Valid sender zipcode required';}
// recipient validation:
    if (strlen($_POST['recipient_name']) == 0) {
        $errors[ ] = 'Recipient name required';
    }
    if (strlen($_POST['recipient_address']) == 0) {
$errors[ ] = 'Recipient address required';
    }
    if (strlen($_POST['recipient_city']) == 0) {
$errors[ ] = 'Recipient city required';
    }
    if (strlen($_POST['recipient_state']) == 0) {
$errors[ ] = 'Recipient state required';
    }
    if($_POST['recipient_zipcode'] == null) {$errors[ ] = 'Recipient zipcode required';}
    elseif(! preg_match("/^[0-9]{5}$/", $_POST['recipient_zipcode'])) {$errors[ ] = 'Recipient zipcode = '. $_POST['recipient_zipcode'] . '<br />Valid recipient zipcode required';}
// package validation:
    if (floatval($_POST['pkg_length']) > 36) {
        $errors[ ] = 'Package length = '. floatval($_POST['pkg_length']) . "<br />Package length cannot exceed 36 inches";
    }
    if (floatval($_POST['pkg_length']) <= 0) {
        $errors[ ] = 'You must enter a valid package length';
    }
    if (floatval($_POST['pkg_width']) > 36) {
        $errors[ ] = 'Package width = '. floatval($_POST['pkg_width']) . "<br />Package width not to exceed 36 inches";
    }
    if (floatval($_POST['pkg_width']) <= 0) {
        $errors[ ] = 'Package width required';
    }
    if (floatval($_POST['pkg_height']) > 36) {
        $errors[ ] = 'Package height = '. floatval($_POST['pkg_height']) . "<br />Package height not to exceed 36 inches";
    }
    if (floatval($_POST['pkg_height']) <= 0) {
        $errors[ ] = 'Package height required';
    }
    if (floatval($_POST['pkg_weight']) > 150){
        $errors[ ] = 'Package weight not to exceed 150 pounds';
    }
    if (floatval($_POST['pkg_weight']) <= 0){
        $errors[ ] = 'Package weight required';
    }
// display errors (if any)
    return $errors;
}
function form(){
$states = array('AK'=>'Alaska','AL'=>'Alabama','AR'=>'Arkansas','AZ'=>'Arizona','CA'=>'California','CO'=>'Colorado','CT'=>'Connecticut','DC'=>'District of Columbia','DE'=>'Delaware','FL'=>'Florida','GA'=>'Georgia','HI'=>'Hawaii','IA'=>'Iowa','ID'=>'Idaho','IL'=>'Illinois','IN'=>'Indiana','KS'=>'Kansas','KY'=>'Kentucky','LA'=>'Louisiana','MA'=>'Massachusetts','MD'=>'Maryland','ME'=>'Maine','MI'=>'Michigan','MN'=>'Minnesota','MO'=>'Missouri','MS'=>'Mississippi','MT'=>'Montana','NC'=>'North Carolina','ND'=>'North Dakota','NE'=>'Nebraska','NH'=>'New Hampshire','NJ'=>'New Jersey','NM'=>'New Mexico','NV'=>'Nevada','NY'=>'New York','OH'=>'Ohio','OK'=>'Oklahoma','OR'=>'Oregon','PA'=>'Pennsylvania','PR'=>'Puerto Rico','RI'=>'Rhode Island','SC'=>'South Carolina','SD'=>'South Dakota','TN'=>'Tennessee','TX'=>'Texas','UT'=>'Utah','VA'=>'Virginia','VT'=>'Vermont','WA'=>'Washington','WI'=>'Wisconsin','WV'=>'West Virginia','WY'=>'Wyoming');
$sender_name = $_POST['sender_name'];
$sender_address = $_POST['sender_address'];
$sender_city = $_POST['sender_city'];
$sender_zipcode = $_POST['sender_zipcode'];
$recipient_name = $_POST['recipient_name'];
$recipient_address = $_POST['recipient_address'];
$recipient_city = $_POST['recipient_city'];
$recipient_zipcode = $_POST['recipient_zipcode'];
$pkg_length = $_POST['pkg_length'];
$pkg_width = $_POST['pkg_width'];
$pkg_height = $_POST['pkg_height'];
echo<<<_HTML_
<b><center>Enter Sender Details Below:</b></center>
<hr />
<form method="post" action="$_SERVER[php_SELF]">
	<div class="inputContainer"><div class="inputLabel">Name:</div><input class="input" type="text" name="sender_name" value="$sender_name"></div>
	<div class="inputContainer"><div class="inputLabel">Address:</div><input class="input" type="text" name="sender_address" value="$sender_address"></div>
	<div class="inputContainer"><div class="inputLabel">City:</div><input class="input" type="text" name="sender_city" value="$sender_city"></div>
	<div class="inputContainer"><div class="inputLabel">State:</div><select class="input" name="sender_state">
_HTML_;
    $returnStatement = '';
    if (isset($states['val'])) {
    	foreach ($states as $val => $choice) {	
        	$returnStatement .= '<option selected="selected" value="' . $val . '">' . $choice . '</option>';
    	}
    } else {
    	foreach ($states as $val => $choice) {	
        	$returnStatement .= '<option value="' . $val . '">' . $choice . '</option>';
    	}
    }
    echo $returnStatement;
echo<<<_HTML_
	</select></div>
	<div class="inputContainer"><div class="inputLabel">Zipcode:</div><input class="input" type="text" name="sender_zipcode" value="$sender_zipcode"></div><br /><br />
	<b><center>Enter Recipient Details Below:</center></b><hr />
	<div class="inputContainer"><div class="inputLabel">Name:</div><input class="input" type="text" name="recipient_name" value="$recipient_name"></div>
	<div class="inputContainer"><div class="inputLabel">Address:</div><input class="input" type="text" name="recipient_address" value="$recipient_address"></div>
	<div class="inputContainer"><div class="inputLabel">City:</div><input class="input" type="text" name="recipient_city" value="$recipient_city"></div>
	<div class="inputcontainer"><div class="inputLabel">State:</div><select class="input" name="recipient_state">
_HTML_;
	foreach ($states as $val => $choice) {echo "<option value=\"$val\">$choice</option>\n";}
echo<<<_HTML_
	</select></div>
	<div class="inputContainer"><div class="inputLabel">Zipcode:</div><input class="input" type="text" name="recipient_zipcode" value="$recipient_zipcode"></div><br /><br />
	<b><center>Enter Package Details Below:</center></b><hr />
	<div style="display:block;width:351px;height:75px;">Dimensions (in inches):<br /> 
		<div style="display:block;width:210px;height:45px;margin-top:5px;margin-left:75px;">
			<span class="pkg">Length<input class="pkgDimensions" type="text" name="pkg_length" value="$pkg_length"></span>
			<span class="pkg">Width<input class="pkgDimensions" type="text" name="pkg_width" value="$pkg_width"></span>
			<span class="pkg">Height<input class="pkgDimensions" type="text" name="pkg_height" value="$pkg_height"></span>
		</div>
	</div>
	<div class="inputContainer"><div class="inputLabel">Weight:</div><input class="input" type="text" name="pkg_weight" value="$pkg_weight"></div><br /><br />
	<hr /><center><input type="submit" value="Submit"></center><hr /><input type="hidden" name="_submit_check" value="1">
</form>
_HTML_;
}
?>

Link to comment
Share on other sites

You are on the right track, but missing a detail.

 

The element that is selected needs to have that attribute set in the html markup as you indicated.  A small mod similar to this will allow you to continue to work with your array and foreach loop.

 

foreach($cast as $role => $actor) {
  $t = "  if ($role === $_POST['dropdown']) 
    $t .= ' selected';
  echo $t . ">$actor\n";
}

 

Link to comment
Share on other sites

It worked! Thanks for your help, you rock! 

 

Now I have to go study this to make sure I fully understand what the code is doing. I understand what . and .= do, but I havent yet learned what the triple equal sign in your example does. I'll read my PHP book and see if I can understand it.

 

Thanks again, you're a HUGE help :)

Link to comment
Share on other sites

  • 2 months later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.