Jump to content

Question regarding input values resetting on form submit. Please check my code.


imgrooot
Go to solution Solved by mac_gyver,

Recommended Posts

There are two parts to my question.

 

Part 1.

 

I have a form.  You know when you submit a form and if there is an error, the form will reset the input values unless you have the them "selected"?   Well I have an issue with one of those inputs.

 

Here is the code.  For some reason the input value doesn't get selected on form reset.  It inserts to the database fine.

<fieldset>
	<label>Expiry Date</label>												
	<select name="expiry_date">
		<?php 
		$date				 =	date('Y-m-d H:i:s');
		$expiry_1			 =	date("Y-m-d H:i:s", strtotime("$date + 1 week"));
		$expiry_2			 =	date("Y-m-d H:i:s", strtotime("$date + 2 weeks"));
		?>
		<option value="0">Expires In</option>
		<option value="<?php echo $expiry_1; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_1) { echo 'selected'; } } ?> >1 week</option>
		<option value="<?php echo $expiry_2; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_1) { echo 'selected'; } } ?> >2 weeks</option>
	</select>
</fieldset>

This is another example of select  drop down.  But this one below works fine.

// this select option's input values get selected on form reset.
<fieldset>
	<label>City</label>												
	<select name="city_id">
		<option value="0">Select City</option>
		<?php  
			$get_city = $db->prepare("SELECT city_id, city_name FROM cities WHERE city_id > :city_id");
			$get_city->bindValue(':city_id', 0);
			$get_city->execute();
			$result_city = $get_city->fetchAll(PDO::FETCH_ASSOC);
			if(count($result_city) > 0){
			
				foreach($result_city as $row) {
				
					$get_city_id 	=	intval($row['city_id']); 
					$get_city_name  =	$row['city_name']; 
				
					?><option value="<?php echo $get_city_id; ?>" <?php if(empty($_POST['city_id'])) {} else { if($_POST['city_id'] == $get_city_id) { echo 'selected'; } } ?> ><?php echo $get_city_name; ?></option><?php
				}
			} else {}
		?>
	</select>
</fieldset>

Part 2. 

 

This relates to my previous topic. 

 

I am trying to do the same thing as above, which is show input values on form reset.  But this is slightly more complicated as it is an array.

Looking at the code, you can see that you can add more fields through jquery.  That all works.  Inserting their values from multiple groups of fields into the db also works fine.  But once again, if the form resets or submits, only the 1st group of fields show the selected values in the input fields.  The 2nd or 3rd group of fields generated through the jquery disappear after submit. But again, their values do insert into the db fine.

 

Here's the html and jquery code.

<div id="options-parent">
	<h2>Add Options</h2>
	<button class="add_field_button">Add More Fields</button>
	<div class="options-child-row">
		<div class="option-float">
			<label>Quantity</label>
			<input type="number" name="option_quantity[]" multiple min="1" max="1000000" step="1" value="<?php if(!empty($_POST['option_quantity'])) { echo $_POST['option_quantity'][0]; } else {}; ?>" />
		</div>	
		<div class="option-float">
			<label>Retail Price</label>
			<input type="number" name="option_retail_price[]" multiple min="5" max="1000000" step="1" value="<?php if(!empty($_POST['option_retail_price'])) { echo $_POST['option_retail_price'][0]; } else {}; ?>" />
		</div>		
		<div class="option-float">
			<label>Discount Price</label>
			<input type="number" name="option_discount_price[]" multiple min="1" max="1000000" step="1" value="<?php if(!empty($_POST['option_discount_price'])) { echo $_POST['option_discount_price'][0]; } else {}; ?>" />
		</div>	
	</div>	
</div>

<script>
	$(document).ready(function() {
		var max_fields      = 20; //maximum input boxes allowed
		var wrapper         = $("#options-parent"); //Fields wrapper
		var add_button      = $(".add_field_button"); //Add button ID
	   
		var x = 1; //initlal text box count
		$(add_button).click(function(e){ //on add input button click
			e.preventDefault();
			if(x < max_fields){ //max input box allowed
				x++; //text box increment
				$(wrapper).append(
				'<div class="options-child-row">'+
					'<div class="option-float">'+
						'<label>Quantity</label>'+
						'<input type="number" name="option_quantity[]" min="1" max="1000000" step="10" value="" />'+
					'</div>'+	
					'<div class="option-float">'+
						'<label>Retail Price</label>'+
						'<input type="number" name="option_retail_price[]" min="1" max="1000000" step="10" value="" />'+
					'</div>'+		
					'<div class="option-float">'+
						'<label>Discount Price</label>'+
						'<input type="number" name="option_discount_price[]" min="1" max="1000000" step="10" value="" />'+
					'</div>'+	
				'</div>'
				); //add input box
			}
		});
	   
		$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
			e.preventDefault(); $(this).parent('.options-child-row').remove(); x--;
		})
	});
