Jump to content

Saving SELECT value on form


phppup
Go to solution Solved by Barand,

Recommended Posts

I'm not sure if I've got a syntax or an implementation problem, but I've created a form entirely in PHP.

Essentially, each item is pulled from an array and named with the associated key index.

Each item is attached to a drop-down menu containing integers 0 thru 10 (indicating the quantity for an order).

On submission of the form, I want the selected values to be retained.

If other fields of the form are not complete, error messages will display, and I want these values to be retained rather than resetting.

 

for($i = 0; $i < 11; $i++){
$quantity .= "<option>".$i."</option>";
}


for($i = 0; $i < count($arr); $i++){

echo "select name='amt_".$i."'>".$quantity."</select>";
}

How can I have each drop-down retain it's value after a (failed) submit effort?

Link to comment
Share on other sites

  • Solution

Set the "selected" attributes of the options containing the selected values in each dropdown

For example

<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
    echo "You ordered the following quantities<br>";
    foreach ($_POST['qty'] as $i => $qty) {
        if ($qty) {
            echo "Item $i : $qty<br>";
        }
    }
    echo "<hr>";
}

function qtyOptions($current)
{
    $opts = '';
    for ($i=0; $i<11; $i++) {
        $sel = $i==$current ? 'selected' : '';
        $opts .= "<option $sel value='$i'>$i</option>\n";
    }
    return $opts;
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Example</title>
<meta charset='utf8'>
</head>
<body>
    <form method='POST'>
        Item 1 <select name='qty[1]'><?= qtyOptions($_POST['qty'][1] ?? 0)?></select> <br>
        Item 2 <select name='qty[2]'><?= qtyOptions($_POST['qty'][2] ?? 0)?></select> <br>
        Item 3 <select name='qty[3]'><?= qtyOptions($_POST['qty'][3] ?? 0)?></select> <br>
        <br>
        <input type='submit'>
    </form>
</body>
</html>

 

Link to comment
Share on other sites

Let me add to Barand's response. The typical process I take with forms is as follows:

  1. Form pages will POST to themselves
  2. When a form page loads it will first determine if a submission was made. If no submission is made, proceed to creating the form
  3. If a submission was made, then I will have the code go through form validation logic to ensure that all required data was submitted and that all submitted data is appropriate (e.g. a numeric field should have a numeric value, a date field should include a value that can be interpreted as a date, if something should match a DB id value, make sure that value exists, etc.)
  4. During the validation, for any errors that are encountered save appropriate error messages in an array/object, then proceed to creating the form.
  5. If no errors in validation, then execute the code to act on the submitted data - e.g. do a DB INSERT. Then redirect to a confirmation page.

CREATE THE FORM:

If there was no form submission or if there were errors in the data validation, create the form for user input. If there were errors, you can repopulate any valid data back into the appropriate fields so the user does not need to reenter. For errors, you can list them all at the top of the page (easy) or you can list them out above/below the individual fields where the errors occurred. You would just need to store the errors in the array/object in a way to correspond them to the input fields where they originated.

I also like to create functions for building my various input fields. That way I can call the function with appropriate parameters so it can build the field either with the default/empty value or with a previously entered value. That way I don't have to write the same 6-10 lines of code to handle those two scenarios for every input field.

Link to comment
Share on other sites

Quote

That way I don't have to write the same 6-10 lines of code to handle those two scenarios for every input field.

@Psycho Thanks for the outline of information. I've begun to understand and get comfortable with the effectiveness of  arrays (I think... LOL).

This is an attempt at using arrays meaningfully.

Thanks for the guidance.

 

@Barand  I think I follow what you are doing here, and I'm trying to confirm it to my code.

However, my understanding of PHP-shorthand is not very good. Can you elaborate/simplify what this

Quote

<?= qtyOptions($_POST['qty'][1] ?? 0)?>

 actually means, please.

I realize that:

qtyOptions is calling the function and

$_POST['qty'][1] will provide a value as $current

What is <?= doing?

What do the ?? mean?

Link to comment
Share on other sites

@Barand So I guess at this point my question is, what is the correct syntax to use within the option tag while creating it with PHP?

It seems simple enough under "normal conditions", but I am echoing

echo "select name='amt_".$i."'>".$quantity."</select>";

the drop-down and using PHP to populate the options through a loop.

I can't put an echo inside an echo, can I?

I understand that some re-working will be necessary, but my goal was to create the for as a large PHP echo without direct HTML usage.

Link to comment
Share on other sites

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.