Variable as default value in form dropdown? - php

I have a parser which extracts information into array $item. From my database, I am pulling all results where I store "Types" into array $getFormats.
I am then displaying $item into a big form which the user can modify (to fix any errors from the parser). In partiular, I am forcusing on $item[3] which contains "types" extracted by the parser.
My form displays $item[3] next to my dropdown list containing possible "types" contained in the database. The goal here is to allow the user to match or change the "type" the parser finds with a "type" contained in the database.
Obviously, I want the default dropdown value to be a value which matches one already in the database. If there is no match, then the default would be blank for the user to choose an appropriate type himself.
The code below demonstrates what I have. Obviously, I am going about it wrong as it doesn't work.
<form>
<?php
foreach($articles as $item) {
?>
Type: <input type="text" name="typeparsed" value="<?php echo $item[3]; ?>">
<select name="typechoose" value="<?php echo $value; ?>">
<?php
foreach ($getFormats as $format) {
$selected = '';
if($item[3] == 'entry form' && $format->name == 'Entry Form'){
$selected = 'selected';
}
echo "<option value='".$format->name."' ".$selected.">".$format->name."</option>";
}
?>
</select>
<?php }?>
</form>
$item[3] is the array containing "type" extracted by the parser.
$format->name is the array containing the dropdown options pulled from the database.
The above code works but my problem is that $format->name contains two instances of the same value.
My database has the following "types":
Entry Form
Facebook
Entry Form
This is because of the way wordpress stores hierarchical options. On my site, these values are actually as follows:
Entry Form
Facebook
- Entry Form
As you can see, it is because Entry Form is a top menu item AND a submenu of Facebook.
So, as I am trying to match a type of entry form with Entry Form, I run into a problem when trying to determine WHICH Entry Form is the right one to select.
As my code is presently, the second instance of Entry Form is selected.
How can I adapt the code so that if $item[3] == 'entry form' (as it is currently), then the FIRST Entry Form will be selected?