</script>

What do you think?

Link to comment
Share on other sites

for the part one problem, you are testing the wrong variable in the second <option.... code. you have - if($_POST['expiry_date'] == $expiry_1 for both <options. the second one should be $expiry_2. if you dynamically produce your option lists, from a data definition (usually an array or data stored in a database table), you can avoid errors like this, since the general purpose php code that makes use of the data definition will not make copy/paste errors or typos.

 

for the part two problem, when you display the form, your php code needs to produce enough form fields to hold the data you have on the server-side to to redisplay. initially, with no data to display, output the the single set of form fields you now have, which wouldn't have anything to put into the value='....' attributes, but any time there is existing submitted form data, loop over the data, outputting the set of form fields with the correct data in the value='....' attributes.

 

edit: for the html markup in your jquery code to dynamically add form fields, see the following link for a 'template' method so that you don't have to repeat the markup in your html and in the javascirpt - http://forums.phpfreaks.com/topic/298777-dynamic-for-additions/?hl=%2Btemplate&do=findComment&comment=1524053

Edited by mac_gyver
Link to comment
Share on other sites

for the part one problem, you are testing the wrong variable in the second <option.... code. you have - if($_POST['expiry_date'] == $expiry_1 for both <options. the second one should be $expiry_2. if you dynamically produce your option lists, from a data definition (usually an array or data stored in a database table), you can avoid errors like this, since the general purpose php code that makes use of the data definition will not make copy/paste errors or typos.

 

for the part two problem, when you display the form, your php code needs to produce enough form fields to hold the data you have on the server-side to to redisplay. initially, with no data to display, output the the single set of form fields you now have, which wouldn't have anything to put into the value='....' attributes, but any time there is existing submitted form data, loop over the data, outputting the set of form fields with the correct data in the value='....' attributes.

 

edit: for the html markup in your jquery code to dynamically add form fields, see the following link for a 'template' method so that you don't have to repeat the markup in your html and in the javascirpt - http://forums.phpfreaks.com/topic/298777-dynamic-for-additions/?hl=%2Btemplate&do=findComment&comment=1524053

 

 

1. That was a mistake when I was adding the code in the message. My normal expiry_date has many more fields, so I simplified it to only 2 options. But rest assured, they have correct variables. 

Normally I would get the data list from the db, but in this case I have no other option.  I need to insert an expiry date into the db and this is the best method I found that worked.

 

2. I did follow the instruction on the provided link.  It works..in a sense that I can get a new row of the inputs data by clicking + or delete it with -. Still have the same issue regarding them disappearing after submit. 

 

Just to make it clear, this is the for loop I am using.

for($i = 0; $i < count($_POST['option_title']); $i++) {
						
	if(trim($_POST['option_title'][$i]) != '' && trim($_POST['option_quantity'][$i]) != '' && trim($_POST['option_retail_price'][$i]) != '' && trim($_POST['option_discount_price'][$i]) != '') {
		$insert_options->execute(array(
			$get_item_id,
			$_POST['option_title'][$i],
			$_POST['option_quantity'][$i],
			$_POST['option_retail_price'][$i],
			$_POST['option_discount_price'][$i]
		));
	} 
	
}

Link to comment
Share on other sites

1. That was a mistake when I was adding the code in the message. My normal expiry_date has many more fields, so I simplified it to only 2 options. But rest assured, they have correct variables. 

Normally I would get the data list from the db, but in this case I have no other option.  I need to insert an expiry date into the db and this is the best method I found that worked.

 

 

cannot help with code errors without seeing the code that's in error. however, this is all the more reason to use a data driven design to dynamically produce the output based on a definition, rather than write out all the repetitive lines of code that only differ in the data values they contain. see the following (untested, my contain typos) example -

<select name="expiry_date">
    <?php
    $num_weeks = 10; // define the number of weeks you want in the option list
    // produce the data for the option list
    $expiry_options = array();
    foreach(range(1,$num_weeks) as $week_no){
        $plural = $week_no > 1 ? 's' : '';
        $expiry_options[] = array(date("Y-m-d H:i:s", strtotime("+ $week_no week")),"$week_no Week{$plural}");
    }
    ?>
    <option value="0">Expires In</option>
    <?php
    // output the option list
    foreach($expiry_options as $arr){
        $sel = !empty($_POST['expiry_date']) && $_POST['expiry_date'] == $arr[0] ? 'selected' : '';
        echo "<option value='$arr[0]' $sel>$arr[1]</option>\n";
    }
    ?>
</select>

for repopulating the dynamic form fields, see the following example. the conversion to the template method is up to you. please see the use of the $data array in the code (the raw $_POST data should in general not be altered, and this internal $data array would have any sort of trimming/filtering/validation done on the values in it) - 

<div id="options-parent">
    <h2>Add Options</h2>
    <button class="add_field_button">Add More Fields</button>
    <?php
    // assume that there's a trimmed/filtered/validated copy of any previously submitted post data is in $data
    $data = $_POST; // just make a copy of the $_POST data for this example

    // if $data is empty(), output one set of form fields. there are no value='...' attribute values in this case
    // if $data is not empty(), output a set of form fields, with values, for each set of data

    $count = isset($data['option_quantity']) ? count($data['option_quantity']) : 1; // determine loop count
    for($x = 0; $x < $count; $x++)
    {
        $quantity = isset($data['option_quantity'][$x]) ? $data['option_quantity'][$x] : '';
        $retail_price = isset($data['option_retail_price'][$x]) ? $data['option_retail_price'][$x] : '';
        $discount_price = isset($data['option_discount_price'][$x]) ? $data['option_discount_price'][$x] : '';
    ?>
    <div class="options-child-row">
        <div class="option-float">
            <label>Quantity</label>
            <input type="number" name="option_quantity[]" multiple min="1" max="1000000" step="1" value="<?php echo $quantity; ?>" />
        </div>
        <div class="option-float">
            <label>Retail Price</label>
            <input type="number" name="option_retail_price[]" multiple min="5" max="1000000" step="1" value="<?php echo $retail_price; ?>" />
        </div>
        <div class="option-float">
            <label>Discount Price</label>
            <input type="number" name="option_discount_price[]" multiple min="1" max="1000000" step="1" value="<?php echo $discount_price; ?>" />
        </div>
    </div>
<?php } ?>
</div>

<script>
    $(document).ready(function() {
        var max_fields      = 20 - <?php echo $count - 1; ?>; //maximum input boxes allowed
        var wrapper         = $("#options-parent"); //Fields wrapper
        var add_button      = $(".add_field_button"); //Add button ID

        var x = 1; //initlal text box count
        $(add_button).click(function(e){ //on add input button click
            e.preventDefault();
            if(x < max_fields){ //max input box allowed
                x++; //text box increment
                $(wrapper).append(
                '<div class="options-child-row">'+
                    '<div class="option-float">'+
                        '<label>Quantity</label>'+
                        '<input type="number" name="option_quantity[]" min="1" max="1000000" step="10" value="" />'+
                    '</div>'+
                    '<div class="option-float">'+
                        '<label>Retail Price</label>'+
                        '<input type="number" name="option_retail_price[]" min="1" max="1000000" step="10" value="" />'+
                    '</div>'+
                    '<div class="option-float">'+
                        '<label>Discount Price</label>'+
                        '<input type="number" name="option_discount_price[]" min="1" max="1000000" step="10" value="" />'+
                    '</div>'+
                '</div>'
                ); //add input box
            }
        });

        $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
            e.preventDefault(); $(this).parent('.options-child-row').remove(); x--;
        })
    });
