populating parent-child menus from arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • phpnewbie26
    New Member
    • Jun 2009
    • 52

    #1

    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!=)
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    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:
    [code=php]<?php
    // Set up the select data
    $items = array(
    "Cars" => array("Ford", "Ferrari", "Toyota"),
    "Bikes" => array("BMW", "Bikemaker 1", "Bikemaker 2")
    );

    // Get the posted data, if any, or initialize as null
    ($type = @$_POST['Type']) or $type = null;
    ($item = @$_POST['Item']) or $item = null;

    // Open the form element
    echo '<form action="?" method="post">' ;

    // Print first select
    echo '<select name="Type" onchange="submi t();">';
    echo '<option value="">- Please select -</option>';

    foreach(array_k eys($items) as $_type) {
    // Check if this type was selected last submit
    $selected = ($type == $_type ? 'selected="sele cted"' : '');

    // Print this type as an option
    echo '<option value="'. $_type .'" '. $selected .'>'. $_type .'</option>';
    }
    echo '</select>';

    // Print the second select
    echo '<select name="Item" onchange="submi t();">';
    if($type) {
    echo '<option value="">- Please select -</option>';

    foreach($items[$type] as $_item) {
    // Check if this item was selected last submit
    $selected = ($item == $_item ? 'selected="sele cted"' : '');

    // Print this item as an option
    echo '<option value="'. $_item .'" '. $selected .'>'. $_item .'</option>';
    }
    }
    else {
    echo '<option value="" selected="selec ted">- Please select a type -</option>';
    }
    echo '</select>';

    // Close the form element
    echo '</form>';

    // Do something with the selected items
    if($type && $item) {
    echo '<pre>You have selected: '. $type .'->'. $item .'</pre>';
    }
    ?>[/code]
    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.

    Comment

    • phpnewbie26
      New Member
      • Jun 2009
      • 52

      #3
      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.=)

      Comment

      • phpnewbie26
        New Member
        • Jun 2009
        • 52

        #4
        I also have a question about your coding. Right now, when it populates the second list you have it so that onchange="submi t"(). 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.

        Comment

        • Atli
          Recognized Expert Expert
          • Nov 2006
          • 5062

          #5
          Originally posted by phpnewbie26
          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.=)
          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_conten ts. 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.
          [code=php]header('Locatio n: welcomePage.php ');[/code]

          Originally posted by phpnewbie26
          I also have a question about your coding. Right now, when it populates the second list you have it so that onchange="submi t"(). 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.
          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:
          [code=php]<?php
          // Get POST values
          ($firstBox = @$_POST['fistBox']) or $firstBox = null;
          ($secondBox = @$_POST['secondBox']) or $secondBox = null;
          ($otherInput1 = @$_POST['otherInput1']) or $otherInput1 = null;
          ($otherInput2 = @$_POST['otherInput1']) or $otherInput2 = null;

          // Print form
          echo '<form action="?" method="post">' ;
          echo ' <input type="text" name="otherInpu t1" value="', htmlentities($o therInput1), '" /><br />';
          echo ' <input type="text" name="otherInpu t2" value="', htmlentities($o therInput2), '" /><br />';

          // Print your select boxes
          //... etc
          ?>[/code]
          There are of course other alternatives, like AJAX.
          That would allow you to update the second box without actually submitting the form.

          Comment

          • phpnewbie26
            New Member
            • Jun 2009
            • 52

            #6
            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:

            Code:
             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! =)

            Comment

            • Atli
              Recognized Expert Expert
              • Nov 2006
              • 5062

              #7
              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.

              Comment

              • phpnewbie26
                New Member
                • Jun 2009
                • 52

                #8
                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!

                Comment

                Working...