First thing is I don't understend why You use this:
<?php
foreach($articles as $item) {
if ($item[3] == 'entry form') {
$value = 'entry form';
} else {
$value = $item[3];
}
?>
You can simply use the code brlowe and it will do exacly the same:
<?php
foreach($articles as $item) {
$value = $item[3];
?>
To match selected element do that:
Type: <input type="text" name="typeparsed" value="<?php echo $item[3]; ?>">
<select name="typechoose" value="<?php echo $value; ?>">
<?php
foreach ($getFormats as $format) {
$selected = '';
if($value == $format->name){ $selected = ' selected="selected" '; }
echo "<option value='".$format->name."' ."$selected".>".$format->name."</option>";
}
?>
</select>
<?php }?>

Becous You have change Your question I will put another answer witch is simple: You will not determine that as long as both "Entry Form's" have the same name. If You can check them for they database ID's please try to use it, if not then You should change their names.
<?php // $value is actualy ID of the element; ?>
Type: <input type="text" name="typeparsed" value="<?php echo $item[3]; ?>">
<select name="typechoose" value="<?php echo $value; ?>">
<?php
foreach ($getFormats as $format) {
$selected = '';
if($value == $format->id){ $selected = ' selected="selected" '; }
echo "<option value='".$format->id."' ."$selected".>".$format->name."</option>";
}
?>
</select>
And as value pass ID of the selected element.

Related

HTML PHP: Why do two identical select elements produce different HTML displays?

Could someone kindly help out with this rather basic issue: In a simple HTML form (functionally all good) two select elements are included.
Code:
<select id="dept" name="dept" required>
<?php
foreach($stddept as $item0) {
echo "<option value='$item0'";
if ($_POST['dept'] == $item0) echo 'selected="selected"';
echo ">$item0</option>";
}
?>
</select>
<br><br>
<select id="lev" name="lev" required>
<?php
foreach($stdlev as $item1) {
echo "<option value='$item1'";
if ($_POST['lev'] == $item1) echo selected="selected"';
echo ">$item1</option>";
}
?>
</select>
<input type='submit' id='submituser' name='submituser' value='Submit'>`
These two drop-down boxes behave differently in that only the second one honours the 'required' attribute. The first one can be submitted blank, which is obviously not right.
They also appear differently (see image) in that the first displays the first option in the list (from MySQL DB) but the second displays a blank. I have checked everything I could to see what else could cause the difference - without any joy.
Does anyone know what I am missing here? Thank you.
You can do this using jquery/javascript by getting the id of the first selected value and then select the result for the second box based on that id.
I think the problem with the code ( as it is shown ) is that you are incorrectly echoing the option in the second dropdown - it is missing quotes. You can streamline the code somewhat like this:
<select id="dept" name="dept" required='required'>
<?php
foreach($stddept as $item0){
$selected=$_POST['dept'] == $item0 ? " selected='selected'" : "";
echo "<option value='$item0'{$selected}>";
}
?>
</select>
<br /><br />
<select id="lev" name="lev" required='required'>
<?php
foreach($stdlev as $item1){
$selected=$_POST['lev'] == $item1 ? " selected='selected'" : "";
echo "<option value='$item1'{$selected}>";
}
?>
</select>
<input type='submit' id='submituser' name='submituser' value='Submit'>

Select list array - prepopulate the choice to the top of the array

I am printing a simple select list out by looping through an associative array which is populated elsewhere.
<select id="choice" name="choice">
<?php
foreach ($this->choice as $key => $value) {
echo "<option name=".$value." value=".$key.">" .$value. "</option>" ;
}
?>
</select>
This select list gives the options available from the array. However, I am trying to pre-populate the list with the selected value, for example if a user is updating their user information, then I would like to set that choice at the top of the list (ideally without the choice appearing further down the list).
I have access to this data in a variable which I have queried:
$this->selected_choice //value
$this->selected_id //key
Now I have been testing some solutions
<select id="choice" name="choice">
<option name="<?php echo $this->selected_choice; ?>" value="<?php echo $this->selected_id;?>">"<?php echo $this->selected_choice; ?></option>
<?php
foreach ($this->choice as $key => $value) {
echo "<option name=".$value." value=".$key.">" .$value. "</option>" ;
}
?>
</select>
This solution does display the users choice on top of the list, but the foreach loop will also display this option as there is no indication that it shouldn't.
This is my question to you guys, how can I do this so the the selected_choice appears at the top of the list, but will then not appear in the foreach array.
I am hoping there is some simple solution to this problem, as it is not so important, but something I come across quite a lot.
Option have no "name". Name is attribute for SELECT tag.
If option is selected, you need to pass "selected" attribute in body of option
Ex: <option value="1" selected>Tramtada</option>
Do it this way:
<select id="choice" name="choice">
<?php
foreach ($this->choice as $key => $value) {
echo "<option <?php if($key == $this->selected_id) {?> selected <?php } ?> value=".$key.">" .$value. "</option>" ;
}
?>
</select>

Updating MySql DB with Dropdown values

My update statement isn't working correctly, I am attempting to pull the data from the database, populate a dropdown with either "Y" or "N" inside it, on submit the values are entered into the database and the page refreshes.
So far I have my list of items, each with correctly populated dropdown, it is now my submit that is failing to work.
<?php
$updatedFeatProd = $_POST['featuredProduct'];
var_dump($updatedFeatProd);
if ($_POST) {
foreach ($_POST['featuredProduct'] as $key => $val) {
$query = 'UPDATE tblProducts SET featuredProduct = ' . $updatedFeatProd . '
WHERE fldID = ' . $val;
$sql = dbQuery($query);
}
}
$sql = dbQuery('SELECT fldId, fldName, featuredProduct FROM tblProducts');
?>
<form method="post" action="#" name="featuredProd">
<table>
<tr><td><p>Product Name</p></td><td><p>Is a featured product?</p></td></tr>
<?php
$products = dbFetchAll($sql);
foreach ($products as $product) {
//var_dump($product['fldName']);
?>
<tr>
<td>
<p><?php echo $product['fldName']; ?></p>
</td>
<td>
<select name="featuredDropdown">;
<?php
if ($product['featuredProduct'] == 'Y') {
?>
<option value="<?php $product['fldId'] ?>"><?php echo $product['featuredProduct'] ?></option>
<option value="<?php $product['fldId'] ?>">N</option>
<?php
} else {
?>
<option value="<?php $product['fldId'] ?>"><?php echo $product['featuredProduct'] ?></option>
<option value="<?php $product['fldId'] ?>">Y</option>
<?php
}
?>
</select>
</td>
</tr>
<?php
}
?>
The presentaton here does not make much sence. You have a dropdown with the ProductName in one slot and a 'N' in another.
Once the user has selected 'N' for a product they have no idea what they have said NO to, as they can no longer see the product name that they have selected NO for.
It would make more sence to provide a <label> containing the product name and a YES/NO dropdown beside it for them to select from.
However the reason your update code is not working is that you have called the dropdown featuredDropdown
<Select name="featuredDropdown">
and you are trying to process a field called featuredProduct in the update code
foreach ($_POST['featuredProduct'] as $key => $val) {
Your next problem will probably be that you are oututting more than one <Select name="featuredDropdown"> so you need to make that into an array as well like this:
<Select name="featuredDropdown[]">
Then you will have an array of featuredDropdown in the $_POST array. $_POST['featuredDropdown'][]

Codeigniter, problems using set_select() and set_checked()

I have a bit of an issue using codeigniter's set_select and set_checked within my forms, I am adding these to my existing forms as I am the stage in development where I am trying to tidy things up and failed validation resetting forms was not a big issue when I was still working on the project but now its coming to a close its become a major headache.
Firstly the set_select, I have this code which outputs me drop down from an array which is passed to the view from the controller which gets the results from a table in my database, the form I am implementing this in has 10 drop down boxes each corresponds to a table in my database. Anyway this is the code:
<label for="rating">Rating: </label>
<select name="rating">
<?php
if(isset($rating) && $rating != 'none') {
echo '<option value="" '.set_select('rating', '', TRUE).'></option>';
foreach($rating as $row) {
echo '<option value="'.$row->door_rating_rating.set_select('rating', $row->door_rating_rating).'">'.$row->door_rating_rating.'</option>';
}
} else {
echo '<option value="none">Nothing to list</option>';
}
?>
</select>
It is just not working and as far as I can see there shouldn't be a problem with my code but this is the first time I have used this and I have looked at examples of using it but could not find an example of using it in a for loop so is what I am doing even possible?
This is my set_checked code within the view and this too is not working after failed validation:
Temporary Refuge Door?<input type="checkbox" class="temp_ref" name="tempref" value="1" <?php echo set_checkbox('tempref', '1'); ?> />
Any help with either of these would be really appreciated.
Looks like you had the set_select within the quotes for the option value. I moved it after it. I have also made an edit to use printf for better readability.
<label for="rating">Rating: </label>
<select name="rating">
<?php
if(isset($rating) && $rating != 'none') {
echo '<option value="" '.set_select('rating', '', TRUE).'></option>';
foreach($rating as $row) {
printf('<option value="%s" %s>%s</option>', $row->door_rating_rating, set_select('rating', $row->door_rating_rating), $row->door_rating_rating);
}
} else {
echo '<option value="none">Nothing to list</option>';
}
?>
</select>
To solve set_select() try the following. Assuming you have an array named $isps which contains id and name field.
<select id="isp" name="isp">
<option value="" selected>Select a ISP</option>
<?php foreach ($isps as $row) { ?>
<option value="<?php echo $row->id ; ?>" <?php echo set_select('isp', $row->id, False); ?> ><?php echo $row->name ; ?> </option>
<?php } ?>
</select>

do not show duplicate values in my drop down box

I need some help with my logic here. I am populating a value from the database in my select box.
If it exists, I echo the value else i display the default options.
Now, for example if the value from the database is New Jersey, I do not want to display New Jersey for the second time in my drop down box. How do I do that?
<select name="location" class="field" >
<option value="<?php if(!empty($get_location)){ echo $get_location; } ?>"><?php if(!empty($get_location)){ echo $get_location; }?></option>
<option value="New Jersey">New Jersey</option>
<option value="New York">New York</option>
<option value="California">California</option>
</select>
You make an if statement in every option field and check if the value from the database matches the value of the option field and if it does so you echo "selected=\"true\"" to the option field.
For a code example see my answer for this question:
retieve data from mysql and display in form
If you only want your database values to be shown:
<?php
// You populate an array with the locations from your database
// As an example:
$options = array(1=>'New Jersey',2=>'Los Angeles');
$html = '<select name="locations">';
foreach($options as $id => $option)
{
$html .= '<option id="'.$id.'">'.$option.'</option>';
}
echo $html.'</select>';
?>
If you want something special to happen to your database values, but still load the default values too:
<?php
// You populate an array with the locations from your database
// As an example:
$options = array(1=>'New Jersey',2=>'Los Angeles');
// Compare against your full list of locations
// As an example:
$locations = array(1=>'New Jersey',2=>'Los Angeles',3=>'California',4=>'London');
$html = '<select name="locations">';
foreach($options as $id => $option)
{
if(array_key_exists($id,$locations))
{
// Enter your magic
}
}
echo $html.'</select>';
?>
I would change your php code slightly to add defaults and then you can filter and remove duplicates with jQuery. If there are lots of options this might not be the best solution tho...
php
<select name="location" class="field">
<?php if(!empty($get_location)): ?>
<option value="<?php echo $get_location; ?>">
<?php echo $get_location; ?>
</option>
<?php else: ?>
// Defaults
<?php endif; ?>
</select>
jQuery
var removeDup = function($select){
var val = '';
$select.find('option').each(function(){
if ($(this).val() === val) { $(this).remove(); }
val = $(this).text();
});
};
removeDup($('#yourSelect'));
Get your locations in one request to the database, add them to an array together with the defaults, if only one location do as below, if several locations parse them into an array and merge them with the defaults, do an array_unique to get rid of duplicates and output the array in a loop.
<select name="location" class="field">
<?php
$output = array(1=>'New Jersey', 2=>'New York', 3=>'California', 4=>$get_location);
$options = array_unique($output);
foreach($options as $key => $value) {
echo '<option value="'.$value.'">'.$value.'</option>';
}
?>
</select>

Categories