Forum Moderators: coopster

Message Too Old, No Replies

Trying to reuse array values in input fields

         

varttina

3:28 am on Sep 30, 2011 (gmt 0)

10+ Year Member



Hi there!

Outline of what I'm trying to do
- Create a dynamic form based on the value of $rows.
- Enter the data from the input values into an array.
- Output that data back to the form input fields.

Reason for wanting to do this
So the value of $rows can be changed and the form can be recreated without losing the data already entered into the input fields.

I hope this makes sense and thanks to anyone in advance for any feedback :)

My Code:

<?php
if(isset($_POST['changeRows'])){
$rows = $_POST['rows'];
}else{
$rows = 3;
}
function createForm($rows){
$i = 1;
while ($i <= $rows){
echo 'Firstname: <input type="text" name="firstname[]" value="" /> Lastname <input type="text" name="lastname[]" value="" /><br />';
$i++;
}
}
?>

<form action="" method="POST" autocomplete="off">
<?php createForm($rows);?>
<input type="text" name="rows" value="<?php echo $rows; ?>" size="2" />
<input type="submit" name="changeRows" value="Change Rows" />
<input type="submit" name="goForm" />
</form>

Status_203

8:14 am on Sep 30, 2011 (gmt 0)

10+ Year Member



If I've understood what you want to do then I believe you want something like:

function createForm($rows){
print_r(get_magic_quotes_gpc());
$i = 0;
// Note: example code: no checking for sensible data, hack attempts, magic quotes etc...
$firstNames = array();
if (array_key_exists('firstname', $_POST)) {
$firstNames = $_POST['firstname'];
}
$lastNames = array();
if (array_key_exists('lastname', $_POST)) {
$lastNames = $_POST['lastname'];
}
while ($i < $rows) {
//...and no optimisation.
$firstName = ($i < count($firstNames) ? $firstNames[$i] : '');
$lastName = ($i < count($lastNames) ? $lastNames[$i] : '');
echo 'Firstname: <input type="text" name="firstname[]" value="' . htmlspecialchars($firstName) . '" />';
echo ' ';
echo 'Lastname <input type="text" name="lastname[]" value="' . htmlspecialchars($lastName) . '" /><br />';
$i++;
}
}

For each row this fills in the default value of the field from the relevant data passed in.

incrediBILL

10:25 am on Sep 30, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



A more elegant approach is a general purpose function to iterate the $_POST data without using hard coded fields names that you could use on any input form.

Example:

foreach($_POST as $key=>$value) {
echo "$key: $value\n";
,,, save to array here...
}

Maybe if I get time later I'll flesh out a function to do this, but you get the idea, saving the input values can be a generic reusable function which will save a lot of coding down the road.

varttina

10:52 pm on Oct 18, 2011 (gmt 0)

10+ Year Member



Thanks for the replies!

I've been out of town for the last few weeks and will hopefully pick this project up again soon.

Thanks again :)