</script>
Link to comment
Share on other sites

here's a tip for the expire week number option menu. you should pass the minimum of data through the form, because you must validate all form data. change the code to submit just he the week number as the value, then using the submitted week number, calculate the actual expire date in the form processing code code.

Link to comment
Share on other sites

here's a tip for the expire week number option menu. you should pass the minimum of data through the form, because you must validate all form data. change the code to submit just he the week number as the value, then using the submitted week number, calculate the actual expire date in the form processing code code.

 

Your options input code works great. That solves that problem.

 

For the expiry date. I should mention that I also have expiry dates listed in hours as well. Like this.

<select name="expiry_date">
	<?php 
	$date				 =	date('Y-m-d H:i:s');
	$expiry_1			 =	date("Y-m-d H:i:s", strtotime("$date + 12 hours"));
	$expiry_2			 =	date("Y-m-d H:i:s", strtotime("$date + 24 hours"));
	$expiry_3			 =	date("Y-m-d H:i:s", strtotime("$date + 1 week"));
	$expiry_4			 =	date("Y-m-d H:i:s", strtotime("$date + 2 weeks"));
	?>
	<option value="0">Expires In</option>
	<option value="<?php echo $expiry_1; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_1) { echo 'selected'; } } ?> >1 week</option>
	<option value="<?php echo $expiry_2; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_2) { echo 'selected'; } } ?> >2 weeks</option>
	<option value="<?php echo $expiry_3; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_3) { echo 'selected'; } } ?> >1 week</option>
	<option value="<?php echo $expiry_4; ?>" <?php if(empty($_POST['expiry_date'])) {} else { if($_POST['expiry_date'] == $expiry_4) { echo 'selected'; } } ?> >2 weeks</option>
