473,382 Members | 1,657 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

populating parent-child menus from arrays

Hi!

I'm new to PHP and I have a question about generating parent-child drop down menus. I have seen many forums on how to generate them from databases, but not many from arrays. Let's say the user chooses between fruits and vegetables and chooses fruits, the second drop down menu should populate with a list of fruits. I've been stuck on this for a while now. Any help would be appreciated.

Thanks!=)
Jun 3 '09 #1
7 2675
Atli
5,058 Expert 4TB
Hi.

Whether the data is coming from a database or an array, the logic is basically the same. Just minor syntax differences.

Seeing as I am apparently not in a descriptive mood today (I'm trying to lay of the caffeine... again :P), I wrote a little example:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Set up the select data
  3. $items = array(
  4.     "Cars" => array("Ford", "Ferrari", "Toyota"),
  5.     "Bikes" => array("BMW", "Bikemaker 1", "Bikemaker 2")
  6. );
  7.  
  8. // Get the posted data, if any, or initialize as null
  9. ($type = @$_POST['Type']) or $type = null;
  10. ($item = @$_POST['Item']) or $item = null;
  11.  
  12. // Open the form element
  13. echo '<form action="?" method="post">';
  14.  
  15. // Print first select
  16. echo '<select name="Type" onchange="submit();">';
  17. echo '<option value="">- Please select -</option>';
  18.  
  19. foreach(array_keys($items) as $_type) {
  20.     // Check if this type was selected last submit
  21.     $selected = ($type == $_type ? 'selected="selected"' : '');
  22.  
  23.     // Print this type as an option
  24.     echo '<option value="'. $_type .'" '. $selected .'>'. $_type .'</option>';
  25. }
  26. echo '</select>';
  27.  
  28. // Print the second select
  29. echo '<select name="Item" onchange="submit();">';
  30. if($type) {
  31.     echo '<option value="">- Please select -</option>';
  32.  
  33.     foreach($items[$type] as $_item) {
  34.         // Check if this item was selected last submit
  35.         $selected = ($item == $_item ? 'selected="selected"' : '');
  36.  
  37.         // Print this item as an option
  38.         echo '<option value="'. $_item .'" '. $selected .'>'. $_item .'</option>';
  39.     }
  40. }
  41. else {
  42.      echo '<option value="" selected="selected">- Please select a type -</option>';
  43. }
  44. echo '</select>';
  45.  
  46. // Close the form element
  47. echo '</form>';
  48.  
  49. // Do something with the selected items
  50. if($type && $item) {
  51.     echo '<pre>You have selected: '. $type .'->'. $item .'</pre>';
  52. }
  53. ?>
Basically just prints a form with two selects, that is set to post data to itself.
When you select a type from the first box, the form is re-printed with the second box filled with item data.

The script starts of by trying to get the data from the two boxes.

Then it goes on to print the first select box, using the value from the first box, if it was sent.

And then it prints the second box, filling it with item data if a value from the first box was sent. Otherwise it is just empty.

And lastly, it uses the values sent from both boxes to print a message.
Jun 3 '09 #2
wow..thanks for the quick reply and your example was very very helpful.=) I got the drop down menu to work, but I was wondering how I would submit the two items to another page. In the end, I'm actually trying to write these two items to a textfile. So would I just use something along the lines of fwrite and use $type and $item when I tell it what to write? Thanks again for your help.=)
Jun 4 '09 #3
I also have a question about your coding. Right now, when it populates the second list you have it so that onchange="submit"(). I have also added an action to the form as well as a type box allowing the user to enter the number of hours they worked. Unfortunately, now that i have an action, as soon as i select the first DDL, it does the action. Is there any way to work around this so that the page doesnt submit until the user presses the submit button? Thanks again.
Jun 4 '09 #4
Atli
5,058 Expert 4TB
@phpnewbie26
At the end of the script I check if both values have been selected.
If that checks out, I print a message.

If you want to do something other than print a message, like say; write something to a file, that is where you would put the code.

Also, check out file_put_contents. Much easier than all those fopen functions.

Once that is done, it would also be a good idea to redirect someplace. Like a "thank you for whatever"page.
You can use the header function for that.
Expand|Select|Wrap|Line Numbers
  1. header('Location: welcomePage.php');
@phpnewbie26
If you want PHP to update the second DDL when the user chooses from the first one, you need to submit the form.

If there are other values in the form that you would like to preserve, you could always simply print them into the form again when PHP updates the second DDL.

