I've a select menu hardcoded in a wordpress (php) theme, but the manager requires to edit those frequently. Is it possible to populate the select dropdown options from a text file import? So he just has to edit the text file and the menu options would change.
The current menu looks like this:
<select name="location" id="sort-location" class="sort-dropdown">
<option value="" selected="selected">LOCATION:</option>
<option value="" disabled="">--------------</option>
<option value="hongkong">Hong Kong</option>
<option value="taiwan">Taiwan</option>
<option value="mainland_china">Mainland China</option>
<option value="" disabled="">--------------</option>
<option value="">SHOW ALL</option>
</select>
Sure -- make yourself a small loop that runs through the lines in the format you choose.
<?php
$select = file_get_contents('select.txt');
$lines = explode("\n", $select);
foreach ($lines as $line) {
// let's say our format is like this:
// value|name|selected|disabled
// or:
// -
// for separator
if ($line == '-') {
echo '<option disabled="disabled">----------</option>';
} else {
list($value, $name, $selected, $disabled) = explode("|",$line);
echo '<option value="'.$value.'"',
$selected?' selected="selected"':'',
$disabled?' disabled="disabled"':'',
'>'.$name.'</option>';
}
}
?>
Sure, just fetch the text file into an array using file() and create the select out of it. A very simple implementation: menu.txt:
hongkong Hong Kong
taiwan Taiwan
mainland_china Mainland China
Note the tabs between value and label.
Then in PHP:
$menu_items = file("menu.txt");
foreach ($menu_items as $menu_item)
{
// Explode
$menu_item_exploded = explode("\t", $menu_item);
$option_value = htmlspecialchars(trim($menu_item_exploded[0]));
$option_label = htmlspecialchars(trim($menu_item_exploded[1]));
echo "<option value='$option_value'>$option_label</option>";
}
As far as I can see, you have the following left to solve:
How to pre-set a predefined value (You need to echo selected in the right item)
How to deal with the user editing out a value from the text file that was pre-set in your select.
Error handling if the file is not existent or not accessible
Error handling if the user screws up the line breaks, or something similar - maybe count the lines, and/or detect whether there are tabs inside the file
Related
I have a php drop down list which retrieves locations from a database, it gets all the data correctly, but sometimes if two records has the same in the database, it will add the item twice in the drop down. This is a location drop down, and some locations are duplicates, i would like to know what code can i add to remove duplicate entries and just keep one.
Here is my code:
<label for="select-service">
<strong>Enter a Location:</strong>
</label>
<select class="form-control" id="select-location" class="col-xs-12 col-sm-4 form-control" required>
<option value="">Select Location</option>
<?php
foreach($appointment_locations as $location) {
$LocationsArray = explode(",", $location->notes);
foreach($LocationsArray as $singleLocation):
?>
<option value="<?=$singleLocation ?>"><?=$singleLocation ?></option>
<? endforeach;
};?>
</select>
EDIT:
Here is the output
I tried using foreach(array_unique($appointment_locations) as $location) { but it doesnt show my second provider when i click on the location Rosebank
1) validate your inserted data to avoid such a situations
2) why you do not group by your retrieved data from database?
if you do not have access to do this, you can try a simple solution rather than the array_unique solution
$tmp = [];
foreach ($repeatedLocations as $location) {
if (isset($tmp[$location]) == false) {
// do your stuff
$tmp[$location] = true;
}
}
unset($tmp);
try
foreach(array_unique($appointment_locations) as $location) {
//... code
or
$LocationsArray = array_unique(explode(",", $location->notes));
https://www.php.net/manual/en/function.array-unique.php
<select name="size_select" class="long form-control">
<option selected="selected" value="">Please select</option>
<option value="6 (xxs)" title="6 (XXS)">6 (XXS)</option>
<option value="8 (xs)" title="8 (XS)">8 (XS)</option>
<option value="10 (s)" title="10 (S)">10 (S)</option>
<option value="12 (m)" title="12 (M)">12 (M)</option>
<option value="14 (l)" title="14 (L)">14 (L)</option>
<option value="16 (xl)" title="16 (XL)">16 (XL)</option>
<option value="18 (xxl)" title="18 (XXL)">18 (XXL)</option>
<option value="20 (xxxl)" title="20 (XXXL)">20 (XXXL)</option>
How to get all value in this select?
$element = $html->find('#sizeDdl',0);
foreach($element as $elemen) {
echo ($elemen->plaintext);
}
I try this output:
Notice: Trying to get property of non-object in /h2/home/website/website.com/test.php on line 11
The idea is that each individual value should be taken and recorded in SQL base. Now is a common result , not every value separately
First add id in select tag as
<select name="size_select" id="sizeDdl" class="long form-control">
then change these lines
$element = $html->find('#sizeDdl',0);
foreach($element as $elemen) {
echo ($elemen->plaintext);
}
to these:
$text_array = array();
$html = "Your html";
foreach($html->find('#sizeDdl') as $element) {
$options = $element->find('option');
foreach($options as $element1) {
$text_array[] = ($element1->plaintext);
}
}
var_dump($text_array);
print_r(text_array);
change this line
<select name="size_select" class="long form-control">
to this line
<select name="size_select" id="sizeDdl" class="long form-control">
as your dom element should have id attribute which u r using in javascript and missing in html.
There is two issues with your current code.
1) You are trying to fetch an element by an id that does not exist.
2) You are iterating through a list of elements, not its children.
Either find the element by name or give it an id (sizeDbl) and iterate its children (the options) instead.
You could also modify the selector to select a list of the children instead of the select itself:
$options = $html->find('#sizeDdl option');
or
$options = $html->find('#sizeDbl')->find('option');
for getting select values with simple html dom
just try this code it will help you
$element = $html->find('#selectIDGoesHere',0)->find('option');
foreach($element as $elemen) {
echo "Display text:".($elemen->plaintext)."<br>";
echo "value:".($elemen->value)."<br>";
}
Consider this snippet from select form:
<select name="cat_id"">
<option value="33">Apple</option>
<option value="44">Banana</option>
<option value="48">Carrot</option>
<option value="50">Dew</option>
<option value="77">Eggplant</option>
<option value="84">Fern</option>
<option value="92">Grass</option>
</select>
Is there a way, using SIMPLE DOM, I can extract the value="x" for specific string.
Example, I want to get the value of Dew, hence, I must be able to get 50
Tried searching and playing, but cannot find exact answer:
Parsing drop down menu with php simple dom <-- But values doesn't start from 0 nor increments uniformly
php , simple_html_dom.php, get selected option <-- I do not even have selected entry in the select form
I need to get the value for specific string so that I can use it to send form using cURL.
Hope, somebody can help. Thanks in advance and more power.
The following code will parse all option nodes and when the searched text is matched, it will display the corresponding value and ends:
$input = <<<_DATA_
<select name="cat_id">
<option value="33">Apple</option>
<option value="44">Banana</option>
<option value="48">Carrot</option>
<option value="50">Dew</option>
<option value="77">Eggplant</option>
<option value="84">Fern</option>
<option value="92">Grass</option>
</select>
_DATA_;
// Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load($input);
// searched text
$searchText = 'dew';
// Create a regex pattern (match $searchText followed OR preceded by any number of spaces/tabs/newLines ...)
// i flag stands for case insensitive match
$pattern = '/\s*'.$searchText.'\s*/i';
foreach( $html->find('select[name="cat_id"] option') as $option ){
echo $string = $option->plaintext;
// Check if the current node contains the searched text
if( preg_match($pattern, $string) ){
$value = $option->value;
echo ' => ' . $value;
// Exit the loop when done
break;
}
echo '<br>';
}
OUTPUT
Apple
Banana
Carrot
Dew => 50
I have a standard select box in my php form for my website containing a list of counties in the UK, an example of which is shown below:
<p class='form_title'>County<br>
<select id="county" name="county">
<optgroup label="England">
<option>Bedfordshire</option>
<option>Berkshire</option>
<option>Bristol</option>
....
<option>Wiltshire</option>
<option>Worcestershire</option>
</optgroup>
<optgroup label="Wales">
<option>Anglesey</option>
...
<option>Radnorshire</option>
</optgroup>
<optgroup label="Scotland">
<option>Aberdeenshire</option>
...
<option>Wigtownshire</option>
</optgroup>
<optgroup label="Northern Ireland">
<option>Antrim</option>
...
<option>Tyrone</option>
</optgroup>
</select>
</p>
Once a user has submitted details, they can then edit them.
I therefore need a way to have selected the option that they previously chose, given that I have the option they chose saved in word form, such as Bedfordshire.
I know I need to add the word selected to one of the options, but I was wondering if there was a better way to do it than a massive case statement.
Thanks
You should set an option value for each option to track the value.
Also you should be generating that from a database and then you can set selected based on a $_GET or $_POST:
for example:
foreach($county as $name){
$selected = '';
if($name == $_GET['name']){
$selected = ' selected="selected"';
}
echo '<option value="'.$name.'"'.$selected.'>'.$name.'</option>';
}
this doesn't include your optgroup but that also should come from database.
Try something like this:
foreach($places as $place) {
$selected = $prevSelectionId == $place['id'] ? " selected='selected' " : "";
echo "<option $selected value='".$place['id']."'>".$place['name']."</option>";
}
</select>
If I have a line like this,
<option value="someval">somval</option>
how can I position the cursor after the last quotation of value and put something like abcdef?
So the output would be
<option value="somval" abcdef>somval</option>
with PHP?
I want to do this dynamically and I can't figure out how to do it. I'm looking at strpos(), but I don't see how it can be done. I'll be posting a bunch of option tags into a textbox and code will be generated. so I'll have a lot of option fields.
#martin - Say I have a huge dropdown and each option lists a country that exists. Rather than having to manually type out something like this:
$query = $db->query("my query....");
while($row = $db->fetch($query)) {
<select name="thename">
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
... Followed by 100 more, because there are a lot of locations to list.
</select>
How can I post all the options I have into a textbox and have the above code automatically generated to save a lot of time?
Using your example you would do:
while($row = $db->fetch($query)) {
printf('<option value="someval"%s>someval</option>',
($row['someval'] == 'someval') ? ' selected="selected" ' : '');
}
This would go through the rows and output an option, replacing the %s with the attribute selected="selected" if $row['someval'] is equal to someval. However, the above is rather pointless, because all option elements will have the same value and text, so try
while($row = $db->fetch($query)) {
printf('<option value="%s"%s>%s</option>',
$row['country-code'],
($row['country-code'] === $selection) ? ' selected="selected" ' : '',
row['country-name']);
}
With $selection being anything you want to compare against. Replace the keys in $row with appropriate keys from in your database.
Note: The usual disclaimers about securing your output apply
You could capture (value=".+?") and replace it with $0 abcdef.
<?php
$string = '<option value="someval">someval</option>';
print preg_replace("/(value=\".+?\")/i", "$0 abcdef", $string);
?>
Which outputs the following:
<option value="someval" abcdef>someval</option>
With PHP, you can generate a whole string with any text you wish. Where do you have your original string? In a variable or a text file?