I'm bug-proofing a form that allows data editing for book entries in a database. Everything is working except for the drop-down box. The drop-down box automatically populates itself with every unique entry in a specific field in the database table, and that part works perfectly. However, when people click to edit a book all the fields are populated with that books information, and I wanted the drop-down box to default to the correct value for that book. My solution was to check each value as it populates the drop-down box against the actual book's value for that field and if they match, make it the "selected" value.
It is not working. The box is still populating fine, but it is not defaulting. Here is the code for the drop-down box.
<span style="margin-left:10px;">
Publication Type:
<select name="publicationType" >
<option value=""></option>
<option value="">-------------------------</option>
<?php
$lPub = '';
if(array_key_exists('publicationType',$_REQUEST)) $lPub = $_REQUEST['publicationType'];
$lPubArr = $datasetManager->getPublicationType();
foreach($lPubArr as $pubStr){
if($pubStr == $bookArr['publicationType']){
echo '<option '.($lPub==$pubStr?'selected="selected"':'').'>'.$pubStr.'</option>'."\n";
}
else{
echo '<option '.($lPub==$pubStr?'':'').'>'.$pubStr.'</option>'."\n";
}
}
?>
</select>
</span>
I can provide what all the variables are if needed. I don't see what I'm doing wrong, but maybe someone will be able to catch an obvious mistake.
Thank you,
Kai
Not sure this will help but try this:
<?php
$lPub = '';
if( array_key_exists('publicationType',$_REQUEST) )
$lPub = $_REQUEST['publicationType'];
$lPubArr = $datasetManager->getPublicationType();
foreach($lPubArr as $pubStr){
echo '<option '.($lPub==$pubStr?'selected="selected"':'').'>'.$pubStr.'</option>'."\n";
}
I removed this condition:
f($pubStr == $bookArr['publicationType'])
since I didn't get what the $bookArr['publicationType'] is used for, perhaps you left it there by mistake
Related
dropmenu is <select name="dropbox"> with 3 options - admin, activate, delete. The below snippet of code shows if the activate <option> is selected and submitted by the submit button then echo etc. I have a <select name="dropbox"> on every row for each user. My code only works if i change the last drop box.
if(isset($_POST['submit']))
{
if(isset($_POST['dropmenu']) && $_POST['dropmenu'] == 'activate')
{
echo 'is activated';
}
else{
echo 'fail';
}
}
Is there a way i can use foreach drop box with a value selected?
One of the possible ways is to connect the name of the select element with user id like
<select name="dropbox_[userId]">
In this case you simply know how to build an input name for checking it's value in $_POST table.
If you don't interate by users on submit code then you can use a regular expression to get an inforamtion abut user connected with element.
I am working on an existing wordpress website.
Users has field "user-country" (actually, I do not know how this field is created in wordpress, but it works).
In the registration form, user can choose one specific country.
However, now this country list is note defined "anywhere". It is created explicitly in the code:
<option value="Afghanistan" <?php if($current_user->user_country == 'Afghanistan') echo 'selected';?>>Afghanistan</option>
<option value="Albania" <?php if($current_user->user_country == 'Albania') echo 'selected';?>>Albania</option>
<option value="Algeria" <?php if($current_user->user_country == 'Algeria') echo 'selected';?>>Algeria</option>
<option value="American Samoa" <?php if($current_user->user_country == 'American Samoa') echo 'selected';?>>American Samoa</opt
etc.
The client wants to changed this list (from country to city). So i need to add other values. I do not want to write all values in the code. I would like to create some list with these values in wp-admin.
What is the best way to create a predefined values list? And these are not custom fields for posts.
EDIT:
I want to store values in DB, so admin can modidfy these values from wp-admin.
Actually, it is not so important whether it is DB or other option like XML.
I just want this list to appear as dropdown when user is registering and also to wp-admin to modify values of this list.
Also, a question come to my mind - is it a normal practice to store user custom fields like country or city in DB? Or maybe it is ok to define them in code explicitly?
Well, if you want the administrator to be able to modify the list, then DB is likely the best option here.
I would do something like this (in WordPress):
// put a default (initial) list in the database, if there isn't one there yet
if(!get_option('my_country_list')){
// store it as a |-delimited string, because WP serializes arrays,
// and this would be too much here
$data = 'Albania|Algeria|Disneyland|etc';
update_option('my_country_list', $data);
}
Now, later where you need that list, simply get it from the db:
$countries = get_option('my_country_list');
// turn it into an array
$countries = implode('|', $countries);
// generate the select field
$html = '';
foreach($countries as $country){
$checked = '';
if($current_user->user_country == $country)
$checked = 'selected="selected"';
$html .= sprintf('<option value="%1$s" %2$s> %1$s </option>', $country, $checked);
}
printf('<select> %s </select>', $html);
I guess you'll also have some kind of administration form for the options, where the administrator can modify entries from this list. This could be a textarea. When it gets submitted you update_option() again (replace new lines with |)
I have a form. The first field is a drop down select option. The user will select the name of a company. Based on the name a second drop down select option needs to be generated showing the addresses of all the company's branches.
The company data is stored in a mysql database.
How can I make the above happen?
If you are saying about <select> tag, the you can use this.
<select name="option">
<option value="one"<?php echo ($data["option"] == "one") ? ' selected="selected"' : ""; ?>>One</option>
<option value="two"<?php echo ($data["option"] == "two") ? ' selected="selected"' : ""; ?>>Two</option>
<option value="three"<?php echo ($data["option"] == "three") ? ' selected="selected"' : ""; ?>>Three</option>
</select>
For the sub select, see this demo: http://jsfiddle.net/ah4rx/
You have two options here
post the form on change of first dropdown and fetch the data based on posted value and display.
use ajax functionality to fetch the data based on value selected in dropdown and display
As basic as it gets - Send the company name via ajax to php, query the database to get the address, populate the next drop down in the same php script whilst in the loop and echo out. Receive back in ajax
I would use that code for the first generation of the first list. Then the second list would have to be done with AJAX (JQUERY can help you here).
You want JQUERY to get
var client=$('#client_name').find("option:selected");
Then make a normal AJAX request.
I would recomend you to use a PDO to connect to your databse instead of using that generic connection.
Based on the code that you posted in the reply to Vamsi then the code would be
<label>Client Name</label><br>
<select id="client_name">
<?php
// PDO connect to the DB
$db = new PDO ('mysql:host=localhost;dbname=DB_NAME','DB_USER','DB_PASS');
$sql = 'SELECT name FROM client'
$result = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
if(count($results)>0){ echo "<option></option>";}
foreach( $result as $key => $val)
{
// could also be $val['name'] depending on your db
echo "<option>".$key['name']."</option>";
}
?>
<select>
I am not exactly how to do it and how to word the question, so i shall try my best (PS: i'm new to web dev, so please be clear in your answers if you could).
So, I have got a drop down menu with the list names, which are taken from my database. In that database i have a table with names column (the ones that are rendered to the dropdown box) and relevant information to those names. Now, I want that relevant information to appear below in a tag when a user choose one of those names. I also cannot use the form.submit() method because my submit button is already taken for something else.
Here is the code to that bit:
<form name="name_choice" method="post" action="index.php">
<select name="names" onchange="form.some_method()">
<option value="NULL" selected="selected">--Select name--</option>
<?php
for ( $i = 0; $i < $numrows; $i++ ) { //for all the columns, iterate and print out
$id_names = mysql_result($result, $i);
echo "<option value='".$id_names."'>".$id_names."</option>";
}
?>
</select>
</form>
So the bit above works fine, but the "some_method()" is my problem, i don't know what to trigger to display the text in the div below the drop down box (code is below for it):
<div class="information"> <!--if the name is chosen ONLY!-->
<?php
if($_POST['names'] == "NULL") {
echo '<p>Please select an option from the select box.</p>'; //this bit is for testing
}
else {
echo '<p>You have selected: <strong>', $_POST['names'], '</strong>.</p>';
//and then how to echo the relevant information?:(
}
?>
</div><!--end of possible info-->
onchange is a JavaScript event. PHP can't do realtime processing of form data, as it sits on the server and the form is on the client. You can sort of do it by using AJAX and passing the form data as the user types, but that would be a lot more work than is needed. Take a look at JavaScript form validation posts to get yourself headed on the correct path.
I wrote some PHP code that will allow me to create an html dropdown box, and then choose what should be the selected value. The code is:
$role_drop = "<select name='role'>";
$role_drop .= "\r\n<option value='Resident Assistant'>Resident Assistant</option>";
$role_drop .= "\r\n<option value='Community Assistant'>Community Assistant</option>";
$role_drop .= "\r\n<option value='Head RA'>Head RA</option>";
$role_drop .= "\r\n</select>";
$result = mysql_query("SELECT role FROM users");
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$role = $r["role"];
$role_drop = str_replace(">$role</option>", "selected=\"\" >$role</option>",$role_drop);
echo $role_drop;
}
}
In reality, this code has a bunch of HTML mixed in, but here is all of the PHP. When I run it, it seems to work. However, let's say the query returned 4 dropdown boxes with roles (from 4 users), and I were to Edit, or select, a new role for the 2nd dropdown box returned (with an UPDATE query), then when the page refreshes, all of the roles including and AFTER the dropdown box I updated will display their selected values as the new one I selected in the 2nd dropdown box.
And it's not that the values in the actual database are wrong, they are just displaying the wrong selected value. Here is the source code for the 3rd dropdown box after I select a new value for the second one:
<select name="role">
<option selected="" value="Resident Assistant">Resident Assistant</option>
<option value="Community Assistant">Community Assistant</option>
<option selected="" value="Head RA">Head RA</option>
</select>
So, it seems its selecting the correct value (Resident Assistant), however its ALSO selecting "Head RA", which is what I changed the prior dropdown box to.
It's very strange, and I have NO idea why this is happening. Any ideas?
Thanks!
It's because you're updating $role_drop each time, so all the previous changes are going to show up in subsequent dropdowns. I'd change the loop to something like this:
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$role = $r["role"];
$temp_role_drop = str_replace(">$role</option>", "selected=\"\">$role</option>", $role_drop);
echo $temp_role_drop;
}
}
That way you're not overwriting your original dropdown markup.
Nuts - forgot to escape my code. I meant, "It's just <OPTION VALUE="foo" SELECTED>".
Dunno if this helps, but according to the HTML spec you shouldn't be passing a value along with the SELECTED attribute of each OPTION. It's just .