Jump to content

Maintaining value in dynamically created select list


Alcain

Recommended Posts

<select name="bugReport">
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'txt') {
echo "<option value={$file}>".basename($file)."</option>";
echo "<br />";
}
}
// close directory
closedir($handle);
} ?>
</select>

Alright so I am fairly new at PhP programming and I'm trying to figure out how to maintain my selection after submitting the form. The thought process here is to create a select list that is dynamically created. It will read through my current directory, and exclude all files not ending in txt. It will assign the value of the file to the option, so if the user chooses an option and hits submit, the file's contents will show.

 

My problem is that when I choose a text file to show and hit submit, the contents of the file show correctly (code isn't provided for this part as it's not the issue), but the select option returns to the default. I want the select list to maintain the option that the user chose after the form is submitted. I've been browsing forums and messing around myself but just cannot figure this issue out.

Link to comment
Share on other sites

You haven't marked any of the select options as 'selected'. When you submit the form, its data is being stored somewhere, probably in a superglobal ($_GET or $_POST). When you're building up your select list, you'll want to compare the current item in the list against the value from the last time the form was submitted.

 

 

<select name="bugReport">
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'txt') {
echo "<option value={$file}>".basename($file)."</option>";
echo "<br />";
}
}
// close directory
closedir($handle);
} ?>
</select>

 

As an aside, you probably want to break this out into a function and separate the reading of the files from the creation of the select list as those are two different concerns.

Link to comment
Share on other sites

First off: Storing data in files is rarely a good idea, especially when you're new to PHP. It's very cumbersome and often introduces severe security vulnerabilities. For example, how do you make sure users cannot manipulate the file path and read arbitrary files from your server? The smarter approach is an actual database system. Chances are you already have one installed on your server (e. g. MySQL).

 

How to maintain the selection depends on where the form data is sent. If it's sent to the same page, then the selection is available in $_GET (assuming you used the GET method). When you build the options, simply compare the current file with the selection and preselect it if they match. If the data is sent to a different page, you'll need a cookie or a session to save the data.

Link to comment
Share on other sites

I probably should have specified more. This is not something that will be implemented for a business or personal use, it's for an assignment that I'm currently stumped on. I fully understand that we don't want users to manipulate data. So for the purposes of this assignment:

 

1. User enters data into a form (done)

2. That data is saved into a text file (done)

3. Another page allows the user to edit the text files that are in the current directory

 

How I went about accomplishing this is there is a dropbox with the all the text files in the directory. The user chooses which file they want to edit, and a text area is then created and populated with the information from the text file. The user then can edit the information they want, and click a button to "submit" their edit. My problem that I can't quite get my head around is keeping the value of the select list for when they edit the text file. I realize this is not a practical or professional way to go about solving it, but like I said I am a beginner and this is how I thought about doing it.

 

 

This is the entire code for the page, the problem comes when the text area is populated with the information from the file. I edit whatever I want to edit, and hit the "edit report" button. Even though I have a different file open, it will take the value of the current option in the select list which upon the first submit defaults back to the top selection. So even if I choose to edit say the 4th file, when I hit edit report, it saves it to the 1st file.

<article>
 <h2>Software Bug Reports</h2>
	<h3 id="title">Edit Report</h3>
	<form action="?" method="post">
         <fieldset id="bugReports">
		Select the bug report you would like to edit: <br />
		<select name="bugReport">
		<?php
		// creating a dropbox for user to choose which report they wish to edit
		// read all entries in current directory
		if ($handle = opendir('.')) {
			// loop through all the files
			while (false !== ($file = readdir($handle))) {
				// strip everything that doesn't end in txt
				if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'txt') {
					// create options in the dropbox with a value of the file the user chose
					echo "<option value={$file}>".basename($file)."</option>";
					echo "<br />";
				}
			}
			// close directory
		closedir($handle);
		}		?>
		</select>
	<br /> <br />
	
		</fieldset>	
		<fieldset id="submitbutton">
			<input type="submit" id="submitBtn" name="submit" value="Edit report" />
		</fieldset>
		<br /><br />
		<?php
			// if user chooses a report and clicks "edit report"
			if (isset($_POST['submit'])) {
				// create variable for requesting the file from the drop box
				$report = $_POST['bugReport'];
				// create variable to retrieve all contents from the file chosen by the dropbox
				$print = file_get_contents($report);
				// create a text area and print all the information from the file into it
				echo "<textarea id='updateText' name='updateText' rows='7' cols='60'>{$print}</textarea>";
				// create a new update file button for editting 
				echo "<input type='submit' name='updateFile' value='Update File'>";
			}
			
			
			// if the user clicks on "update file"
			if (isset($_POST['updateFile'])) {
				// retrieve the file the user chose to edit
				$report = $_POST['bugReport'];
				// opens the file
				$newFile = fopen($report, "w+") or die("Unable to open file!");
				// retrieves the updated text from the textarea
				$newText = $_REQUEST['updateText'];
				// prints the newly updated text from the textarea into the file
				fwrite($newFile, $newText . "\r\n");
				echo "{$report} updated!";
			}

		?>
	</form>
</article>

Link to comment
Share on other sites

OK, here is what I would suggest.

 

Create a function that takes two parameters

function createOptions($options, $selectedValue=false)

$options will be an array of items for the select list where the index is the value and the value is the label. E.g.

$cars = array(
0 => 'Select One',
1 => 'Honda',
2 => 'Ford',
3 => 'Chevy',
4 => 'Dodge',
5 => 'Toyota'
);

The selected value parameter is optional. First, create an output variable for the function that will hold the HTML content of the options. Then, in that function and iterate through the array using a foreach() function.

foreach($options as $value => $label)

Then test the $value to see if it is equal to $selectedValue. If yes, set a variable ($selected) as the string ' selected', else set it to an empty string. Then append the HTML contents for the current option to the output variable using the $selected variable inside the opening option tag. Once all items have been processed return the output variable.

 

Now you can use the function to generate any of your select lists (with or without a 'sticky' value)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.