Hi I am the beginner of Codeigniter. The following is my code. The issue is, it does not display the default value in select opinion menu. Please assist, Thank you.
<select name="taskOption1" class="form-control">
<option value="" disabled selected> -- select an option -- </option>
<?php
foreach($stagesData as $key => $value):
echo '<option value="'. $value -> stage_id . '"' .
set_select('taskOption1', $rows[0] -> stage_reject_id) . '>' . $value -> stage_name . '</option>';
endforeach;
?>
</select>
<select name="taskOption2" class="form-control">
<option value="" disabled selected> -- select an option -- </option>
<?php
foreach($rejectsData as $key => $value):
echo '<option value="'. $value -> reject_id . '"' .
set_select('taskOption2', $rows[0] -> stage_reject_id, ((($value -> reject_id) == ($rows[0] -> reject_id))?true:false)) . '>' . $value -> reject_name . '</option>';
endforeach;
?>
</select>
First of all, if you have a default option, I guess that should be the one selected? If so, you don't need <option value="" disabled selected> -- select an option -- </option>. But I may have understood this the wrong way.
Second, if you want to set a default value with set_select() in CodeIgniter, you must use the third parameter, like this:
set_select('taskOption1', $rows[0] -> stage_reject_id, TRUE)
You are using Form Helper, I see, so why don't you use from_dropdown or for multiple use form_multiselect
form_dropdown([$name = '', $options, $selected, $extra)
Parameters:
$name (string) – Field name
$options (array) – An associative array of options to be listed
$selected (string) – Selected Value
$extra (mixed) – Extra attributes
For your code
<?php $stagesData = ['' => '--select--'] + $stagesData; ?>
<?php echo form_dropdown('taskOption1', $stagesData, ''); ?>
Related
I have recursion function which populates data on my select drop down.
How can I pass a value that, if it matches with any value on drop down, gets selected?
this is function on my model:
function get_all_cat($parent,$level=0,$s){
$ui = '';
$this->db->order_by($this->id, $this->order);
$this->db->where('parent',$parent);
$query=$this->db->get($this->table)->result();
foreach ($query as $qu) {
if($s==$qu->id){
$y = 'selected';
}
$repeat = str_repeat('--', $level);
$ui .= '<option value="'. $qu->id .'" '.$y.' >' .$repeat. $qu->title.'</option>';
$new_level = $level+1;
$ui .= '' .$this->get_all_cat($qu->id,$new_level) .'';
}
return $ui;
}
and here is my select option in the view:
<div class="form-group">
<select name="category" class="form-control chosen-select">
<option value="">Any Category</option>
<?php
$cat = $this->Dbc_categories_model->get_all_cat(0,0,$this-session->userdata('clicked_id');
echo $cat;
?>
</select>
</div>
few notes that I pick up...
1.) Don't ever use variable names like $s => easy to lost track and that name doesn't tell you what variable contain or do
2.) You're not passing selected value to reclusive function (missing third parameter)
Otherwise looks like this are working code.
I have a form consisting of 11 elements (input and select tags). The form has form validation that prompts an error message next to field when a user inputs incorrect data. I want to maintain the correct data entered into the fields after the page is refreshed.
For instance, let's say that 10 fields where populated correctly and 1 field incorrectly. When the user presses the submit button, an error message is shown near the field. What I want to do is to keep the 10 correct values selected so the user does no have to start all over again.
For the input elements, this is working fine but for the select elements this is not working. Important is that I am populating the drop down list dynamically with PHP.
Is this possible to do in PHP since I cannot figure out how?
Below is an example of how I am generating a drop down list of a select element.
select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
echo '<option value="' . htmlspecialchars($row['description']) . '">'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
</select>
As for the input elements I am achieving this using the below:
<input type="text" name="serial" value="<?php echo $serial;?>">
Try this:
<select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
$selected = "";
if ($row['description'] == $location) {
$selected = " selected";
}
echo '<option value="' . htmlspecialchars($row['description']) . '"' . $selected . '>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
</select>
As outlined in the as duplicate linked question the selected attribute is to mark the option that has been submitted. The selected attribute addresses the issue to make the selected value visible.
Additionally your code can benefit from data-binding the select element to the (SQL) data in a modular way.
Let us not care for a moment on the retrieval of the data and just say they come from a Generator:
/**
* #param string $name of the select field
* #param string $value of the select field
* #param Generator $data to use as select field option values
* #return string HTML of the select element
*/
function select($name, $value, Generator $data) {
$buffer = sprintf('<select name="%s">', htmlspecialchars($name));
foreach ($data as $option) {
$buffer .= sprintf(
'<option%s>%s</option>',
$value === $option ? ' selected' : '',
htmlspecialchars($option)
);
}
$buffer .= "</select>\n";
return $buffer;
}
This little function returns the HMTL of a select element with the data from a Generator selecting an existing value (if part of the options).
Combining it with any generator, for example from a data-source, it can be easily put into your forms template script:
<form method="post">
<?= select('location', $_POST['location'] ?? 'default value',
datasource($connection, "SELECT description FROM location ORDER BY description ASC", "description")
) ?>
</form>
So if you've got 10 selects, this can be easily adopted. As the database connection as you know it is passed to the datasource function, it would be interesting to see what that function actually does. That function is even more simple:
/**
* #param mysqli $mysqli
* #param string $query
* #param string $field from query result to use as option values
* #return Generator
*/
function datasource(mysqli $mysqli, $query, $field) {
$result = $mysqli->query($query);
if ($result) foreach ($result as $row) {
yield $row[$field];
}
}
It queries the query on the database connection (it's a different way of writing as in your code, but it's the same $connection as in your example) and then iterates over the result (if there is a result). Then yielding each option value. That yield is a special form of returning from a function creating a Generator which is used in the select function for output, by having the Generator in the foreach loop there. Each yielding becomes one iteration of the Generator.
I hope this shows how you can benefit from dividing your code into functions. Values that change should be put into variables. This is easily done by creating functions and using parameters for these values. You sort of extend the language to your own special needs, like creating select elements.
Is this possible to do in PHP since I cannot figure out how?
Yes it is possible to keep the values selected, by using the selected attribute on the option elements.
For instance, the <option> tag below contains that attribute:
<option value="value2" selected>Value 2</option>
If you care about XHTML validation, use selected="selected" - refer to this answer for more information.
<option value="value2" selected="selected">Value 2</option>
From the examples section of the MDN documentation for <select>, the following HTML is listed:
<!-- The second value will be selected initially -->
<select name="select"> <!--Supplement an id here instead of using 'name'-->
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
Rendering a select list with PHP
To achieve this with the PHP code, the selected attribute needs to be conditionally added to the option.
First, before the while loop, store the selected location in a variable:
$selectedLocation = '';
if (isset($_POST['location'])) {
//Get selected value from values submitted with form
//use $_GET if form is submitted via GET
$selectedLocation = $_POST['location'];
}
Then in the while loop, set that selected attribute when the matching option is found (i.e. when $selectedLocation == $row['description']).
while($row = mysqli_fetch_assoc()){
$selected = ''; //default to empty string - not selected
if ($selectedLocation == $row['description']) {
$selected = 'selected';
}
echo '<option value="' . htmlspecialchars($row['description']) . '" '.$selected.'>'
. htmlspecialchars($row['description'])
. '</option>';
}
See a demosntration of this in this phpfiddle.
Edit and try:
<select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
$selected = "";
if ($row['description'] == $location) {
$selected = " selected";
}
echo '<option value="' . htmlspecialchars($row['description']) . '"' . $selected . '>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
How would I go about setting the "selected" attribute to one of these boxes, based on what value is stored in the $genre variable?
i.e. If $genre == "Puzzle" then
<option value=Puzzle>
becomes
<option value=Puzzle selected>
Here is my current code:
<?php
$query = "SELECT * FROM release_dates WHERE id = $id";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$genre = $row['game_genre'];
?>
<select name=genre>
<option value=Action>Action</option>
<option value=Adventure>Adventure</option>
<option value=Puzzle>Puzzle</option>
<option value=RPG>RPG</option>
<option value=Horror>Horror</option>
<option value=Shooter>Shooter</option>
<option value=Simulator>Simulator</option>
<option value=Sport>Sport</option>
<option value=Strategy>Strategy</option>
</select>
Also, for extra brownie points, how would this apply to select boxes with the "multiple" attribute?
Any help or ideas would be greatly appreciated.
Well, that's pretty simple actually:
<option value=Action <?php $genre == "Action" ? "selected":""?> >Action</option>
Just use a ternary operator (condition) ? true:false to input "selected" if the value is set. Simply duplicate that logic on all the options:
<option value=Action <?php $genre == "Action" ? "selected":""?> >Action</option>
<option value=Adventure <?php $genre == "Adventure" ? "selected":""?> >Adventure</option>
<option value=Puzzle <?php $genre == "Puzzle" ? "selected":""?> >Puzzle</option>
<option value=RPG <?php $genre == "RPG" ? "selected":""?> >RPG</option>
Hope that helps!
You could use a foreach loop to iterate over your options, and each time, perform a check using an if statement to see if it matches:
foreach ($genres as $genre) {
if ($genre === "Puzzle") {
echo '<option value="'.$genre.'" selected>'.$genre.'</option>';
else {
echo '<option value="'.$genre.'">'.$genre.'</option>';
}
}
By the way, you shouldn't be using mysql_* functions anymore as they are unsafe, deprecated, and will be removed from PHP in the future. Take a look at PDO.
<option value="Strategy" <?php if($genre == "Strategy"){ echo 'selected="selected"';} ?> >Strategy</option>
I came up with a version that keeps everything in PHP
<?php
$query = "SELECT * FROM release_dates WHERE id = ". $id;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
// possible options
$genre_options = array(
'Action'
'Adventure'
'Puzzle'
'RPG'
'Horror'
'Shooter'
'Simulator'
'Sport'
'Strategy'
);
// loop over the options, and wrap them in tags
$options = '';
foreach ($genre_options as $genre) {
// check if we have a match
$selected = '';
if ($genre == $row['game_genre']) {
$selected = 'selected="selected"';
}
$options .= '<option value="'. $genre .'" '. $selected .'>'. $genre .'</option>'
}
echo '
<select name=genre>
'. $options .'
</select>
';
?>
What this does is create an array of possible genre's, loop over them, and see if any of them match the genre that was returned from the query. If thats the case it will add the selected="selected" attribute.
Unfortunately I'll be missing out on the "brownie points", because I'm not able to help you with the multi-select.
Let me know if this helps!
EDIT: I also noted that in your query you where passing the $id variable as a string. Fixed that in the query in my example.
Instead of defining your genres using plain HTML, create an array with all your genres.
To do so:
$genres = array(
"Action",
"Adventure",
"Puzzle",
"RPG",
"Horror",
"Shooter",
"Simulator",
"Sport",
"Strategy"
);
foreach($genres as $currentGenre) {
echo "<option value="'.$currentGenre.'" '.($currentGenre == $genre ? "selected" : "").'>'.$currentGenre.'</option>';
}
What this does, is loop over all your genres and create a single <option> for each of them. If the $currentGenre (so one of the genres from the array $genres) matches $genre (which you pulled from MySQL), it selects that option using a inline if-statement.
I have a drop down form item with four options.
<p>Priority:
<select required name=\"priority\">
<option default value=\"1\">1 - 10 days</option>
<option value=\"2\">2 - 5 days</option>
<option value=\"3\">3 - 48 hours</option>
<option value=\"4\">4 - 24 hours</option>
</select>
</p>
http://jsfiddle.net/2nmxN/
These values are already stored in the SQL database with either 1,2,3,4. The page I am working on is an edit page of sorts, so I would like to have whichever value is set in the database be selected on the drop down, so the user does not have to reselect the value upon submission. How can I get it to find the value and select the correct option depending what is set? I have no problem doing this with a text field like this:
echo "<p>Cost: <input required type=\"text\" name=\"cost\" value=\"".$cost."\">";
Do I have to do four different if statements for each value (if ($priority == 1) {...}) etc.?
If the options were stored in an associative array, you could write something like:
foreach ($options as $value => $label) {
echo '<option value="', $value, '"', ($dbValue == $value ? ' selected="selected"' : ''), '>', $label, '</option>';
}
You do not have to do four different if statements for each value. You have to do four if statements, one for each value.
foreach ($options as $value => $label)
{
if(isset($_POST['priority']) && $_POST['priority']==$value)
{
$selected = 'selected="selected"';
}
else
{
$selected='';
}
echo '<option value="'. $value. '" '.$selected.'>'. $label. '</option>';
}
here is my mysql and php code layout:
I have 3 tables
tableA stores unique "person" information
tableB stores unique "places" information
tableC stores not unique information about a person and places they have "beenTo".
here is how i layed out my form:
-one big form to insert into "person" tableA; "beenTo" tableC
in the form, a person mulitple selects "places" which get inserted into "beenTo"
my question is, when i am editing a "person" how do i display what the user has already selected to appear on my multiple select options drop down menu?
my drop down menu at the moment query "places" table and displays it in a multiple select drop down menu. its easier when a person have beenTo one place, the problem arrises when there is more than one "beenTo" places?
Foreach option, check if they have beenTo it. Then add the selected="selected" attribute to the tag if true.
Example:
<select multiple="multiple">
<option selected="selected">Rome</option>
<option>France</option>
<option selected="selected">Underpants</option>
</select>
And in PHP this might look like:
$beenTo = array("Rome","Underpants");
$places = array("Rome","France","Underpants");
?> <select multiple="multiple"> <?php
foreach($places as $place) {
echo "<option";
$found = false;
foreach($beenTo as $placeBeenTo) {
echo "value='$place'";
if ($placeBeenTo == $place) {
$found == true;
echo " selected=\"selected\" ";
break;
}
}
if (!$found) echo ">";
echo $place . "</option>";
}
?> </select> <?php
There's probably a much more efficient way to do this.
For clarification, you will want to have a name attribute for your select tag which allows for multiple selected options to function correctly.
<form method="post" action="">
<select name="places[]" multiple="multiple">
<?php
$_POST += array('places' => array());
$places = array('fr' => 'France', 'cn' => 'China', 'jp' => 'Japan');
$beenTo = array_flip($_POST['places']);
foreach ($places as $place => $place_label) {
$selected = isset($beenTo[$place]) ? ' selected="selected"' : '';
echo '<option value="' . $place . '"' . $selected . '>' . $place_label . '</option>';
}
?>
</select>
<input type="submit" value="Save Changes" />
</form>
<option id = 'example' <? if ($_POST['example']) echo 'selected' ?>>
But you'll be using a $_SERVER['cookies'] or other cache to store the past visits, not the $_POST array.. edit with extreme predjudice