Like:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Get POST values
  3. ($firstBox = @$_POST['fistBox']) or $firstBox = null;
  4. ($secondBox = @$_POST['secondBox']) or $secondBox = null;
  5. ($otherInput1 = @$_POST['otherInput1']) or $otherInput1 = null;
  6. ($otherInput2 = @$_POST['otherInput1']) or $otherInput2 = null;
  7.  
  8. // Print form
  9. echo '<form action="?" method="post">';
  10. echo '  <input type="text" name="otherInput1" value="', htmlentities($otherInput1), '" /><br />';
  11. echo '  <input type="text" name="otherInput2" value="', htmlentities($otherInput2), '" /><br />';
  12.  
  13. // Print your select boxes
  14. //... etc
  15. ?>
There are of course other alternatives, like AJAX.
That would allow you to update the second box without actually submitting the form.
Jun 4 '09 #5
I have got it working when I don't have an additional action in the beginning, but once I add that action in, it automatically does it as soon as I select from the first DDL. Am I supposed to put this action somewhere else in my coding? Right now it's at the very beginning looking like this:

Expand|Select|Wrap|Line Numbers
  1.  echo '<form action="submitted.php" method="post"> '; 
I want this submitted.php action to go when I click on the submit button at the bottom of the page. Is there a way I can do that? The purpose of the submitted.php page is so that the user can see what they have selected on another page and confirm that is what they want to submit. Thanks! =)
Jun 4 '09 #6
Atli
5,058 Expert 4TB
I see two posibilites here.

First
Change the action of the <form> in your PHP code, when the second box is filled.

Consider these facts:
  1. The action of the <form> needs to point to the current page in order for the first <select> to update the second <select>.
  2. When the first <select> is changed, submitting the page to itself, the PHP code prints the <form> elmement before filling the <select> boxes.
  3. The PHP code can check if the <select> boxes have had their values set.
You see where I am going with this?

When the PHP code prints the <form> element, have it check if the first <select> has been submitted with a value.
If it has, have it set the action to whichever page you want to data to eventually end up in.
If it has not, have it set the action to the current page.

Second
Always have the action of the <form> point to the current page, but use the header function to redirect (like I showed in my last post) when the <selects> have been filled and submitted.

I would prefer the first method, because it requires fewer requests, and doesn't require a manual redirect, but they both work.
Jun 4 '09 #7
hm..let me try processing that through my head and ill get bak to you. Right now, I have it so that after I ended the form once, I started it up back again just for the submit button and this form has the action as well, but the first one doesnt. But I just noticed that even if I dont select anything, the form still goes through when I press submit which it shouldnt. I'm also wondering if I do it this way, should I put the file writing coding before the submit button or after? Thanks again. You've been VERY helpful!
Jun 4 '09 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: John Hargrove | last post by:
I am building a database to manage test samples in an environmental laboratory. I am learning Access as I go and don't know much about the programming aspects. I hope to make the application...
2
by: Janus | last post by:
Hello. I need a little advice for populating the treeview control. I dont want my application to hang while populating the treeview, there is a lot of data what's the best approach? Maybe...
12
by: apoc69 | last post by:
hi people, i got stucked in my project and i just dont know how to continue. it's about puting business entities into the UI (web). first some simple example code how an entity looks like in...
0
by: Henry | last post by:
I have a dataset dsMain in which I have two tables The table period has columns like period_id, name, root_org_id.... The table organization has org_id, name, parent_id, hier_path, level,...
6
by: Chris Leuty | last post by:
I am populating a multiselect Listbox from a dataset, with the content of the listbox filled by one table, and the selections determined from another table. So far, I have been keeping the dataset...
5
by: | last post by:
Trying to learn about manipulating collections of objects, and populating these objects dynamically from datasources. Could someone post a code sample that shows the following: Instantiating a...
2
by: Unforgiven | last post by:
Hello All, I have the following query... SELECT Demographics.Full_Name, Demographics.Year_of_birth, Status.Status_OK, SUM(2004 - Demographics.Year_of_birth) AS Age FROM Demographics INNER...
2
by: Mike | last post by:
Hi all, I have a dataset that contains following records: id ref_id level -------------------------------------- A - 0 A1 A 1 A2 ...
3
by: pzh20 | last post by:
I have an unbound form/subform where I populate a combo box on the main form, and using the onchange event, display fields from a table in a datasheet subform. I want to add a new record via the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.