</select>
Link to comment
Share on other sites

  • Solution

you can build the $expiry_options array entries with whatever values you want. store the strtotime offsets - '12 hour', '24 hour' (add them manually), '1 week' up to 'n week' (add the weeks dynamically using a loop) in the array. i'm pretty sure that the 's' is optional in the strtotime, so build the values that you need for display purposes, and the strtotime() should work.

 

since the permitted values are now in an array, to validate that the submitted value is one of the permitted ones, before using it in your code, you can just use in_array().

 

see this code -

<select name="expiry_date">
    <?php
    $num_weeks = 10; // define the number of weeks you want in the option list
    // produce the data for the option list
    $expiry_options = array();
    $expiry_options[] = '12 Hours'; // manually add the two hours entries...
    $expiry_options[] = '24 Hours';
    foreach(range(1,$num_weeks) as $week_no){ // add the week entries
        $plural = $week_no > 1 ? 's' : '';
        $expiry_options[] = "$week_no Week{$plural}";
    }
    ?>
    <option value="0">Expires In</option>
    <?php
    // output the option list
    foreach($expiry_options as $arr){
        $sel = !empty($_POST['expiry_date']) && $_POST['expiry_date'] == $arr ? 'selected' : '';
        echo "<option value='$arr' $sel>$arr</option>\n";
    }
    ?>
</select>
Edited by mac_gyver
Link to comment
Share on other sites

 

you can build the $expiry_options array entries with whatever values you want. store the strtotime offsets - '12 hour', '24 hour' (add them manually), '1 week' up to 'n week' (add the weeks dynamically using a loop) in the array. i'm pretty sure that the 's' is optional in the strtotime, so build the values that you need for display purposes, and the strtotime() should work.

 

since the permitted values are now in an array, to validate that the submitted value is one of the permitted ones, before using it in your code, you can just use in_array().

 

see this code -

<select name="expiry_date">
    <?php
    $num_weeks = 10; // define the number of weeks you want in the option list
    // produce the data for the option list
    $expiry_options = array();
    $expiry_options[] = '12 Hours'; // manually add the two hours entries...
    $expiry_options[] = '24 Hours';
    foreach(range(1,$num_weeks) as $week_no){ // add the week entries
        $plural = $week_no > 1 ? 's' : '';
        $expiry_options[] = "$week_no Week{$plural}";
    }
    ?>
    <option value="0">Expires In</option>
    <?php
    // output the option list
    foreach($expiry_options as $arr){
        $sel = !empty($_POST['expiry_date']) && $_POST['expiry_date'] == $arr ? 'selected' : '';
        echo "<option value='$arr' $sel>$arr</option>\n";
    }
    ?>
</select>

 

That's great. It works. 

 

One last thing.  How would you add my original date string into your new option value?  I tried it like this and it gives me error like this.

Parse error: syntax error, unexpected '$expiry_n' (T_VARIABLE), expecting identifier (T_STRING)
foreach($expiry_options as $arr){
	$sel = !empty($_POST['expiry_date']) && $_POST['expiry_date'] == $arr ? 'selected' : '';\
	
	$date				 =	date('Y-m-d H:i:s');
	$expiry_n			 =	date("Y-m-d H:i:s", strtotime("$date + $arr"));
	
	?><option value="<?php echo $expiry_n; ?>" <?php echo $sel; ?>><?php echo $arr; ?></option><?php 
	
}
Edited by imgrooot
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.