Eric1978
Eric1978

Reputation: 83

PHP / HTML creating a dropdown for webshop categories with parent ID and childs

I am busy now making a webshop with different categories, and also different parent id's. My database structure is as follows:

id - name - parentid:

1 - games - 0

2 - movies - 0

3 - type - 1

4 - type - 2

5 - action - 3

6 - history - 4

Now in the admin part when i want to add a category, i want to show in a dropdown all my categories, but i want the parent and the childs separated. Is there an easy way to do this?

Greetings Eric

Upvotes: 0

Views: 543

Answers (1)

David
David

Reputation: 218827

I'm not sure what you mean by "want the parent ids and child ids separated." Understand that the elements in a select are nothing more than a display value and a data value, and the data value will be what gets sent to the server along with the field name.

So the select can't really distinguish between multiple kinds of data values. Each option can't have multiple IDs, for example. All you could do is format your display value to include IDs (such as you have with "1 - games - 0" and such), and decide which data value should be the value for that option in the select.

One thing you can do is group option elements, using the optgroup tag. Something like this:

<select name="myOptions">
  <optgroup label="Category 1">
    <option value="1">First Choice</option>
    <option value="2">Second Choice</option>
    <option value="3">Third Choice</option>
  </optgroup>
  <optgroup label="Category 2">
    <option value="4">Fourth Choice</option>
    <option value="5">Fifth Choice</option>
  </optgroup>
  <optgroup label="Category 3">
    <option value="6">Sixth Choice</option>
    <option value="7">Seventh Choice</option>
  </optgroup>
</select>

In validation, the browser shouldn't allow the user to select a group, they would have to select an actual option. So you shouldn't have to worry about that. This does present some additional flexibility in displaying your values more hierarchically. Understand, however, that only one level of option nesting is allowed in this case. (So an optgroup can't contain another optgroup.)

Upvotes: 1

Related Questions